From 57d9c5066e2fc28d3e89b1bd9fd3ee98e27c4c48 Mon Sep 17 00:00:00 2001 From: Gunnar Mills Date: Fri, 14 Sep 2018 14:42:34 -0500 Subject: clang-format: Update to match docs repo Update the .clang-format file and run clang-format-6.0. This .clang-format matches the example one in https://github.com/openbmc/docs/blob/master/cpp-style-and-conventions.md#clang-formatting Change-Id: Ia331c9a5b040e1a3c45a0ebf1b8d776d93b05ae5 Signed-off-by: Gunnar Mills --- .clang-format | 98 ++++++++++ argument.cpp | 29 ++- argument.hpp | 75 ++++---- config_parser.cpp | 32 ++-- config_parser.hpp | 104 ++++++----- dhcp_configuration.cpp | 15 +- dhcp_configuration.hpp | 160 ++++++++--------- dns_updater.cpp | 13 +- dns_updater.hpp | 7 +- ethernet_interface.cpp | 255 ++++++++++++-------------- ethernet_interface.hpp | 375 +++++++++++++++++++-------------------- ipaddress.cpp | 44 +++-- ipaddress.hpp | 73 ++++---- ncsi_netlink_main.cpp | 16 +- ncsi_util.cpp | 119 +++++-------- ncsi_util.hpp | 7 +- network_config.cpp | 23 ++- network_config.hpp | 8 +- network_manager.cpp | 53 +++--- network_manager.hpp | 189 ++++++++++---------- network_manager_main.cpp | 35 ++-- routing_table.cpp | 48 +++-- routing_table.hpp | 117 ++++++------ rtnetlink_server.cpp | 37 ++-- rtnetlink_server.hpp | 39 ++-- system_configuration.cpp | 41 ++--- system_configuration.hpp | 84 +++++---- test/mock_syscall.cpp | 33 ++-- test/test_config_parser.cpp | 52 +++--- test/test_dns_updater.cpp | 65 +++---- test/test_ethernet_interface.cpp | 208 ++++++++++------------ test/test_network_manager.cpp | 90 +++++----- test/test_rtnetlink.cpp | 116 ++++++------ test/test_util.cpp | 54 +++--- test/test_vlan_interface.cpp | 157 ++++++++-------- test/test_watch.cpp | 86 +++++---- timer.cpp | 18 +- timer.hpp | 148 +++++++-------- types.hpp | 13 +- util.cpp | 144 +++++++-------- util.hpp | 117 ++++++------ vlan_interface.cpp | 38 ++-- vlan_interface.hpp | 89 +++++----- watch.cpp | 34 ++-- watch.hpp | 145 ++++++++------- 45 files changed, 1796 insertions(+), 1907 deletions(-) create mode 100644 .clang-format diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..8c5278e --- /dev/null +++ b/.clang-format @@ -0,0 +1,98 @@ +--- +Language: Cpp +# BasedOnStyle: LLVM +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +AlignEscapedNewlinesLeft: false +AlignOperands: true +AlignTrailingComments: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: true +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: true + AfterControlStatement: true + AfterEnum: true + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + IndentBraces: false +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: AfterColon +ColumnLimit: 80 +CommentPragmas: '^ IWYU pragma:' +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] +IncludeBlocks: Regroup +IncludeCategories: + - Regex: '^[<"](gtest|gmock)' + Priority: 5 + - Regex: '^"config.h"' + Priority: -1 + - Regex: '^".*\.hpp"' + Priority: 1 + - Regex: '^<.*\.h>' + Priority: 2 + - Regex: '^<.*' + Priority: 3 + - Regex: '.*' + Priority: 4 +IndentCaseLabels: true +IndentWidth: 4 +IndentWrappedFunctionNames: true +KeepEmptyLinesAtTheStartOfBlocks: true +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBlockIndentWidth: 2 +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakString: 1000 +PenaltyExcessCharacter: 1000000 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Left +ReflowComments: true +SortIncludes: true +SortUsingDeclarations: true +SpaceAfterCStyleCast: false +SpaceBeforeAssignmentOperators: true +SpaceBeforeParens: ControlStatements +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: true +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp11 +TabWidth: 4 +UseTab: Never +... diff --git a/argument.cpp b/argument.cpp index 6d4bb1a..bcd5a13 100644 --- a/argument.cpp +++ b/argument.cpp @@ -70,23 +70,23 @@ void ArgumentParser::usage(char** argv) std::cerr << " --help Print this menu.\n"; std::cerr << " --info= Retrieve info about NCSI topology.\n"; std::cerr << " --set= Set a specific package/channel.\n"; - std::cerr << " --clear= Clear all the settings on the interface.\n"; + std::cerr + << " --clear= Clear all the settings on the interface.\n"; std::cerr << " --package= Specify a package.\n"; std::cerr << " --channel= Specify a channel.\n"; std::cerr << " --index= Specify device ifindex.\n"; std::cerr << std::flush; } -const option ArgumentParser::options[] = -{ - { "info", no_argument, NULL, 'i' }, - { "set", no_argument, NULL, 's' }, - { "clear", no_argument, NULL, 'r' }, - { "package", required_argument, NULL, 'p' }, - { "channel", required_argument, NULL, 'c' }, - { "index", required_argument, NULL, 'x' }, - { "help", no_argument, NULL, 'h' }, - { 0, 0, 0, 0}, +const option ArgumentParser::options[] = { + {"info", no_argument, NULL, 'i'}, + {"set", no_argument, NULL, 's'}, + {"clear", no_argument, NULL, 'r'}, + {"package", required_argument, NULL, 'p'}, + {"channel", required_argument, NULL, 'c'}, + {"index", required_argument, NULL, 'x'}, + {"help", no_argument, NULL, 'h'}, + {0, 0, 0, 0}, }; const char* ArgumentParser::optionStr = "i:s:r:p:c:x:h?"; @@ -94,7 +94,6 @@ const char* ArgumentParser::optionStr = "i:s:r:p:c:x:h?"; const std::string ArgumentParser::trueString = "true"; const std::string ArgumentParser::emptyString = ""; -} //namespace ncsi -} //namespace network -} //namespece phosphor - +} // namespace ncsi +} // namespace network +} // namespace phosphor diff --git a/argument.hpp b/argument.hpp index 94fdbd6..28e5ce3 100644 --- a/argument.hpp +++ b/argument.hpp @@ -16,54 +16,53 @@ namespace ncsi */ class ArgumentParser { - public: - ArgumentParser() = delete; - ~ArgumentParser() = default; - ArgumentParser(const ArgumentParser&) = delete; - ArgumentParser& operator=(const ArgumentParser&) = delete; - ArgumentParser(ArgumentParser&&) = default; - ArgumentParser& operator=(ArgumentParser&&) = default; + public: + ArgumentParser() = delete; + ~ArgumentParser() = default; + ArgumentParser(const ArgumentParser&) = delete; + ArgumentParser& operator=(const ArgumentParser&) = delete; + ArgumentParser(ArgumentParser&&) = default; + ArgumentParser& operator=(ArgumentParser&&) = default; - /** @brief Constructs Argument object - * - * @param argc - the main function's argc passed as is - * @param argv - the main function's argv passed as is - * @return Object constructed - */ - ArgumentParser(int argc, char** argv); + /** @brief Constructs Argument object + * + * @param argc - the main function's argc passed as is + * @param argv - the main function's argv passed as is + * @return Object constructed + */ + ArgumentParser(int argc, char** argv); - /** @brief Given an option, returns its argument(optarg) - * - * @param opt - command line option string - * - * @return argument which is a standard optarg - */ - const std::string& operator[](const std::string& opt); + /** @brief Given an option, returns its argument(optarg) + * + * @param opt - command line option string + * + * @return argument which is a standard optarg + */ + const std::string& operator[](const std::string& opt); - /** @brief Displays usage - * - * @param argv - the main function's argv passed as is - */ - static void usage(char** argv); + /** @brief Displays usage + * + * @param argv - the main function's argv passed as is + */ + static void usage(char** argv); - /** @brief Set to 'true' when an option is passed */ - static const std::string trueString; + /** @brief Set to 'true' when an option is passed */ + static const std::string trueString; - /** @brief Set to '' when an option is not passed */ - static const std::string emptyString; + /** @brief Set to '' when an option is not passed */ + static const std::string emptyString; - private: - /** @brief Option to argument mapping */ - std::map arguments; + private: + /** @brief Option to argument mapping */ + std::map arguments; - /** @brief Array of struct options as needed by getopt_long */ - static const option options[]; + /** @brief Array of struct options as needed by getopt_long */ + static const option options[]; - /** @brief optstring as needed by getopt_long */ - static const char* optionStr; + /** @brief optstring as needed by getopt_long */ + static const char* optionStr; }; } // namespace ncsi } // namespace network } // namespace phosphor - diff --git a/config_parser.cpp b/config_parser.cpp index 92c344f..c4af404 100644 --- a/config_parser.cpp +++ b/config_parser.cpp @@ -22,8 +22,8 @@ Parser::Parser(const fs::path& filePath) setFile(filePath); } - -std::tuple Parser::getSection(const std::string& section) +std::tuple + Parser::getSection(const std::string& section) { auto it = sections.find(section); if (it == sections.end()) @@ -40,7 +40,7 @@ std::tuple Parser::getValues(const std::string& section, const std::string& key) { ValueList values; - KeyValueMap keyValues {}; + KeyValueMap keyValues{}; auto rc = ReturnCode::SUCCESS; std::tie(rc, keyValues) = getSection(section); @@ -63,7 +63,6 @@ std::tuple Parser::getValues(const std::string& section, return std::make_tuple(ReturnCode::SUCCESS, std::move(values)); } - bool Parser::isValueExist(const std::string& section, const std::string& key, const std::string& value) { @@ -124,26 +123,17 @@ void Parser::setFile(const fs::path& filePath) { return; } - //clear all the section data. + // clear all the section data. sections.clear(); parse(stream); stream.close(); - } +} void Parser::parse(std::istream& in) { - static const std::regex commentRegex - { - R"x(\s*[;#])x" - }; - static const std::regex sectionRegex - { - R"x(\s*\[([^\]]+)\])x" - }; - static const std::regex valueRegex - { - R"x(\s*(\S[^ \t=]*)\s*=\s*(\S+)\s*$)x" - }; + static const std::regex commentRegex{R"x(\s*[;#])x"}; + static const std::regex sectionRegex{R"x(\s*\[([^\]]+)\])x"}; + static const std::regex valueRegex{R"x(\s*(\S[^ \t=]*)\s*=\s*(\S+)\s*$)x"}; std::string section; std::smatch pieces; for (std::string line; std::getline(in, line);) @@ -169,6 +159,6 @@ void Parser::parse(std::istream& in) } } -}//namespace config -}//namespace network -}//namespace phosphor +} // namespace config +} // namespace network +} // namespace phosphor diff --git a/config_parser.hpp b/config_parser.hpp index 34b2a68..164d3c3 100644 --- a/config_parser.hpp +++ b/config_parser.hpp @@ -15,7 +15,7 @@ namespace config { using Section = std::string; -using KeyValueMap = std::multimap; +using KeyValueMap = std::multimap; using ValueList = std::vector; namespace fs = std::experimental::filesystem; @@ -29,73 +29,69 @@ enum class ReturnCode class Parser { - public: + public: + Parser() = default; - Parser() = default; + /** @brief Constructor + * @param[in] fileName - Absolute path of the file which will be parsed. + */ - /** @brief Constructor - * @param[in] fileName - Absolute path of the file which will be parsed. - */ + Parser(const fs::path& fileName); - Parser(const fs::path& fileName); + /** @brief Get the values of the given key and section. + * @param[in] section - section name. + * @param[in] key - key to look for. + * @returns the tuple of return code and the + * values associated with the key. + */ - /** @brief Get the values of the given key and section. - * @param[in] section - section name. - * @param[in] key - key to look for. - * @returns the tuple of return code and the - * values associated with the key. - */ + std::tuple getValues(const std::string& section, + const std::string& key); - std::tuple getValues( - const std::string& section, - const std::string& key); + /** @brief Set the value of the given key and section. + * @param[in] section - section name. + * @param[in] key - key name. + * @param[in] value - value. + */ - /** @brief Set the value of the given key and section. - * @param[in] section - section name. - * @param[in] key - key name. - * @param[in] value - value. - */ + void setValue(const std::string& section, const std::string& key, + const std::string& value); - void setValue(const std::string& section, const std::string& key, - const std::string& value); - - - /** @brief Set the file name and parse it. - * @param[in] fileName - Absolute path of the file. - */ + /** @brief Set the file name and parse it. + * @param[in] fileName - Absolute path of the file. + */ - void setFile(const fs::path& fileName); + void setFile(const fs::path& fileName); - private: + private: + /** @brief Parses the given file and fills the data. + * @param[in] stream - inputstream. + */ - /** @brief Parses the given file and fills the data. - * @param[in] stream - inputstream. - */ + void parse(std::istream& stream); - void parse(std::istream& stream); + /** @brief Get all the key values of the given section. + * @param[in] section - section name. + * @returns the tuple of return code and the map of (key,value). + */ - /** @brief Get all the key values of the given section. - * @param[in] section - section name. - * @returns the tuple of return code and the map of (key,value). - */ + std::tuple getSection(const std::string& section); - std::tuple getSection(const std::string& section); + /** @brief checks that whether the value exist in the + * given section. + * @param[in] section - section name. + * @param[in] key - key name. + * @param[in] value - value. + * @returns true if exist otherwise false. + */ - /** @brief checks that whether the value exist in the - * given section. - * @param[in] section - section name. - * @param[in] key - key name. - * @param[in] value - value. - * @returns true if exist otherwise false. - */ - - bool isValueExist(const std::string& section, const std::string& key, - const std::string& value); + bool isValueExist(const std::string& section, const std::string& key, + const std::string& value); - std::unordered_map sections; - fs::path filePath; + std::unordered_map sections; + fs::path filePath; }; -}//namespace config -}//namespce network -}//namespace phosphor +} // namespace config +} // namespace network +} // namespace phosphor diff --git a/dhcp_configuration.cpp b/dhcp_configuration.cpp index 7451ef6..e492156 100644 --- a/dhcp_configuration.cpp +++ b/dhcp_configuration.cpp @@ -1,6 +1,7 @@ +#include "config.h" + #include "dhcp_configuration.hpp" -#include "config.h" #include "network_manager.hpp" #include @@ -59,7 +60,6 @@ bool Configuration::nTPEnabled(bool value) return ntp; } - bool Configuration::dNSEnabled(bool value) { if (value == dNSEnabled()) @@ -81,7 +81,7 @@ bool Configuration::getDHCPPropFromConf(const std::string& prop) // get the first interface name, we need it to know config file name. auto interface = *interfaceStrList.begin(); auto fileName = systemd::config::networkFilePrefix + interface + - systemd::config::networkFileSuffix; + systemd::config::networkFileSuffix; confPath /= fileName; // systemd default behaviour is all DHCP fields should be enabled by @@ -96,8 +96,7 @@ bool Configuration::getDHCPPropFromConf(const std::string& prop) if (rc != config::ReturnCode::SUCCESS) { log("Unable to get the value from section DHCP", - entry("PROP=%s", prop.c_str()), - entry("RC=%d", rc)); + entry("PROP=%s", prop.c_str()), entry("RC=%d", rc)); return propValue; } @@ -107,6 +106,6 @@ bool Configuration::getDHCPPropFromConf(const std::string& prop) } return propValue; } -}// namespace dhcp -}// namespace network -}// namespace phosphor +} // namespace dhcp +} // namespace network +} // namespace phosphor diff --git a/dhcp_configuration.hpp b/dhcp_configuration.hpp index 56a9fda..cc2083e 100644 --- a/dhcp_configuration.hpp +++ b/dhcp_configuration.hpp @@ -20,9 +20,7 @@ namespace dhcp using ConfigIntf = sdbusplus::xyz::openbmc_project::Network::server::DHCPConfiguration; -using Iface = - sdbusplus::server::object::object; - +using Iface = sdbusplus::server::object::object; /** @class Configuration * @brief DHCP configuration. @@ -31,86 +29,82 @@ using Iface = */ class Configuration : public Iface { - public: - Configuration() = default; - Configuration(const Configuration&) = delete; - Configuration& operator=(const Configuration&) = delete; - Configuration(Configuration&&) = delete; - Configuration& operator=(Configuration&&) = delete; - virtual ~Configuration() = default; - - /** @brief Constructor to put object onto bus at a dbus path. - * @param[in] bus - Bus to attach to. - * @param[in] objPath - Path to attach at. - * @param[in] parent - Parent object. - */ - Configuration(sdbusplus::bus::bus& bus, - const std::string& objPath, - Manager& parent) : - Iface(bus, objPath.c_str(), true), - bus(bus), - manager(parent) - { - ConfigIntf::dNSEnabled(getDHCPPropFromConf("UseDNS")); - ConfigIntf::nTPEnabled(getDHCPPropFromConf("UseNTP")); - ConfigIntf::hostNameEnabled(getDHCPPropFromConf("UseHostname")); - ConfigIntf::sendHostNameEnabled(getDHCPPropFromConf("SendHostname")); - emit_object_added(); - } - - /** @brief If true then DNS servers received from the DHCP server - * will be used and take precedence over any statically - * configured ones. - * @param[in] value - true if DNS server needed from DHCP server - * else false. - */ - bool dNSEnabled(bool value) override; - - /** @brief If true then NTP servers received from the DHCP server - will be used by systemd-timesyncd. - * @param[in] value - true if NTP server needed from DHCP server - * else false. - */ - bool nTPEnabled(bool value) override; - - /** @brief If true then Hostname received from the DHCP server will - * be set as the hostname of the system - * @param[in] value - true if hostname needed from the DHCP server - * else false. - * - */ - bool hostNameEnabled(bool value) override; - - /** @brief if true then it will cause an Option 12 field, i.e machine's - * hostname, will be included in the DHCP packet. - * @param[in] value - true if machine's host name needs to be included - * in the DHCP packet. - */ - bool sendHostNameEnabled(bool value) override; - - /** @brief read the DHCP Prop value from the configuration file - * @param[in] prop - DHCP Prop name. - */ - bool getDHCPPropFromConf(const std::string& prop); - - /* @brief Network Manager needed the below function to know the - * value of the properties (ntpEnabled,dnsEnabled,hostnameEnabled - sendHostNameEnabled). - * - */ - using ConfigIntf::dNSEnabled; - using ConfigIntf::nTPEnabled; - using ConfigIntf::hostNameEnabled; - using ConfigIntf::sendHostNameEnabled; - - private: - - /** @brief sdbusplus DBus bus connection. */ - sdbusplus::bus::bus& bus; - - /** @brief Network Manager object. */ - phosphor::network::Manager& manager; - + public: + Configuration() = default; + Configuration(const Configuration&) = delete; + Configuration& operator=(const Configuration&) = delete; + Configuration(Configuration&&) = delete; + Configuration& operator=(Configuration&&) = delete; + virtual ~Configuration() = default; + + /** @brief Constructor to put object onto bus at a dbus path. + * @param[in] bus - Bus to attach to. + * @param[in] objPath - Path to attach at. + * @param[in] parent - Parent object. + */ + Configuration(sdbusplus::bus::bus& bus, const std::string& objPath, + Manager& parent) : + Iface(bus, objPath.c_str(), true), + bus(bus), manager(parent) + { + ConfigIntf::dNSEnabled(getDHCPPropFromConf("UseDNS")); + ConfigIntf::nTPEnabled(getDHCPPropFromConf("UseNTP")); + ConfigIntf::hostNameEnabled(getDHCPPropFromConf("UseHostname")); + ConfigIntf::sendHostNameEnabled(getDHCPPropFromConf("SendHostname")); + emit_object_added(); + } + + /** @brief If true then DNS servers received from the DHCP server + * will be used and take precedence over any statically + * configured ones. + * @param[in] value - true if DNS server needed from DHCP server + * else false. + */ + bool dNSEnabled(bool value) override; + + /** @brief If true then NTP servers received from the DHCP server + will be used by systemd-timesyncd. + * @param[in] value - true if NTP server needed from DHCP server + * else false. + */ + bool nTPEnabled(bool value) override; + + /** @brief If true then Hostname received from the DHCP server will + * be set as the hostname of the system + * @param[in] value - true if hostname needed from the DHCP server + * else false. + * + */ + bool hostNameEnabled(bool value) override; + + /** @brief if true then it will cause an Option 12 field, i.e machine's + * hostname, will be included in the DHCP packet. + * @param[in] value - true if machine's host name needs to be included + * in the DHCP packet. + */ + bool sendHostNameEnabled(bool value) override; + + /** @brief read the DHCP Prop value from the configuration file + * @param[in] prop - DHCP Prop name. + */ + bool getDHCPPropFromConf(const std::string& prop); + + /* @brief Network Manager needed the below function to know the + * value of the properties (ntpEnabled,dnsEnabled,hostnameEnabled + sendHostNameEnabled). + * + */ + using ConfigIntf::dNSEnabled; + using ConfigIntf::hostNameEnabled; + using ConfigIntf::nTPEnabled; + using ConfigIntf::sendHostNameEnabled; + + private: + /** @brief sdbusplus DBus bus connection. */ + sdbusplus::bus::bus& bus; + + /** @brief Network Manager object. */ + phosphor::network::Manager& manager; }; } // namespace dhcp diff --git a/dns_updater.cpp b/dns_updater.cpp index e98cc4a..bf29fff 100644 --- a/dns_updater.cpp +++ b/dns_updater.cpp @@ -1,7 +1,7 @@ -#include "dns_updater.hpp" - #include "config.h" +#include "dns_updater.hpp" + #include #include #include @@ -17,8 +17,7 @@ namespace dns namespace updater { -void updateDNSEntries(const fs::path& inFile, - const fs::path& outFile) +void updateDNSEntries(const fs::path& inFile, const fs::path& outFile) { using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; @@ -44,10 +43,10 @@ void updateDNSEntries(const fs::path& inFile, for (std::string line; std::getline(inStream, line);) { auto index = line.find("DNS="); - if(index != std::string::npos) + if (index != std::string::npos) { - auto dns = line.substr(index + 4); - outStream << "nameserver " << dns << "\n" ; + auto dns = line.substr(index + 4); + outStream << "nameserver " << dns << "\n"; } } return; diff --git a/dns_updater.hpp b/dns_updater.hpp index 84646c6..32cbb1b 100644 --- a/dns_updater.hpp +++ b/dns_updater.hpp @@ -20,8 +20,7 @@ constexpr auto RESOLV_CONF = "/etc/resolv.conf"; * @param[in] inFile - File having DNS entries supplied by DHCP * @param[in] outFile - File to write the nameserver entries to */ -void updateDNSEntries(const fs::path& inFile, - const fs::path& outFile); +void updateDNSEntries(const fs::path& inFile, const fs::path& outFile); /** @brief User callback handler invoked by inotify watcher * @@ -35,7 +34,7 @@ inline void processDNSEntries(const fs::path& inFile) return updateDNSEntries(inFile, RESOLV_CONF); } -} // namepsace updater -} // namepsace dns +} // namespace updater +} // namespace dns } // namespace network } // namespace phosphor diff --git a/ethernet_interface.cpp b/ethernet_interface.cpp index 04f9009..19dfec4 100644 --- a/ethernet_interface.cpp +++ b/ethernet_interface.cpp @@ -1,6 +1,7 @@ +#include "config.h" + #include "ethernet_interface.hpp" -#include "config.h" #include "config_parser.hpp" #include "ipaddress.hpp" #include "network_manager.hpp" @@ -36,13 +37,10 @@ using Argument = xyz::openbmc_project::Common::InvalidArgument; EthernetInterface::EthernetInterface(sdbusplus::bus::bus& bus, const std::string& objPath, - bool dhcpEnabled, - Manager& parent, + bool dhcpEnabled, Manager& parent, bool emitSignal) : - Ifaces(bus, objPath.c_str(), true), - bus(bus), - manager(parent), - objPath(objPath) + Ifaces(bus, objPath.c_str(), true), + bus(bus), manager(parent), objPath(objPath) { auto intfName = objPath.substr(objPath.rfind("/") + 1); std::replace(intfName.begin(), intfName.end(), '_', '.'); @@ -84,34 +82,24 @@ void EthernetInterface::createIPAddressObjects() { origin = IP::AddressOrigin::LinkLocal; } - gateway = routingTable.getGateway(addr.addrType, addr.ipaddress, addr.prefix); - - std::string ipAddressObjectPath = generateObjectPath(addressType, - addr.ipaddress, - addr.prefix, - gateway); - - this->addrs.emplace( - addr.ipaddress, - std::make_shared( - bus, - ipAddressObjectPath.c_str(), - *this, - addressType, - addr.ipaddress, - origin, - addr.prefix, - gateway)); + gateway = + routingTable.getGateway(addr.addrType, addr.ipaddress, addr.prefix); + + std::string ipAddressObjectPath = generateObjectPath( + addressType, addr.ipaddress, addr.prefix, gateway); + + this->addrs.emplace(addr.ipaddress, + std::make_shared( + bus, ipAddressObjectPath.c_str(), *this, + addressType, addr.ipaddress, origin, + addr.prefix, gateway)); origin = IP::AddressOrigin::Static; } - } -void EthernetInterface::iP(IP::Protocol protType, - std::string ipaddress, - uint8_t prefixLength, - std::string gateway) +void EthernetInterface::iP(IP::Protocol protType, std::string ipaddress, + uint8_t prefixLength, std::string gateway) { if (dHCPEnabled()) @@ -121,7 +109,6 @@ void EthernetInterface::iP(IP::Protocol protType, dHCPEnabled(false); } - IP::AddressOrigin origin = IP::AddressOrigin::Static; int addressFamily = (protType == IP::Protocol::IPv4) ? AF_INET : AF_INET6; @@ -146,32 +133,21 @@ void EthernetInterface::iP(IP::Protocol protType, { log("PrefixLength is not correct "), entry("PREFIXLENGTH=%d", gateway.c_str()); - elog(Argument::ARGUMENT_NAME("prefixLength"), - Argument::ARGUMENT_VALUE(std::to_string( - prefixLength).c_str())); - } - - - std::string objectPath = generateObjectPath(protType, - ipaddress, - prefixLength, - gateway); - this->addrs.emplace( - ipaddress, - std::make_shared( - bus, - objectPath.c_str(), - *this, - protType, - ipaddress, - origin, - prefixLength, - gateway)); + elog( + Argument::ARGUMENT_NAME("prefixLength"), + Argument::ARGUMENT_VALUE(std::to_string(prefixLength).c_str())); + } + + std::string objectPath = + generateObjectPath(protType, ipaddress, prefixLength, gateway); + this->addrs.emplace(ipaddress, + std::make_shared( + bus, objectPath.c_str(), *this, protType, ipaddress, + origin, prefixLength, gateway)); manager.writeToConfigurationFile(); } - /* Note: We don't have support for ethtool now will enable this code once we bring the ethtool @@ -182,11 +158,17 @@ TODO: https://github.com/openbmc/openbmc/issues/1484 InterfaceInfo EthernetInterface::getInterfaceInfo() const { int sock{-1}; - struct ifreq ifr{0}; - struct ethtool_cmd edata{0}; - LinkSpeed speed {0}; - Autoneg autoneg {0}; - DuplexMode duplex {0}; + struct ifreq ifr + { + 0 + }; + struct ethtool_cmd edata + { + 0 + }; + LinkSpeed speed{0}; + Autoneg autoneg{0}; + DuplexMode duplex{0}; do { sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); @@ -207,13 +189,11 @@ InterfaceInfo EthernetInterface::getInterfaceInfo() const log("ioctl failed for SIOCETHTOOL:", entry("ERROR=%s", strerror(errno))); break; - } speed = edata.speed; duplex = edata.duplex; autoneg = edata.autoneg; - } - while (0); + } while (0); if (sock) { @@ -226,11 +206,13 @@ InterfaceInfo EthernetInterface::getInterfaceInfo() const * @return macaddress on success */ -std::string EthernetInterface::getMACAddress( - const std::string& interfaceName) const +std::string + EthernetInterface::getMACAddress(const std::string& interfaceName) const { - struct ifreq ifr{}; - char macAddress[mac_address::size] {}; + struct ifreq ifr + { + }; + char macAddress[mac_address::size]{}; int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if (sock < 0) @@ -244,14 +226,14 @@ std::string EthernetInterface::getMACAddress( if (ioctl(sock, SIOCGIFHWADDR, &ifr) != 0) { log("ioctl failed for SIOCGIFHWADDR:", - entry("ERROR=%s", strerror(errno))); + entry("ERROR=%s", strerror(errno))); return macAddress; } snprintf(macAddress, mac_address::size, mac_address::format, - ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], - ifr.ifr_hwaddr.sa_data[2], ifr.ifr_hwaddr.sa_data[3], - ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]); + ifr.ifr_hwaddr.sa_data[0], ifr.ifr_hwaddr.sa_data[1], + ifr.ifr_hwaddr.sa_data[2], ifr.ifr_hwaddr.sa_data[3], + ifr.ifr_hwaddr.sa_data[4], ifr.ifr_hwaddr.sa_data[5]); return macAddress; } @@ -266,8 +248,7 @@ std::string EthernetInterface::generateId(const std::string& ipaddress, hashString += gateway; // Only want 8 hex digits. - hexId << std::hex << ((std::hash {}( - hashString)) & 0xFFFFFFFF); + hexId << std::hex << ((std::hash{}(hashString)) & 0xFFFFFFFF); return hexId.str(); } @@ -316,7 +297,6 @@ void EthernetInterface::deleteVLANFromSystem(const std::string& interface) { commit(); } - } void EthernetInterface::deleteVLANObject(const std::string& interface) @@ -325,7 +305,7 @@ void EthernetInterface::deleteVLANObject(const std::string& interface) if (it == vlanInterfaces.end()) { log("DeleteVLANObject:Unable to find the object", - entry("INTERFACE=%s",interface.c_str())); + entry("INTERFACE=%s", interface.c_str())); return; } @@ -336,10 +316,9 @@ void EthernetInterface::deleteVLANObject(const std::string& interface) manager.writeToConfigurationFile(); } -std::string EthernetInterface::generateObjectPath(IP::Protocol addressType, - const std::string& ipaddress, - uint8_t prefixLength, - const std::string& gateway) const +std::string EthernetInterface::generateObjectPath( + IP::Protocol addressType, const std::string& ipaddress, + uint8_t prefixLength, const std::string& gateway) const { std::string type = convertForMessage(addressType); type = type.substr(type.rfind('.') + 1); @@ -393,8 +372,7 @@ ServerList EthernetInterface::getNameServerFromConf() fs::path confPath = manager.getConfDir(); std::string fileName = systemd::config::networkFilePrefix + - interfaceName() + - systemd::config::networkFileSuffix; + interfaceName() + systemd::config::networkFileSuffix; confPath /= fileName; ServerList servers; config::Parser parser(confPath.string()); @@ -421,7 +399,7 @@ void EthernetInterface::writeDNSEntries(const ServerList& dnsList, } outStream << "### Generated manually via dbus settings ###\n"; - for(const auto& server : dnsList) + for (const auto& server : dnsList) { outStream << "nameserver " << server << "\n"; } @@ -429,24 +407,18 @@ void EthernetInterface::writeDNSEntries(const ServerList& dnsList, void EthernetInterface::loadVLAN(VlanId id) { - std::string vlanInterfaceName = interfaceName() + "." + - std::to_string(id); + std::string vlanInterfaceName = interfaceName() + "." + std::to_string(id); std::string path = objPath; path += "_" + std::to_string(id); - auto dhcpEnabled = getDHCPValue(manager.getConfDir().string(), - vlanInterfaceName); + auto dhcpEnabled = + getDHCPValue(manager.getConfDir().string(), vlanInterfaceName); auto vlanIntf = std::make_unique( - bus, - path.c_str(), - dhcpEnabled, - id, - *this, - manager); - - // Fetch the ip address from the system - // and create the dbus object. + bus, path.c_str(), dhcpEnabled, id, *this, manager); + + // Fetch the ip address from the system + // and create the dbus object. vlanIntf->createIPAddressObjects(); this->vlanInterfaces.emplace(std::move(vlanInterfaceName), @@ -455,25 +427,17 @@ void EthernetInterface::loadVLAN(VlanId id) void EthernetInterface::createVLAN(VlanId id) { - std::string vlanInterfaceName = interfaceName() + "." + - std::to_string(id); + std::string vlanInterfaceName = interfaceName() + "." + std::to_string(id); std::string path = objPath; path += "_" + std::to_string(id); - auto vlanIntf = std::make_unique( - bus, - path.c_str(), - false, - id, - *this, - manager); + bus, path.c_str(), false, id, *this, manager); // write the device file for the vlan interface. vlanIntf->writeDeviceFile(); - this->vlanInterfaces.emplace(vlanInterfaceName, - std::move(vlanIntf)); + this->vlanInterfaces.emplace(vlanInterfaceName, std::move(vlanIntf)); // write the new vlan device entry to the configuration(network) file. manager.writeToConfigurationFile(); } @@ -482,8 +446,8 @@ ServerList EthernetInterface::getNTPServersFromConf() { fs::path confPath = manager.getConfDir(); - std::string fileName = systemd::config::networkFilePrefix + interfaceName() + - systemd::config::networkFileSuffix; + std::string fileName = systemd::config::networkFilePrefix + + interfaceName() + systemd::config::networkFileSuffix; confPath /= fileName; ServerList servers; @@ -502,7 +466,7 @@ ServerList EthernetInterface::getNTPServersFromConf() ServerList EthernetInterface::nTPServers(ServerList servers) { - auto ntpServers = EthernetInterfaceIntf::nTPServers(servers); + auto ntpServers = EthernetInterfaceIntf::nTPServers(servers); writeConfigurationFile(); // timesynchd reads the NTP server configuration from the @@ -526,15 +490,15 @@ void EthernetInterface::writeConfigurationFile() // if there is vlan interafce then write the configuration file // for vlan also. - for (const auto& intf: vlanInterfaces) + for (const auto& intf : vlanInterfaces) { intf.second->writeConfigurationFile(); } fs::path confPath = manager.getConfDir(); - std::string fileName = systemd::config::networkFilePrefix + interfaceName() + - systemd::config::networkFileSuffix; + std::string fileName = systemd::config::networkFilePrefix + + interfaceName() + systemd::config::networkFileSuffix; confPath /= fileName; std::fstream stream; @@ -547,13 +511,17 @@ void EthernetInterface::writeConfigurationFile() } // Write the device - stream << "[" << "Match" << "]\n"; + stream << "[" + << "Match" + << "]\n"; stream << "Name=" << interfaceName() << "\n"; auto addrs = getAddresses(); // write the network section - stream << "[" << "Network" << "]\n"; + stream << "[" + << "Network" + << "]\n"; #ifdef LINK_LOCAL_AUTOCONFIGURATION stream << "LinkLocalAddressing=yes\n"; #else @@ -562,10 +530,10 @@ void EthernetInterface::writeConfigurationFile() stream << "IPv6AcceptRA=false\n"; // Add the VLAN entry - for (const auto& intf: vlanInterfaces) + for (const auto& intf : vlanInterfaces) { stream << "VLAN=" << intf.second->EthernetInterface::interfaceName() - << "\n"; + << "\n"; } // Add the DHCP entry auto value = dHCPEnabled() ? "true"s : "false"s; @@ -575,13 +543,13 @@ void EthernetInterface::writeConfigurationFile() // in config file. if (dHCPEnabled() == false) { - //Add the NTP server + // Add the NTP server for (const auto& ntp : EthernetInterfaceIntf::nTPServers()) { stream << "NTP=" << ntp << "\n"; } - //Add the DNS entry + // Add the DNS entry for (const auto& dns : EthernetInterfaceIntf::nameservers()) { stream << "DNS=" << dns << "\n"; @@ -596,8 +564,9 @@ void EthernetInterface::writeConfigurationFile() #endif ) { - std::string address = addr.second->address() + "/" + - std::to_string(addr.second->prefixLength()); + std::string address = + addr.second->address() + "/" + + std::to_string(addr.second->prefixLength()); stream << "Address=" << address << "\n"; } @@ -614,20 +583,21 @@ void EthernetInterface::writeConfigurationFile() { if (addr.second->origin() == AddressOrigin::Static) { - int addressFamily = addr.second->type() == IP::Protocol::IPv4 ? - AF_INET : AF_INET6; + int addressFamily = addr.second->type() == IP::Protocol::IPv4 + ? AF_INET + : AF_INET6; - std::string destination = getNetworkID( - addressFamily, - addr.second->address(), - addr.second->prefixLength()); + std::string destination = + getNetworkID(addressFamily, addr.second->address(), + addr.second->prefixLength()); if (addr.second->gateway() != "0.0.0.0" && - addr.second->gateway() != "" && - destination != "0.0.0.0" && + addr.second->gateway() != "" && destination != "0.0.0.0" && destination != "") { - stream << "[" << "Route" << "]\n"; + stream << "[" + << "Route" + << "]\n"; stream << "Gateway=" << addr.second->gateway() << "\n"; stream << "Destination=" << destination << "\n"; } @@ -672,7 +642,7 @@ std::string EthernetInterface::mACAddress(std::string value) if (!mac_address::validate(value)) { log("MACAddress is not valid.", - entry("MAC=%s", value.c_str())); + entry("MAC=%s", value.c_str())); elog(Argument::ARGUMENT_NAME("MACAddress"), Argument::ARGUMENT_VALUE(value.c_str())); } @@ -683,7 +653,7 @@ std::string EthernetInterface::mACAddress(std::string value) if (!(intMac ^ mac_address::broadcastMac)) { log("MACAddress is a broadcast mac.", - entry("MAC=%s", value.c_str())); + entry("MAC=%s", value.c_str())); elog(Argument::ARGUMENT_NAME("MACAddress"), Argument::ARGUMENT_VALUE(value.c_str())); } @@ -705,17 +675,18 @@ std::string EthernetInterface::mACAddress(std::string value) try { auto inventoryMac = mac_address::getfromInventory(bus); - auto intInventoryMac = mac_address::internal::convertToInt(inventoryMac); + auto intInventoryMac = + mac_address::internal::convertToInt(inventoryMac); if (intInventoryMac != intMac) { log("Given MAC address is neither a local Admin " - "type nor is same as in inventory"); + "type nor is same as in inventory"); elog(Argument::ARGUMENT_NAME("MACAddress"), Argument::ARGUMENT_VALUE(value.c_str())); } } - catch(InternalFailure& e) + catch (InternalFailure& e) { log("Exception occurred during getting of MAC " "address from Inventory"); @@ -724,18 +695,18 @@ std::string EthernetInterface::mACAddress(std::string value) } auto interface = interfaceName(); execute("/sbin/fw_setenv", "fw_setenv", "ethaddr", value.c_str()); - //TODO: would replace below three calls + // TODO: would replace below three calls // with restarting of systemd-netwokd // through https://github.com/systemd/systemd/issues/6696 execute("/sbin/ip", "ip", "link", "set", "dev", interface.c_str(), "down"); - execute("/sbin/ip", "ip", "link", "set", "dev", interface.c_str(), "address", - value.c_str()); + execute("/sbin/ip", "ip", "link", "set", "dev", interface.c_str(), + "address", value.c_str()); execute("/sbin/ip", "ip", "link", "set", "dev", interface.c_str(), "up"); auto mac = MacAddressIntf::mACAddress(std::move(value)); - //update all the vlan interfaces - for(const auto& intf: vlanInterfaces) + // update all the vlan interfaces + for (const auto& intf : vlanInterfaces) { intf.second->updateMacAddress(); } @@ -747,16 +718,14 @@ std::string EthernetInterface::mACAddress(std::string value) restartSystemdUnit(networkdService); } return mac; - } void EthernetInterface::deleteAll() { - if(EthernetInterfaceIntf::dHCPEnabled()) + if (EthernetInterfaceIntf::dHCPEnabled()) { log("DHCP enabled on the interface"), - entry("INTERFACE=%s", interfaceName().c_str()); - + entry("INTERFACE=%s", interfaceName().c_str()); } // clear all the ip on the interface @@ -764,5 +733,5 @@ void EthernetInterface::deleteAll() manager.writeToConfigurationFile(); } -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/ethernet_interface.hpp b/ethernet_interface.hpp index 7865ab3..8dad0e9 100644 --- a/ethernet_interface.hpp +++ b/ethernet_interface.hpp @@ -17,12 +17,11 @@ namespace phosphor namespace network { -using Ifaces = - sdbusplus::server::object::object< - sdbusplus::xyz::openbmc_project::Network::server::EthernetInterface, - sdbusplus::xyz::openbmc_project::Network::server::MACAddress, - sdbusplus::xyz::openbmc_project::Network::IP::server::Create, - sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll>; +using Ifaces = sdbusplus::server::object::object< + sdbusplus::xyz::openbmc_project::Network::server::EthernetInterface, + sdbusplus::xyz::openbmc_project::Network::server::MACAddress, + sdbusplus::xyz::openbmc_project::Network::IP::server::Create, + sdbusplus::xyz::openbmc_project::Collection::server::DeleteAll>; using IP = sdbusplus::xyz::openbmc_project::Network::server::IP; @@ -50,7 +49,8 @@ using VlanId = uint32_t; using InterfaceName = std::string; using InterfaceInfo = std::tuple; using AddressMap = std::map>; -using VlanInterfaceMap = std::map>; +using VlanInterfaceMap = + std::map>; /** @class EthernetInterface * @brief OpenBMC Ethernet Interface implementation. @@ -59,187 +59,186 @@ using VlanInterfaceMap = std::map> */ class EthernetInterface : public Ifaces { - public: - EthernetInterface() = delete; - EthernetInterface(const EthernetInterface&) = delete; - EthernetInterface& operator=(const EthernetInterface&) = delete; - EthernetInterface(EthernetInterface&&) = delete; - EthernetInterface& operator=(EthernetInterface&&) = delete; - virtual ~EthernetInterface() = default; - - /** @brief Constructor to put object onto bus at a dbus path. - * @param[in] bus - Bus to attach to. - * @param[in] objPath - Path to attach at. - * @param[in] dhcpEnabled - is dhcp enabled(true/false). - * @param[in] parent - parent object. - * @param[in] emitSignal - true if the object added signal needs to be - * send. - */ - EthernetInterface(sdbusplus::bus::bus& bus, - const std::string& objPath, - bool dhcpEnabled, - Manager& parent, - bool emitSignal = true); - - /** @brief Function to create ipaddress dbus object. - * @param[in] addressType - Type of ip address. - * @param[in] ipaddress- IP address. - * @param[in] prefixLength - Length of prefix. - * @param[in] gateway - Gateway ip address. - */ - - void iP(IP::Protocol addressType, - std::string ipaddress, - uint8_t prefixLength, - std::string gateway) override; - - /* @brief delete the dbus object of the given ipaddress. - * @param[in] ipaddress - IP address. - */ - void deleteObject(const std::string& ipaddress); - - /* @brief delete the vlan dbus object of the given interface. - * Also deletes the device file and the network file. - * @param[in] interface - VLAN Interface. - */ - void deleteVLANObject(const std::string& interface); - - /* @brief creates the dbus object(IPaddres) given in the address list. - * @param[in] addrs - address list for which dbus objects needs - * to create. - */ - void createIPAddressObjects(); - - /* @brief Gets all the ip addresses. - * @returns the list of ipaddress. - */ - const AddressMap& getAddresses() const { return addrs; } - - /** Set value of DHCPEnabled */ - bool dHCPEnabled(bool value) override; - - /** @brief sets the MAC address. - * @param[in] value - MAC address which needs to be set on the system. - * @returns macAddress of the interface or throws an error. - */ - std::string mACAddress(std::string value) override; - - /** @brief sets the NTP servers. - * @param[in] value - vector of NTP servers. - */ - ServerList nTPServers(ServerList value) override; - - /** @brief sets the DNS/nameservers. - * @param[in] value - vector of DNS servers. - */ - ServerList nameservers(ServerList value) override; - - /** @brief create Vlan interface. - * @param[in] id- VLAN identifier. - */ - void createVLAN(VlanId id); - - /** @brief load the vlan info from the system - * and creates the ip address dbus objects. - * @param[in] vlanID- VLAN identifier. - */ - void loadVLAN(VlanId vlanID); - - /** @brief write the network conf file with the in-memory objects. - */ - void writeConfigurationFile(); - - /** @brief delete all dbus objects. - */ - void deleteAll(); - - using EthernetInterfaceIntf::dHCPEnabled; - using EthernetInterfaceIntf::interfaceName; - using MacAddressIntf::mACAddress; - - /** @brief Absolute path of the resolv conf file */ - static constexpr auto resolvConfFile = "/etc/resolv.conf"; - - protected: - /** @brief get the info of the ethernet interface. - * @return tuple having the link speed,autonegotiation,duplexmode . - */ - InterfaceInfo getInterfaceInfo() const; - - /* @brief delete the vlan interface from system. - * @param[in] interface - vlan Interface. - */ - void deleteVLANFromSystem(const std::string& interface); - - /** @brief get the mac address of the interface. - * @param[in] interfaceName - Network interface name. - * @return macaddress on success - */ - - std::string getMACAddress(const std::string& interfaceName) const; - - /** @brief construct the ip address dbus object path. - * @param[in] addressType - Type of ip address. - * @param[in] ipaddress - IP address. - * @param[in] prefixLength - Length of prefix. - * @param[in] gateway - Gateway address. - - * @return path of the address object. - */ - - std::string generateObjectPath(IP::Protocol addressType, - const std::string& ipaddress, - uint8_t prefixLength, - const std::string& gateway) const; - - /** @brief generates the id by doing hash of ipaddress, - * prefixlength and the gateway. - * @param[in] ipaddress - IP address. - * @param[in] prefixLength - Length of prefix. - * @param[in] gateway - Gateway address. - * @return hash string. - */ - - static std::string generateId(const std::string& ipaddress, - uint8_t prefixLength, - const std::string& gateway); - - /** @brief write the dhcp section **/ - void writeDHCPSection(std::fstream& stream);; - - /** @brief get the NTP server list from the network conf - * - */ - ServerList getNTPServersFromConf(); - - /** @brief write the DNS entries to resolver file. - * @param[in] dnsList - DNS server list which needs to be written. - * @param[in] file - File to write the name server entries to. - */ - void writeDNSEntries(const ServerList& dnsList, - const std::string& file); - - /** @brief get the name server details from the network conf - * - */ - ServerList getNameServerFromConf(); - - /** @brief Persistent sdbusplus DBus bus connection. */ - sdbusplus::bus::bus& bus; - - /** @brief Network Manager object. */ - Manager& manager; - - /** @brief Persistent map of IPAddress dbus objects and their names */ - AddressMap addrs; - - /** @brief Persistent map of VLAN interface dbus objects and their names */ - VlanInterfaceMap vlanInterfaces; - - /** @brief Dbus object path */ - std::string objPath; - - friend class TestEthernetInterface; + public: + EthernetInterface() = delete; + EthernetInterface(const EthernetInterface&) = delete; + EthernetInterface& operator=(const EthernetInterface&) = delete; + EthernetInterface(EthernetInterface&&) = delete; + EthernetInterface& operator=(EthernetInterface&&) = delete; + virtual ~EthernetInterface() = default; + + /** @brief Constructor to put object onto bus at a dbus path. + * @param[in] bus - Bus to attach to. + * @param[in] objPath - Path to attach at. + * @param[in] dhcpEnabled - is dhcp enabled(true/false). + * @param[in] parent - parent object. + * @param[in] emitSignal - true if the object added signal needs to be + * send. + */ + EthernetInterface(sdbusplus::bus::bus& bus, const std::string& objPath, + bool dhcpEnabled, Manager& parent, + bool emitSignal = true); + + /** @brief Function to create ipaddress dbus object. + * @param[in] addressType - Type of ip address. + * @param[in] ipaddress- IP address. + * @param[in] prefixLength - Length of prefix. + * @param[in] gateway - Gateway ip address. + */ + + void iP(IP::Protocol addressType, std::string ipaddress, + uint8_t prefixLength, std::string gateway) override; + + /* @brief delete the dbus object of the given ipaddress. + * @param[in] ipaddress - IP address. + */ + void deleteObject(const std::string& ipaddress); + + /* @brief delete the vlan dbus object of the given interface. + * Also deletes the device file and the network file. + * @param[in] interface - VLAN Interface. + */ + void deleteVLANObject(const std::string& interface); + + /* @brief creates the dbus object(IPaddres) given in the address list. + * @param[in] addrs - address list for which dbus objects needs + * to create. + */ + void createIPAddressObjects(); + + /* @brief Gets all the ip addresses. + * @returns the list of ipaddress. + */ + const AddressMap& getAddresses() const + { + return addrs; + } + + /** Set value of DHCPEnabled */ + bool dHCPEnabled(bool value) override; + + /** @brief sets the MAC address. + * @param[in] value - MAC address which needs to be set on the system. + * @returns macAddress of the interface or throws an error. + */ + std::string mACAddress(std::string value) override; + + /** @brief sets the NTP servers. + * @param[in] value - vector of NTP servers. + */ + ServerList nTPServers(ServerList value) override; + + /** @brief sets the DNS/nameservers. + * @param[in] value - vector of DNS servers. + */ + ServerList nameservers(ServerList value) override; + + /** @brief create Vlan interface. + * @param[in] id- VLAN identifier. + */ + void createVLAN(VlanId id); + + /** @brief load the vlan info from the system + * and creates the ip address dbus objects. + * @param[in] vlanID- VLAN identifier. + */ + void loadVLAN(VlanId vlanID); + + /** @brief write the network conf file with the in-memory objects. + */ + void writeConfigurationFile(); + + /** @brief delete all dbus objects. + */ + void deleteAll(); + + using EthernetInterfaceIntf::dHCPEnabled; + using EthernetInterfaceIntf::interfaceName; + using MacAddressIntf::mACAddress; + + /** @brief Absolute path of the resolv conf file */ + static constexpr auto resolvConfFile = "/etc/resolv.conf"; + + protected: + /** @brief get the info of the ethernet interface. + * @return tuple having the link speed,autonegotiation,duplexmode . + */ + InterfaceInfo getInterfaceInfo() const; + + /* @brief delete the vlan interface from system. + * @param[in] interface - vlan Interface. + */ + void deleteVLANFromSystem(const std::string& interface); + + /** @brief get the mac address of the interface. + * @param[in] interfaceName - Network interface name. + * @return macaddress on success + */ + + std::string getMACAddress(const std::string& interfaceName) const; + + /** @brief construct the ip address dbus object path. + * @param[in] addressType - Type of ip address. + * @param[in] ipaddress - IP address. + * @param[in] prefixLength - Length of prefix. + * @param[in] gateway - Gateway address. + + * @return path of the address object. + */ + + std::string generateObjectPath(IP::Protocol addressType, + const std::string& ipaddress, + uint8_t prefixLength, + const std::string& gateway) const; + + /** @brief generates the id by doing hash of ipaddress, + * prefixlength and the gateway. + * @param[in] ipaddress - IP address. + * @param[in] prefixLength - Length of prefix. + * @param[in] gateway - Gateway address. + * @return hash string. + */ + + static std::string generateId(const std::string& ipaddress, + uint8_t prefixLength, + const std::string& gateway); + + /** @brief write the dhcp section **/ + void writeDHCPSection(std::fstream& stream); + ; + + /** @brief get the NTP server list from the network conf + * + */ + ServerList getNTPServersFromConf(); + + /** @brief write the DNS entries to resolver file. + * @param[in] dnsList - DNS server list which needs to be written. + * @param[in] file - File to write the name server entries to. + */ + void writeDNSEntries(const ServerList& dnsList, const std::string& file); + + /** @brief get the name server details from the network conf + * + */ + ServerList getNameServerFromConf(); + + /** @brief Persistent sdbusplus DBus bus connection. */ + sdbusplus::bus::bus& bus; + + /** @brief Network Manager object. */ + Manager& manager; + + /** @brief Persistent map of IPAddress dbus objects and their names */ + AddressMap addrs; + + /** @brief Persistent map of VLAN interface dbus objects and their names */ + VlanInterfaceMap vlanInterfaces; + + /** @brief Dbus object path */ + std::string objPath; + + friend class TestEthernetInterface; }; } // namespace network diff --git a/ipaddress.cpp b/ipaddress.cpp index 8693123..43433e2 100644 --- a/ipaddress.cpp +++ b/ipaddress.cpp @@ -1,6 +1,7 @@ +#include "config.h" + #include "ipaddress.hpp" -#include "config.h" #include "ethernet_interface.hpp" #include "util.hpp" @@ -16,28 +17,23 @@ namespace network using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; -IPAddress::IPAddress(sdbusplus::bus::bus& bus, - const char* objPath, - EthernetInterface& parent, - IP::Protocol type, - const std::string& ipaddress, - IP::AddressOrigin origin, - uint8_t prefixLength, - const std::string& gateway): - IPIfaces(bus, objPath, true), - parent(parent) +IPAddress::IPAddress(sdbusplus::bus::bus& bus, const char* objPath, + EthernetInterface& parent, IP::Protocol type, + const std::string& ipaddress, IP::AddressOrigin origin, + uint8_t prefixLength, const std::string& gateway) : + IPIfaces(bus, objPath, true), + parent(parent) { - this->address(ipaddress); - this->prefixLength(prefixLength); - this->gateway(gateway); - this->type(type); - this->origin(origin); - - // Emit deferred signal. - emit_object_added(); + this->address(ipaddress); + this->prefixLength(prefixLength); + this->gateway(gateway); + this->type(type); + this->origin(origin); + + // Emit deferred signal. + emit_object_added(); } - void IPAddress::delete_() { if (parent.dHCPEnabled()) @@ -51,8 +47,8 @@ void IPAddress::delete_() if (isLinkLocalIP(address())) { log("Can not delete the LinkLocal address"), - entry("INTERFACE=%s ADDRESS=%s", - parent.interfaceName().c_str(), address().c_str()); + entry("INTERFACE=%s ADDRESS=%s", parent.interfaceName().c_str(), + address().c_str()); return; } #endif @@ -60,5 +56,5 @@ void IPAddress::delete_() parent.deleteObject(address()); } -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/ipaddress.hpp b/ipaddress.hpp index 7ffb769..b0e77fb 100644 --- a/ipaddress.hpp +++ b/ipaddress.hpp @@ -11,10 +11,9 @@ namespace phosphor namespace network { -using IPIfaces = - sdbusplus::server::object::object< - sdbusplus::xyz::openbmc_project::Network::server::IP, - sdbusplus::xyz::openbmc_project::Object::server::Delete>; +using IPIfaces = sdbusplus::server::object::object< + sdbusplus::xyz::openbmc_project::Network::server::IP, + sdbusplus::xyz::openbmc_project::Object::server::Delete>; using IP = sdbusplus::xyz::openbmc_project::Network::server::IP; @@ -28,42 +27,36 @@ class EthernetInterface; */ class IPAddress : public IPIfaces { - public: - IPAddress() = delete; - IPAddress(const IPAddress&) = delete; - IPAddress& operator=(const IPAddress&) = delete; - IPAddress(IPAddress&&) = delete; - IPAddress& operator=(IPAddress &&) = delete; - virtual ~IPAddress() = default; - - /** @brief Constructor to put object onto bus at a dbus path. - * @param[in] bus - Bus to attach to. - * @param[in] objPath - Path to attach at. - * @param[in] parent - Parent object. - * @param[in] type - ipaddress type(v4/v6). - * @param[in] ipAddress - ipadress. - * @param[in] origin - origin of ipaddress(dhcp/static/SLAAC/LinkLocal). - * @param[in] prefixLength - Length of prefix. - * @param[in] gateway - gateway address. - */ - IPAddress(sdbusplus::bus::bus& bus, - const char* objPath, - EthernetInterface& parent, - IP::Protocol type, - const std::string& ipAddress, - IP::AddressOrigin origin, - uint8_t prefixLength, - const std::string& gateway); - - /** @brief Delete this d-bus object. - */ - void delete_() override; - - private: - - /** @brief Parent Object. */ - EthernetInterface& parent; - + public: + IPAddress() = delete; + IPAddress(const IPAddress&) = delete; + IPAddress& operator=(const IPAddress&) = delete; + IPAddress(IPAddress&&) = delete; + IPAddress& operator=(IPAddress&&) = delete; + virtual ~IPAddress() = default; + + /** @brief Constructor to put object onto bus at a dbus path. + * @param[in] bus - Bus to attach to. + * @param[in] objPath - Path to attach at. + * @param[in] parent - Parent object. + * @param[in] type - ipaddress type(v4/v6). + * @param[in] ipAddress - ipadress. + * @param[in] origin - origin of ipaddress(dhcp/static/SLAAC/LinkLocal). + * @param[in] prefixLength - Length of prefix. + * @param[in] gateway - gateway address. + */ + IPAddress(sdbusplus::bus::bus& bus, const char* objPath, + EthernetInterface& parent, IP::Protocol type, + const std::string& ipAddress, IP::AddressOrigin origin, + uint8_t prefixLength, const std::string& gateway); + + /** @brief Delete this d-bus object. + */ + void delete_() override; + + private: + /** @brief Parent Object. */ + EthernetInterface& parent; }; } // namespace network diff --git a/ncsi_netlink_main.cpp b/ncsi_netlink_main.cpp index aeb26bb..9db624f 100644 --- a/ncsi_netlink_main.cpp +++ b/ncsi_netlink_main.cpp @@ -32,9 +32,9 @@ int main(int argc, char** argv) using namespace phosphor::network::ncsi; // Read arguments. auto options = ArgumentParser(argc, argv); - int packageInt {}; - int channelInt {}; - int indexInt {}; + int packageInt{}; + int channelInt{}; + int indexInt{}; // Parse out interface argument. auto ifIndex = (options)["index"]; @@ -49,7 +49,8 @@ int main(int argc, char** argv) if (indexInt < 0) { - exitWithError("Interface value should be greater than equal to 0", argv); + exitWithError("Interface value should be greater than equal to 0", + argv); } // Parse out package argument. @@ -60,7 +61,7 @@ int main(int argc, char** argv) } catch (const std::exception& e) { - packageInt = DEFAULT_VALUE; + packageInt = DEFAULT_VALUE; } if (packageInt < 0) @@ -76,7 +77,7 @@ int main(int argc, char** argv) } catch (const std::exception& e) { - channelInt = DEFAULT_VALUE; + channelInt = DEFAULT_VALUE; } if (channelInt < 0) @@ -100,7 +101,7 @@ int main(int argc, char** argv) } else if ((options)["clear"] == "true") { - return ncsi::clearInterface(indexInt); + return ncsi::clearInterface(indexInt); } else { @@ -108,4 +109,3 @@ int main(int argc, char** argv) } return 0; } - diff --git a/ncsi_util.cpp b/ncsi_util.cpp index c177bec..2b3fb54 100644 --- a/ncsi_util.cpp +++ b/ncsi_util.cpp @@ -1,9 +1,9 @@ #include "ncsi_util.hpp" #include -#include -#include #include +#include +#include #include #include @@ -19,7 +19,7 @@ namespace ncsi using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; -using CallBack = int(*)(struct nl_msg* msg, void* arg); +using CallBack = int (*)(struct nl_msg* msg, void* arg); namespace internal { @@ -27,40 +27,26 @@ namespace internal using nlMsgPtr = std::unique_ptr; using nlSocketPtr = std::unique_ptr; -CallBack infoCallBack = [](struct nl_msg* msg, void* arg) -{ +CallBack infoCallBack = [](struct nl_msg* msg, void* arg) { using namespace phosphor::network::ncsi; auto nlh = nlmsg_hdr(msg); - struct nlattr* tb[NCSI_ATTR_MAX + 1] = { nullptr }; - struct nla_policy ncsiPolicy[NCSI_ATTR_MAX + 1] = - { - { type: NLA_UNSPEC }, - { type: NLA_U32 }, - { type: NLA_NESTED }, - { type: NLA_U32 }, - { type: NLA_U32 }, + struct nlattr* tb[NCSI_ATTR_MAX + 1] = {nullptr}; + struct nla_policy ncsiPolicy[NCSI_ATTR_MAX + 1] = { + {type : NLA_UNSPEC}, {type : NLA_U32}, {type : NLA_NESTED}, + {type : NLA_U32}, {type : NLA_U32}, }; - struct nlattr* packagetb[NCSI_PKG_ATTR_MAX + 1] = { nullptr }; - struct nla_policy packagePolicy[NCSI_PKG_ATTR_MAX + 1] = - { - { type: NLA_UNSPEC }, - { type: NLA_NESTED }, - { type: NLA_U32 }, - { type: NLA_FLAG }, - { type: NLA_NESTED }, + struct nlattr* packagetb[NCSI_PKG_ATTR_MAX + 1] = {nullptr}; + struct nla_policy packagePolicy[NCSI_PKG_ATTR_MAX + 1] = { + {type : NLA_UNSPEC}, {type : NLA_NESTED}, {type : NLA_U32}, + {type : NLA_FLAG}, {type : NLA_NESTED}, }; - struct nlattr* channeltb[NCSI_CHANNEL_ATTR_MAX + 1] = { nullptr }; - struct nla_policy channelPolicy[NCSI_CHANNEL_ATTR_MAX + 1] = - { - { type: NLA_UNSPEC }, - { type: NLA_NESTED }, - { type: NLA_U32 }, - { type: NLA_FLAG }, - { type: NLA_NESTED }, - { type: NLA_UNSPEC}, + struct nlattr* channeltb[NCSI_CHANNEL_ATTR_MAX + 1] = {nullptr}; + struct nla_policy channelPolicy[NCSI_CHANNEL_ATTR_MAX + 1] = { + {type : NLA_UNSPEC}, {type : NLA_NESTED}, {type : NLA_U32}, + {type : NLA_FLAG}, {type : NLA_NESTED}, {type : NLA_UNSPEC}, }; auto ret = genlmsg_parse(nlh, 0, tb, NCSI_ATTR_MAX, ncsiPolicy); @@ -91,8 +77,7 @@ CallBack infoCallBack = [](struct nl_msg* msg, void* arg) if (packagetb[NCSI_PKG_ATTR_ID]) { auto attrID = nla_get_u32(packagetb[NCSI_PKG_ATTR_ID]); - log("Package has id", - entry("ID=%x", attrID)); + log("Package has id", entry("ID=%x", attrID)); } else { @@ -105,7 +90,7 @@ CallBack infoCallBack = [](struct nl_msg* msg, void* arg) } auto channelListTarget = static_cast( - nla_data(packagetb[NCSI_PKG_ATTR_CHANNEL_LIST])); + nla_data(packagetb[NCSI_PKG_ATTR_CHANNEL_LIST])); auto channelrem = nla_len(packagetb[NCSI_PKG_ATTR_CHANNEL_LIST]); nla_for_each_nested(channelListTarget, @@ -125,7 +110,7 @@ CallBack infoCallBack = [](struct nl_msg* msg, void* arg) if (channeltb[NCSI_CHANNEL_ATTR_ACTIVE]) { log("Channel Active", - entry("CHANNEL=%x", channel)); + entry("CHANNEL=%x", channel)); } else { @@ -145,26 +130,30 @@ CallBack infoCallBack = [](struct nl_msg* msg, void* arg) if (channeltb[NCSI_CHANNEL_ATTR_VERSION_MAJOR]) { - auto major = nla_get_u32(channeltb[NCSI_CHANNEL_ATTR_VERSION_MAJOR]); + auto major = + nla_get_u32(channeltb[NCSI_CHANNEL_ATTR_VERSION_MAJOR]); log("Channel Major Version", entry("VERSION=%x", major)); } if (channeltb[NCSI_CHANNEL_ATTR_VERSION_MINOR]) { - auto minor = nla_get_u32(channeltb[NCSI_CHANNEL_ATTR_VERSION_MINOR]); + auto minor = + nla_get_u32(channeltb[NCSI_CHANNEL_ATTR_VERSION_MINOR]); log("Channel Minor Version", entry("VERSION=%x", minor)); } if (channeltb[NCSI_CHANNEL_ATTR_VERSION_STR]) { - auto str = nla_get_string(channeltb[NCSI_CHANNEL_ATTR_VERSION_STR]); + auto str = + nla_get_string(channeltb[NCSI_CHANNEL_ATTR_VERSION_STR]); log("Channel Version Str", entry("VERSION=%s", str)); } if (channeltb[NCSI_CHANNEL_ATTR_LINK_STATE]) { - auto link = nla_get_u32(channeltb[NCSI_CHANNEL_ATTR_LINK_STATE]); + auto link = + nla_get_u32(channeltb[NCSI_CHANNEL_ATTR_LINK_STATE]); log("Channel Link State", entry("STATE=%x", link)); } @@ -177,14 +166,11 @@ CallBack infoCallBack = [](struct nl_msg* msg, void* arg) while (nla_ok(vid, len)) { auto id = nla_get_u16(vid); - log("VID", - entry("VID=%d", id)); + log("VID", entry("VID=%d", id)); vid = nla_next(vid, &len); } } - } - } return (int)NL_SKIP; }; @@ -193,31 +179,28 @@ int applyCmd(int ifindex, int cmd, int package = DEFAULT_VALUE, int channel = DEFAULT_VALUE, int flags = NONE, CallBack function = nullptr) { - nlSocketPtr socket(nl_socket_alloc(),&::nl_socket_free); + nlSocketPtr socket(nl_socket_alloc(), &::nl_socket_free); auto ret = genl_connect(socket.get()); if (ret < 0) { - log("Failed to open the socket", - entry("RC=%d", ret)); + log("Failed to open the socket", entry("RC=%d", ret)); return ret; } auto driverID = genl_ctrl_resolve(socket.get(), "NCSI"); if (driverID < 0) { - log("Failed to resolve", - entry("RC=%d", ret)); + log("Failed to resolve", entry("RC=%d", ret)); return driverID; } nlMsgPtr msg(nlmsg_alloc(), &::nlmsg_free); - auto msgHdr = genlmsg_put(msg.get(), 0, 0, driverID, 0, flags, - cmd, 0); + auto msgHdr = genlmsg_put(msg.get(), 0, 0, driverID, 0, flags, cmd, 0); if (!msgHdr) { log("Unable to add the netlink headers", - entry("COMMAND=%d", cmd)); + entry("COMMAND=%d", cmd)); return -1; } @@ -227,8 +210,7 @@ int applyCmd(int ifindex, int cmd, int package = DEFAULT_VALUE, package); if (ret < 0) { - log("Failed to set the attribute", - entry("RC=%d", ret), + log("Failed to set the attribute", entry("RC=%d", ret), entry("PACKAGE=%x", package)); return ret; } @@ -240,8 +222,7 @@ int applyCmd(int ifindex, int cmd, int package = DEFAULT_VALUE, channel); if (ret < 0) { - log("Failed to set the attribute", - entry("RC=%d", ret), + log("Failed to set the attribute", entry("RC=%d", ret), entry("CHANNEL=%x", channel)); return ret; } @@ -250,8 +231,7 @@ int applyCmd(int ifindex, int cmd, int package = DEFAULT_VALUE, ret = nla_put_u32(msg.get(), ncsi_nl_attrs::NCSI_ATTR_IFINDEX, ifindex); if (ret < 0) { - log("Failed to set the attribute", - entry("RC=%d", ret), + log("Failed to set the attribute", entry("RC=%d", ret), entry("INTERFACE=%x", ifindex)); return ret; } @@ -259,33 +239,30 @@ int applyCmd(int ifindex, int cmd, int package = DEFAULT_VALUE, if (function) { // Add a callback function to the socket - nl_socket_modify_cb(socket.get(), NL_CB_VALID, NL_CB_CUSTOM, - function, nullptr); + nl_socket_modify_cb(socket.get(), NL_CB_VALID, NL_CB_CUSTOM, function, + nullptr); } ret = nl_send_auto(socket.get(), msg.get()); if (ret < 0) { - log("Failed to send the message", - entry("RC=%d", ret)); + log("Failed to send the message", entry("RC=%d", ret)); return ret; } ret = nl_recvmsgs_default(socket.get()); if (ret < 0) { - log("Failed to receive the message", - entry("RC=%d", ret)); + log("Failed to receive the message", entry("RC=%d", ret)); } return ret; } -}//namespace internal +} // namespace internal int setChannel(int ifindex, int package, int channel) { - log("Set Channel", - entry("CHANNEL=%x", channel), + log("Set Channel", entry("CHANNEL=%x", channel), entry("PACKAGE=%x", package), entry("IFINDEX=%x", ifindex)); return internal::applyCmd(ifindex, ncsi_nl_commands::NCSI_CMD_SET_INTERFACE, @@ -294,16 +271,14 @@ int setChannel(int ifindex, int package, int channel) int clearInterface(int ifindex) { - log("ClearInterface", - entry("IFINDEX=%x", ifindex)); + log("ClearInterface", entry("IFINDEX=%x", ifindex)); return internal::applyCmd(ifindex, ncsi_nl_commands::NCSI_CMD_CLEAR_INTERFACE); } int getInfo(int ifindex, int package) { - log("Get Info", - entry("PACKAGE=%x", package), + log("Get Info", entry("PACKAGE=%x", package), entry("IFINDEX=%x", ifindex)); if (package == DEFAULT_VALUE) { @@ -319,6 +294,6 @@ int getInfo(int ifindex, int package) } } -}//namespace ncsi -}//namespace network -}//namespace phosphor +} // namespace ncsi +} // namespace network +} // namespace phosphor diff --git a/ncsi_util.hpp b/ncsi_util.hpp index db92269..db754fe 100644 --- a/ncsi_util.hpp +++ b/ncsi_util.hpp @@ -39,7 +39,6 @@ int clearInterface(int ifindex); */ int getInfo(int ifindex, int package); -}//namespace ncsi -}//namespace network -}//namespace phosphor - +} // namespace ncsi +} // namespace network +} // namespace phosphor diff --git a/network_config.cpp b/network_config.cpp index d3b560f..e83b16c 100644 --- a/network_config.cpp +++ b/network_config.cpp @@ -1,7 +1,7 @@ -#include "network_config.hpp" - #include "config.h" +#include "network_config.hpp" + #include #include @@ -12,13 +12,12 @@ namespace network namespace bmc { - void writeDHCPDefault(const std::string& filename, - const std::string& interface) - { - std::ofstream filestream; +void writeDHCPDefault(const std::string& filename, const std::string& interface) +{ + std::ofstream filestream; - filestream.open(filename); - filestream << "[Match]\nName=" << interface << + filestream.open(filename); + filestream << "[Match]\nName=" << interface << "\n[Network]\nDHCP=true\n" #ifdef LINK_LOCAL_AUTOCONFIGURATION "LinkLocalAddressing=yes\n" @@ -27,9 +26,9 @@ namespace bmc #endif "IPv6AcceptRA=false\n" "[DHCP]\nClientIdentifier=mac\n"; - filestream.close(); - } + filestream.close(); } +} // namespace bmc -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/network_config.hpp b/network_config.hpp index 0868820..7260ca2 100644 --- a/network_config.hpp +++ b/network_config.hpp @@ -7,9 +7,9 @@ namespace network namespace bmc { - void writeDHCPDefault(const std::string& filename, - const std::string& interface); +void writeDHCPDefault(const std::string& filename, + const std::string& interface); } -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/network_manager.cpp b/network_manager.cpp index 9617ff7..c1b0ba6 100644 --- a/network_manager.cpp +++ b/network_manager.cpp @@ -1,6 +1,7 @@ +#include "config.h" + #include "network_manager.hpp" -#include "config.h" #include "ipaddress.hpp" #include "network_config.hpp" #include "timer.hpp" @@ -30,10 +31,9 @@ using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; Manager::Manager(sdbusplus::bus::bus& bus, const char* objPath, - const std::string& path): + const std::string& path) : details::VLANCreateIface(bus, objPath, true), - bus(bus), - objectPath(objPath) + bus(bus), objectPath(objPath) { fs::path confDir(path); setConfDir(confDir); @@ -71,7 +71,7 @@ bool Manager::createDefaultNetworkFiles(bool force) } auto fileName = systemd::config::networkFilePrefix + interface + - systemd::config::networkFileSuffix; + systemd::config::networkFileSuffix; fs::path filePath = confDir; filePath /= fileName; @@ -84,7 +84,7 @@ bool Manager::createDefaultNetworkFiles(bool force) { bmc::writeDHCPDefault(filePath.string(), interface); log("Created the default network file.", - entry("INTERFACE=%s", interface.c_str())); + entry("INTERFACE=%s", interface.c_str())); isCreated = true; } } @@ -109,12 +109,11 @@ void Manager::setConfDir(const fs::path& dir) elog(); } } - } void Manager::createInterfaces() { - //clear all the interfaces first + // clear all the interfaces first interfaces.clear(); auto interfaceStrList = getInterfaces(); @@ -130,7 +129,7 @@ void Manager::createInterfaces() // to create the vlaninterface or normal physical interface. if (index != std::string::npos) { - //it is vlan interface + // it is vlan interface auto interfaceName = interface.substr(0, index); auto vlanid = interface.substr(index + 1); uint32_t vlanInt = std::stoul(vlanid); @@ -143,20 +142,14 @@ void Manager::createInterfaces() auto dhcp = getDHCPValue(confDir, interface); - auto intf = std::make_shared( - bus, - objPath.string(), - dhcp, - *this); - + auto intf = std::make_shared( + bus, objPath.string(), dhcp, *this); intf->createIPAddressObjects(); - this->interfaces.emplace(std::make_pair( - std::move(interface), std::move(intf))); - + this->interfaces.emplace( + std::make_pair(std::move(interface), std::move(intf))); } - } void Manager::createChildObjects() @@ -172,12 +165,11 @@ void Manager::createChildObjects() // create the system conf object. systemConf = std::make_unique( - bus, objPath.string(), *this); + bus, objPath.string(), *this); // create the dhcp conf object. objPath /= "dhcp"; dhcpConf = std::make_unique( - bus, objPath.string(), *this); - + bus, objPath.string(), *this); } void Manager::vLAN(IntfName interfaceName, uint32_t id) @@ -187,7 +179,7 @@ void Manager::vLAN(IntfName interfaceName, uint32_t id) void Manager::reset() { - if(!createDefaultNetworkFiles(true)) + if (!createDefaultNetworkFiles(true)) { log("Network Factory Reset failed."); return; @@ -199,14 +191,13 @@ void Manager::reset() // Need to merge the below function with the code which writes the // config file during factory reset. -//TODO openbmc/openbmc#1751 +// TODO openbmc/openbmc#1751 void Manager::writeToConfigurationFile() { // write all the static ip address in the systemd-network conf file for (const auto& intf : interfaces) { intf.second->writeConfigurationFile(); - } restartTimers(); } @@ -217,16 +208,16 @@ void Manager::restartTimers() if (refreshObjectTimer && restartTimer) { // start the restart timer. - auto restartTime = duration_cast( - phosphor::network::restartTimeout); + auto restartTime = + duration_cast(phosphor::network::restartTimeout); restartTimer->startTimer(restartTime); // start the refresh timer. - auto refreshTime = duration_cast( - phosphor::network::refreshTimeout); + auto refreshTime = + duration_cast(phosphor::network::refreshTimeout); refreshObjectTimer->startTimer(refreshTime); } } -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/network_manager.hpp b/network_manager.hpp index ab5fbd1..23eaacb 100644 --- a/network_manager.hpp +++ b/network_manager.hpp @@ -35,102 +35,111 @@ using VLANCreateIface = details::ServerObject< } // namespace details -class TestNetworkManager; //forward declaration -class TestRtNetlink; //forward declaration +class TestNetworkManager; // forward declaration +class TestRtNetlink; // forward declaration /** @class Manager * @brief OpenBMC network manager implementation. */ class Manager : public details::VLANCreateIface { - public: - Manager() = delete; - Manager(const Manager&) = delete; - Manager& operator=(const Manager&) = delete; - Manager(Manager&&) = delete; - Manager& operator=(Manager&&) = delete; - virtual ~Manager() = default; - - /** @brief Constructor to put object onto bus at a dbus path. - * @param[in] bus - Bus to attach to. - * @param[in] objPath - Path to attach at. - * @param[in] dir - Network Configuration directory path. - */ - Manager(sdbusplus::bus::bus& bus, const char* objPath, - const std::string& dir); - - void vLAN(IntfName interfaceName, uint32_t id) override; - - /** @brief write the network conf file with the in-memory objects. - */ - void writeToConfigurationFile(); - - /** @brief Fetch the interface and the ipaddress details - * from the system and create the ethernet interraces - * dbus object. - */ - void createInterfaces(); - - /** @brief create child interface object and the system conf object. - */ - void createChildObjects(); - - /** @brief sets the network conf directory. - * @param[in] dirName - Absolute path of the directory. - */ - void setConfDir(const fs::path& dir); - - /** @brief gets the network conf directory. - */ - fs::path getConfDir() { return confDir; } - - /** @brief gets the system conf object. - * - */ - const SystemConfPtr& getSystemConf() { return systemConf; } - - /** @brief gets the dhcp conf object. - * - */ - const DHCPConfPtr& getDHCPConf() { return dhcpConf; } - - /** @brief create the default network files for each interface - * @detail if force param is true then forcefully create the network - * files otherwise if network file doesn't exist then - * create it. - * @param[in] force - forcefully create the file - * @return true if network file created else false - */ - bool createDefaultNetworkFiles(bool force); - - /** @brief restart the network timers. */ - void restartTimers(); - - private: - /** @brief Persistent sdbusplus DBus bus connection. */ - sdbusplus::bus::bus& bus; - - /** @brief Persistent map of EthernetInterface dbus objects and their names */ - std::map> interfaces; - - /** @brief BMC network reset - resets network configuration for BMC. */ - void reset() override; - - /** @brief Path of Object. */ - std::string objectPath; - - /** @brief pointer to system conf object. */ - SystemConfPtr systemConf = nullptr; - - /** @brief pointer to dhcp conf object. */ - DHCPConfPtr dhcpConf = nullptr; - - /** @brief Network Configuration directory. */ - fs::path confDir; - - friend class TestNetworkManager; - friend class TestRtNetlink; - + public: + Manager() = delete; + Manager(const Manager&) = delete; + Manager& operator=(const Manager&) = delete; + Manager(Manager&&) = delete; + Manager& operator=(Manager&&) = delete; + virtual ~Manager() = default; + + /** @brief Constructor to put object onto bus at a dbus path. + * @param[in] bus - Bus to attach to. + * @param[in] objPath - Path to attach at. + * @param[in] dir - Network Configuration directory path. + */ + Manager(sdbusplus::bus::bus& bus, const char* objPath, + const std::string& dir); + + void vLAN(IntfName interfaceName, uint32_t id) override; + + /** @brief write the network conf file with the in-memory objects. + */ + void writeToConfigurationFile(); + + /** @brief Fetch the interface and the ipaddress details + * from the system and create the ethernet interraces + * dbus object. + */ + void createInterfaces(); + + /** @brief create child interface object and the system conf object. + */ + void createChildObjects(); + + /** @brief sets the network conf directory. + * @param[in] dirName - Absolute path of the directory. + */ + void setConfDir(const fs::path& dir); + + /** @brief gets the network conf directory. + */ + fs::path getConfDir() + { + return confDir; + } + + /** @brief gets the system conf object. + * + */ + const SystemConfPtr& getSystemConf() + { + return systemConf; + } + + /** @brief gets the dhcp conf object. + * + */ + const DHCPConfPtr& getDHCPConf() + { + return dhcpConf; + } + + /** @brief create the default network files for each interface + * @detail if force param is true then forcefully create the network + * files otherwise if network file doesn't exist then + * create it. + * @param[in] force - forcefully create the file + * @return true if network file created else false + */ + bool createDefaultNetworkFiles(bool force); + + /** @brief restart the network timers. */ + void restartTimers(); + + private: + /** @brief Persistent sdbusplus DBus bus connection. */ + sdbusplus::bus::bus& bus; + + /** @brief Persistent map of EthernetInterface dbus objects and their names + */ + std::map> interfaces; + + /** @brief BMC network reset - resets network configuration for BMC. */ + void reset() override; + + /** @brief Path of Object. */ + std::string objectPath; + + /** @brief pointer to system conf object. */ + SystemConfPtr systemConf = nullptr; + + /** @brief pointer to dhcp conf object. */ + DHCPConfPtr dhcpConf = nullptr; + + /** @brief Network Configuration directory. */ + fs::path confDir; + + friend class TestNetworkManager; + friend class TestRtNetlink; }; } // namespace network diff --git a/network_manager_main.cpp b/network_manager_main.cpp index 89ba7b3..5f6b81b 100644 --- a/network_manager_main.cpp +++ b/network_manager_main.cpp @@ -1,4 +1,5 @@ #include "config.h" + #include "dns_updater.hpp" #include "network_manager.hpp" #include "rtnetlink_server.hpp" @@ -41,16 +42,16 @@ void restartNetwork() restartSystemdUnit("systemd-networkd.service"); } -} //namespace network -} //namespace phosphor +} // namespace network +} // namespace phosphor void initializeTimers() { std::function refreshFunc( - std::bind(&phosphor::network::refreshObjects)); + std::bind(&phosphor::network::refreshObjects)); std::function restartFunc( - std::bind(&phosphor::network::restartNetwork)); + std::bind(&phosphor::network::restartNetwork)); phosphor::network::refreshObjectTimer = std::make_unique(refreshFunc); @@ -62,9 +63,9 @@ void initializeTimers() void createNetLinkSocket(phosphor::Descriptor& smartSock) { using namespace phosphor::logging; - using InternalFailure = sdbusplus::xyz::openbmc_project::Common:: - Error::InternalFailure; - //RtnetLink socket + using InternalFailure = + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; + // RtnetLink socket auto fd = socket(PF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_ROUTE); if (fd < 0) { @@ -76,9 +77,7 @@ void createNetLinkSocket(phosphor::Descriptor& smartSock) smartSock.set(fd); } - - -int main(int argc, char *argv[]) +int main(int argc, char* argv[]) { using namespace phosphor::logging; @@ -105,10 +104,8 @@ int main(int argc, char *argv[]) sdbusplus::server::manager::manager objManager(bus, OBJ_NETWORK); bus.request_name(BUSNAME_NETWORK); - phosphor::network::manager = - std::make_unique(bus, - OBJ_NETWORK, - NETWORK_CONF_DIR); + phosphor::network::manager = std::make_unique( + bus, OBJ_NETWORK, NETWORK_CONF_DIR); // create the default network files if the network file // is not there for any interface. @@ -130,7 +127,7 @@ int main(int argc, char *argv[]) // the network which creates the network objects } - //RtnetLink socket + // RtnetLink socket phosphor::Descriptor smartSock; createNetLinkSocket(smartSock); @@ -138,9 +135,10 @@ int main(int argc, char *argv[]) phosphor::network::rtnetlink::Server svr(eventPtr, smartSock); // DNS entry handler - phosphor::network::inotify::Watch watch(eventPtr, DNS_ENTRY_FILE, - std::bind(&phosphor::network::dns::updater::processDNSEntries, - std::placeholders::_1)); + phosphor::network::inotify::Watch watch( + eventPtr, DNS_ENTRY_FILE, + std::bind(&phosphor::network::dns::updater::processDNSEntries, + std::placeholders::_1)); // At this point, we have registered for the notifications for future // events. However, if the file is already populated before this, then @@ -150,4 +148,3 @@ int main(int argc, char *argv[]) sd_event_loop(eventPtr.get()); } - diff --git a/routing_table.cpp b/routing_table.cpp index 41e4a6d..6a17037 100644 --- a/routing_table.cpp +++ b/routing_table.cpp @@ -39,14 +39,13 @@ Table::Table() { commit(); } - } -int Table::readNetLinkSock(int sockFd, std::array& buf) +int Table::readNetLinkSock(int sockFd, std::array& buf) { struct nlmsghdr* nlHdr = nullptr; - int readLen {}; - int msgLen {}; + int readLen{}; + int msgLen{}; uint8_t seqNum = 1; uint8_t pID = getpid(); char* bufPtr = buf.data(); @@ -58,23 +57,22 @@ int Table::readNetLinkSock(int sockFd, std::array& buf) { auto error = errno; log("Socket recv failed:", - entry("ERROR=%s", strerror(error))); + entry("ERROR=%s", strerror(error))); elog(); - } nlHdr = reinterpret_cast(bufPtr); // Check if the header is valid - if ((NLMSG_OK(nlHdr, readLen) == 0) - || (nlHdr->nlmsg_type == NLMSG_ERROR)) + if ((NLMSG_OK(nlHdr, readLen) == 0) || + (nlHdr->nlmsg_type == NLMSG_ERROR)) { auto error = errno; log("Error validating header", - entry("NLMSGTYPE=%d", nlHdr->nlmsg_type), - entry("ERROR=%s", strerror(error))); + entry("NLMSGTYPE=%d", nlHdr->nlmsg_type), + entry("ERROR=%s", strerror(error))); elog(); } @@ -95,8 +93,7 @@ int Table::readNetLinkSock(int sockFd, std::array& buf) { break; } - } - while ((nlHdr->nlmsg_seq != seqNum) || (nlHdr->nlmsg_pid != pID)); + } while ((nlHdr->nlmsg_seq != seqNum) || (nlHdr->nlmsg_pid != pID)); return msgLen; } @@ -104,9 +101,9 @@ void Table::parseRoutes(const nlmsghdr* nlHdr) { rtmsg* rtMsg = nullptr; rtattr* rtAttr = nullptr; - int rtLen {}; - in_addr dstAddr {}; - in_addr gateWayAddr {}; + int rtLen{}; + in_addr dstAddr{}; + in_addr gateWayAddr{}; char ifName[IF_NAMESIZE] = {}; rtMsg = reinterpret_cast(NLMSG_DATA(nlHdr)); @@ -128,10 +125,12 @@ void Table::parseRoutes(const nlmsghdr* nlHdr) switch (rtAttr->rta_type) { case RTA_OIF: - if_indextoname(*reinterpret_cast(RTA_DATA(rtAttr)), ifName); + if_indextoname(*reinterpret_cast(RTA_DATA(rtAttr)), + ifName); break; case RTA_GATEWAY: - gateWayAddr.s_addr = *reinterpret_cast(RTA_DATA(rtAttr)); + gateWayAddr.s_addr = + *reinterpret_cast(RTA_DATA(rtAttr)); break; case RTA_DST: dstAddr.s_addr = *reinterpret_cast(RTA_DATA(rtAttr)); @@ -168,9 +167,9 @@ Map Table::getRoutes() std::array msgBuf = {0}; int sock = -1; - int len {0}; + int len{0}; - uint8_t msgSeq {0}; + uint8_t msgSeq{0}; // Create Socket if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) @@ -189,7 +188,7 @@ Map Table::getRoutes() // Length of message nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg)); // Get the routes from kernel routing table - nlMsg->nlmsg_type = RTM_GETROUTE; + nlMsg->nlmsg_type = RTM_GETROUTE; // The message is a request for dump nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST; @@ -216,8 +215,7 @@ Map Table::getRoutes() return routeList; } -std::string Table::getGateway(int addressFamily, - const std::string& ipaddress, +std::string Table::getGateway(int addressFamily, const std::string& ipaddress, uint8_t prefix) const { std::string gateway; @@ -231,6 +229,6 @@ std::string Table::getGateway(int addressFamily, return gateway; } -}// namespace route -}// namespace network -}// namespace phosphor +} // namespace route +} // namespace network +} // namespace phosphor diff --git a/routing_table.hpp b/routing_table.hpp index 0768d8e..f23b54c 100644 --- a/routing_table.hpp +++ b/routing_table.hpp @@ -1,8 +1,8 @@ #pragma once #include -#include #include +#include #include #include @@ -25,18 +25,15 @@ struct Entry std::string gateway; // interface for this route std::string interface; - Entry(std::string dest, - std::string gtw, - std::string intf) : - destination(dest), - gateway(gtw), - interface(intf){} + Entry(std::string dest, std::string gtw, std::string intf) : + destination(dest), gateway(gtw), interface(intf) + { + } bool operator==(const Entry& rhs) { return this->destination == rhs.destination && - this->gateway == rhs.gateway && - this->interface == rhs.interface; + this->gateway == rhs.gateway && this->interface == rhs.interface; } }; @@ -45,62 +42,60 @@ using Map = std::map; class Table { - public: - Table(); - ~Table() = default; - Table(const Table&) = default; - Table& operator=(const Table&) = default; - Table(Table&&) = default; - Table& operator=(Table &&) = default; - - /** - * @brief gets the list of routes. - * - * @returns list of routes. - */ - Map getRoutes(); + public: + Table(); + ~Table() = default; + Table(const Table&) = default; + Table& operator=(const Table&) = default; + Table(Table&&) = default; + Table& operator=(Table&&) = default; - /** - * @brief gets the default gateway. - * - * @returns the default gateway. - */ - std::string getDefaultGateway() const - { - return defaultGateway; - }; + /** + * @brief gets the list of routes. + * + * @returns list of routes. + */ + Map getRoutes(); - /** - * @brief get the gateway for the network. - * @param[in] addressFamily - ip address family(AF_INET/AF_INET6) - * @param[in] ipaddress - ip address. - * @param[in] prefix - prefix length. - * @returns the gatway for the given network. - */ - std::string getGateway(int addressFamily, - const std::string& ipaddress, - uint8_t prefix) const; - private: + /** + * @brief gets the default gateway. + * + * @returns the default gateway. + */ + std::string getDefaultGateway() const + { + return defaultGateway; + }; - /** - * @brief read the routing data from the socket and fill the buffer. - * - * @param[in] bufPtr - unique pointer to confidentiality algorithm - * instance - */ - int readNetLinkSock(int sockFd, std::array& buff); - /** - * @brief Parse the route and add it to the route list. - * - * @param[in] nlHdr - net link message header. - */ - void parseRoutes(const struct nlmsghdr* nlHdr); + /** + * @brief get the gateway for the network. + * @param[in] addressFamily - ip address family(AF_INET/AF_INET6) + * @param[in] ipaddress - ip address. + * @param[in] prefix - prefix length. + * @returns the gatway for the given network. + */ + std::string getGateway(int addressFamily, const std::string& ipaddress, + uint8_t prefix) const; - std::string defaultGateway; // default gateway - Map routeList; //List of routes + private: + /** + * @brief read the routing data from the socket and fill the buffer. + * + * @param[in] bufPtr - unique pointer to confidentiality algorithm + * instance + */ + int readNetLinkSock(int sockFd, std::array& buff); + /** + * @brief Parse the route and add it to the route list. + * + * @param[in] nlHdr - net link message header. + */ + void parseRoutes(const struct nlmsghdr* nlHdr); + std::string defaultGateway; // default gateway + Map routeList; // List of routes }; -}// namespace route -}// namespace network -}// namespace phosphor +} // namespace route +} // namespace network +} // namespace phosphor diff --git a/rtnetlink_server.cpp b/rtnetlink_server.cpp index eb63f74..3121e4d 100644 --- a/rtnetlink_server.cpp +++ b/rtnetlink_server.cpp @@ -31,16 +31,16 @@ namespace rtnetlink static int eventHandler(sd_event_source* es, int fd, uint32_t revents, void* userdata) { - char buffer[phosphor::network::rtnetlink::BUFSIZE] {}; - int len {}; + char buffer[phosphor::network::rtnetlink::BUFSIZE]{}; + int len{}; auto netLinkHeader = reinterpret_cast(buffer); - while ((len = recv(fd, netLinkHeader, - phosphor::network::rtnetlink::BUFSIZE, 0)) > 0) + while ((len = recv(fd, netLinkHeader, phosphor::network::rtnetlink::BUFSIZE, + 0)) > 0) { for (; (NLMSG_OK(netLinkHeader, len)) && (netLinkHeader->nlmsg_type != NLMSG_DONE); - netLinkHeader = NLMSG_NEXT(netLinkHeader, len)) + netLinkHeader = NLMSG_NEXT(netLinkHeader, len)) { if (netLinkHeader->nlmsg_type == RTM_NEWADDR || netLinkHeader->nlmsg_type == RTM_DELADDR) @@ -55,7 +55,7 @@ static int eventHandler(sd_event_source* es, int fd, uint32_t revents, // crash refreshObjectTimer->startTimer(time); } // end if - } // end if + } // end if } // end for @@ -67,14 +67,16 @@ static int eventHandler(sd_event_source* es, int fd, uint32_t revents, Server::Server(EventPtr& eventPtr, const phosphor::Descriptor& smartSock) { using namespace phosphor::logging; - using InternalFailure = sdbusplus::xyz::openbmc_project::Common:: - Error::InternalFailure; - struct sockaddr_nl addr {}; - int r {}; + using InternalFailure = + sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure; + struct sockaddr_nl addr + { + }; + int r{}; - sigset_t ss {}; + sigset_t ss{}; // check that the given socket is valid or not. - if(smartSock() < 0) + if (smartSock() < 0) { r = -EBADF; goto finish; @@ -118,8 +120,8 @@ Server::Server(EventPtr& eventPtr, const phosphor::Descriptor& smartSock) goto finish; } - r = sd_event_add_io(eventPtr.get(), nullptr, - smartSock(), EPOLLIN, eventHandler, nullptr); + r = sd_event_add_io(eventPtr.get(), nullptr, smartSock(), EPOLLIN, + eventHandler, nullptr); if (r < 0) { goto finish; @@ -135,7 +137,6 @@ finish: } } - -} //rtnetlink -} //network -} //phosphor +} // namespace rtnetlink +} // namespace network +} // namespace phosphor diff --git a/rtnetlink_server.hpp b/rtnetlink_server.hpp index 0991ae0..e62f51c 100644 --- a/rtnetlink_server.hpp +++ b/rtnetlink_server.hpp @@ -23,25 +23,24 @@ constexpr auto BUFSIZE = 4096; class Server { - public: - - /** @brief Constructor - * - * @details Sets up the server to handle incoming RTNETLINK events - * - * @param[in] eventPtr - Unique ptr reference to sd_event. - * @param[in] socket - netlink socket. - */ - Server(EventPtr& eventPtr, const phosphor::Descriptor& socket); - - Server() = delete; - ~Server() = default; - Server(const Server&) = delete; - Server& operator=(const Server&) = delete; - Server(Server&&) = default; - Server& operator=(Server &&) = default; + public: + /** @brief Constructor + * + * @details Sets up the server to handle incoming RTNETLINK events + * + * @param[in] eventPtr - Unique ptr reference to sd_event. + * @param[in] socket - netlink socket. + */ + Server(EventPtr& eventPtr, const phosphor::Descriptor& socket); + + Server() = delete; + ~Server() = default; + Server(const Server&) = delete; + Server& operator=(const Server&) = delete; + Server(Server&&) = default; + Server& operator=(Server&&) = default; }; -} //namespace rtnetlink -} //namespce network -} //namespace phosphor +} // namespace rtnetlink +} // namespace network +} // namespace phosphor diff --git a/system_configuration.cpp b/system_configuration.cpp index da5140a..b9c0b2f 100644 --- a/system_configuration.cpp +++ b/system_configuration.cpp @@ -1,6 +1,7 @@ +#include "config.h" + #include "system_configuration.hpp" -#include "config.h" #include "network_manager.hpp" #include "routing_table.hpp" @@ -14,9 +15,9 @@ namespace network { // systemd service to kick start a target. -constexpr auto HOSTNAMED_SERVICE = "org.freedesktop.hostname1"; -constexpr auto HOSTNAMED_SERVICE_PATH = "/org/freedesktop/hostname1"; -constexpr auto HOSTNAMED_INTERFACE = "org.freedesktop.hostname1"; +constexpr auto HOSTNAMED_SERVICE = "org.freedesktop.hostname1"; +constexpr auto HOSTNAMED_SERVICE_PATH = "/org/freedesktop/hostname1"; +constexpr auto HOSTNAMED_INTERFACE = "org.freedesktop.hostname1"; constexpr auto PROPERTY_INTERFACE = "org.freedesktop.DBus.Properties"; constexpr auto METHOD_GET = "Get"; constexpr auto METHOD_SET = "SetStaticHostname"; @@ -31,9 +32,8 @@ using SystemConfigIntf = SystemConfiguration::SystemConfiguration(sdbusplus::bus::bus& bus, const std::string& objPath, Manager& parent) : - Iface(bus, objPath.c_str(), true), - bus(bus), - manager(parent) + Iface(bus, objPath.c_str(), true), + bus(bus), manager(parent) { auto name = getHostNameFromSystem(); route::Table routingTable; @@ -50,11 +50,8 @@ std::string SystemConfiguration::hostName(std::string name) { return name; } - auto method = bus.new_method_call( - HOSTNAMED_SERVICE, - HOSTNAMED_SERVICE_PATH, - HOSTNAMED_INTERFACE, - METHOD_SET); + auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH, + HOSTNAMED_INTERFACE, METHOD_SET); method.append(name, true); @@ -71,11 +68,8 @@ std::string SystemConfiguration::hostName(std::string name) std::string SystemConfiguration::getHostNameFromSystem() const { sdbusplus::message::variant name; - auto method = bus.new_method_call( - HOSTNAMED_SERVICE, - HOSTNAMED_SERVICE_PATH, - PROPERTY_INTERFACE, - METHOD_GET); + auto method = bus.new_method_call(HOSTNAMED_SERVICE, HOSTNAMED_SERVICE_PATH, + PROPERTY_INTERFACE, METHOD_GET); method.append(HOSTNAMED_INTERFACE, "Hostname"); @@ -94,7 +88,6 @@ std::string SystemConfiguration::getHostNameFromSystem() const return name.get(); } - std::string SystemConfiguration::defaultGateway(std::string gateway) { auto gw = SystemConfigIntf::defaultGateway(); @@ -106,15 +99,15 @@ std::string SystemConfiguration::defaultGateway(std::string gateway) if (!isValidIP(AF_INET, gateway)) { log("Not a valid Gateway", - entry("GATEWAY=%s", gateway.c_str())); - elog(InvalidArgumentMetadata::ARGUMENT_NAME("GATEWAY"), - InvalidArgumentMetadata::ARGUMENT_VALUE( - gateway.c_str())); + entry("GATEWAY=%s", gateway.c_str())); + elog( + InvalidArgumentMetadata::ARGUMENT_NAME("GATEWAY"), + InvalidArgumentMetadata::ARGUMENT_VALUE(gateway.c_str())); } gw = SystemConfigIntf::defaultGateway(gateway); manager.writeToConfigurationFile(); return gw; } -}// namespace network -}// namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/system_configuration.hpp b/system_configuration.hpp index e28d496..9e76dca 100644 --- a/system_configuration.hpp +++ b/system_configuration.hpp @@ -13,8 +13,7 @@ namespace network using SystemConfigIntf = sdbusplus::xyz::openbmc_project::Network::server::SystemConfiguration; -using Iface = - sdbusplus::server::object::object; +using Iface = sdbusplus::server::object::object; class Manager; // forward declaration of network manager. @@ -25,48 +24,45 @@ class Manager; // forward declaration of network manager. */ class SystemConfiguration : public Iface { - public: - SystemConfiguration() = default; - SystemConfiguration(const SystemConfiguration&) = delete; - SystemConfiguration& operator=(const SystemConfiguration&) = delete; - SystemConfiguration(SystemConfiguration&&) = delete; - SystemConfiguration& operator=(SystemConfiguration&&) = delete; - virtual ~SystemConfiguration() = default; - - /** @brief Constructor to put object onto bus at a dbus path. - * @param[in] bus - Bus to attach to. - * @param[in] objPath - Path to attach at. - * @param[in] parent - Parent object. - */ - SystemConfiguration(sdbusplus::bus::bus& bus, - const std::string& objPath, - Manager& parent); - - /** @brief set the hostname of the system. - * @param[in] name - host name of the system. - */ - std::string hostName(std::string name) override; - - /** @brief set the default gateway of the system. - * @param[in] gateway - default gateway of the system. - */ - std::string defaultGateway(std::string gateway) override; - - using SystemConfigIntf::defaultGateway; - - private: - - /** @brief get the hostname from the system by doing - * dbus call to hostnamed service. - */ - std::string getHostNameFromSystem() const; - - /** @brief Persistent sdbusplus DBus bus connection. */ - sdbusplus::bus::bus& bus; - - /** @brief Network Manager object. */ - Manager& manager; - + public: + SystemConfiguration() = default; + SystemConfiguration(const SystemConfiguration&) = delete; + SystemConfiguration& operator=(const SystemConfiguration&) = delete; + SystemConfiguration(SystemConfiguration&&) = delete; + SystemConfiguration& operator=(SystemConfiguration&&) = delete; + virtual ~SystemConfiguration() = default; + + /** @brief Constructor to put object onto bus at a dbus path. + * @param[in] bus - Bus to attach to. + * @param[in] objPath - Path to attach at. + * @param[in] parent - Parent object. + */ + SystemConfiguration(sdbusplus::bus::bus& bus, const std::string& objPath, + Manager& parent); + + /** @brief set the hostname of the system. + * @param[in] name - host name of the system. + */ + std::string hostName(std::string name) override; + + /** @brief set the default gateway of the system. + * @param[in] gateway - default gateway of the system. + */ + std::string defaultGateway(std::string gateway) override; + + using SystemConfigIntf::defaultGateway; + + private: + /** @brief get the hostname from the system by doing + * dbus call to hostnamed service. + */ + std::string getHostNameFromSystem() const; + + /** @brief Persistent sdbusplus DBus bus connection. */ + sdbusplus::bus::bus& bus; + + /** @brief Network Manager object. */ + Manager& manager; }; } // namespace network diff --git a/test/mock_syscall.cpp b/test/mock_syscall.cpp index 173b67f..28ebed2 100644 --- a/test/mock_syscall.cpp +++ b/test/mock_syscall.cpp @@ -1,43 +1,42 @@ -#include -#include - -#include -#include #include - #include +#include +#include +#include +#include #define MAX_IFADDRS 5 int debugging = false; /* Data for mocking getifaddrs */ -struct ifaddr_storage { +struct ifaddr_storage +{ struct ifaddrs ifaddr; struct sockaddr_storage addr; struct sockaddr_storage mask; struct sockaddr_storage bcast; } mock_ifaddr_storage[MAX_IFADDRS]; -struct ifaddrs *mock_ifaddrs = nullptr; +struct ifaddrs* mock_ifaddrs = nullptr; int ifaddr_count = 0; /* Stub library functions */ -void freeifaddrs(ifaddrs *ifp) +void freeifaddrs(ifaddrs* ifp) { - return ; + return; } void mock_addIP(const char* name, const char* addr, const char* mask, unsigned int flags) { - struct ifaddrs *ifaddr = &mock_ifaddr_storage[ifaddr_count].ifaddr; + struct ifaddrs* ifaddr = &mock_ifaddr_storage[ifaddr_count].ifaddr; - struct sockaddr_in *in = reinterpret_cast - (&mock_ifaddr_storage[ifaddr_count].addr); - struct sockaddr_in *mask_in = reinterpret_cast - (&mock_ifaddr_storage[ifaddr_count].mask); + struct sockaddr_in* in = + reinterpret_cast(&mock_ifaddr_storage[ifaddr_count].addr); + struct sockaddr_in* mask_in = + reinterpret_cast(&mock_ifaddr_storage[ifaddr_count].mask); in->sin_family = AF_INET; in->sin_port = 0; @@ -58,14 +57,12 @@ void mock_addIP(const char* name, const char* addr, const char* mask, mock_ifaddr_storage[ifaddr_count - 1].ifaddr.ifa_next = ifaddr; ifaddr_count++; mock_ifaddrs = &mock_ifaddr_storage[0].ifaddr; - } -int getifaddrs(ifaddrs **ifap) +int getifaddrs(ifaddrs** ifap) { *ifap = mock_ifaddrs; if (mock_ifaddrs == nullptr) return -1; return (0); } - diff --git a/test/test_config_parser.cpp b/test/test_config_parser.cpp index 1c902d2..99effad 100644 --- a/test/test_config_parser.cpp +++ b/test/test_config_parser.cpp @@ -1,14 +1,14 @@ -#include +#include "config.h" #include "config_parser.hpp" - #include "xyz/openbmc_project/Common/error.hpp" -#include -#include "config.h" #include -#include #include +#include +#include + +#include namespace phosphor { @@ -17,31 +17,31 @@ namespace network class TestConfigParser : public testing::Test { - public: - config::Parser parser; - TestConfigParser() - { - remove("/tmp/eth0.network"); - std::ofstream filestream("/tmp/eth0.network"); + public: + config::Parser parser; + TestConfigParser() + { + remove("/tmp/eth0.network"); + std::ofstream filestream("/tmp/eth0.network"); - filestream << "[Match]\nName=eth0\n" << - "[Network]\nDHCP=true\n[DHCP]\nClientIdentifier= mac\n"; - filestream.close(); - parser.setFile("/tmp/eth0.network"); - } + filestream << "[Match]\nName=eth0\n" + << "[Network]\nDHCP=true\n[DHCP]\nClientIdentifier= mac\n"; + filestream.close(); + parser.setFile("/tmp/eth0.network"); + } - bool isValueFound(const std::vector& values, - const std::string& expectedValue) + bool isValueFound(const std::vector& values, + const std::string& expectedValue) + { + for (const auto& value : values) { - for (const auto& value : values) + if (expectedValue == value) { - if (expectedValue == value) - { - return true; - } + return true; } - return false; } + return false; + } }; TEST_F(TestConfigParser, ReadConfigDataFromFile) @@ -82,5 +82,5 @@ TEST_F(TestConfigParser, KeyNotFound) remove("/tmp/eth0.network"); } -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/test/test_dns_updater.cpp b/test/test_dns_updater.cpp index 8697d4c..2a425c0 100644 --- a/test/test_dns_updater.cpp +++ b/test/test_dns_updater.cpp @@ -1,13 +1,14 @@ #include "dns_updater.hpp" -#include - -#include #include +#include + +#include static constexpr auto IN_FILE = "/tmp/" __BASE_FILE__ "netif_state"; static constexpr auto OUT_FILE = "/tmp/" __BASE_FILE__ "resolv.conf"; -static constexpr auto COMPARE_FILE = "/tmp/" __BASE_FILE__ "resolv_compare.conf"; +static constexpr auto COMPARE_FILE = + "/tmp/" __BASE_FILE__ "resolv_compare.conf"; static constexpr auto DNS_ENTRY_1 = "DNS=1.2.3.4\n"; static constexpr auto DNS_ENTRY_2 = "DNS=5.6.7.8\n"; @@ -15,38 +16,38 @@ namespace fs = std::experimental::filesystem; class DnsUpdateTest : public ::testing::Test { - public: - // Gets called as part of each TEST_F construction - DnsUpdateTest() - { - // Create a file containing DNS entries like in netif/state - std::ofstream file(IN_FILE); - file << DNS_ENTRY_1; - file << DNS_ENTRY_2; + public: + // Gets called as part of each TEST_F construction + DnsUpdateTest() + { + // Create a file containing DNS entries like in netif/state + std::ofstream file(IN_FILE); + file << DNS_ENTRY_1; + file << DNS_ENTRY_2; - // Create a file to compare the results against - std::ofstream compare(COMPARE_FILE); - compare << "### Generated by phosphor-networkd ###\n"; - compare << "nameserver 1.2.3.4\n"; - compare << "nameserver 5.6.7.8\n"; - } + // Create a file to compare the results against + std::ofstream compare(COMPARE_FILE); + compare << "### Generated by phosphor-networkd ###\n"; + compare << "nameserver 1.2.3.4\n"; + compare << "nameserver 5.6.7.8\n"; + } - // Gets called as part of each TEST_F destruction - ~DnsUpdateTest() + // Gets called as part of each TEST_F destruction + ~DnsUpdateTest() + { + if (fs::exists(IN_FILE)) + { + fs::remove(IN_FILE); + } + if (fs::exists(OUT_FILE)) + { + fs::remove(OUT_FILE); + } + if (fs::exists(COMPARE_FILE)) { - if (fs::exists(IN_FILE)) - { - fs::remove(IN_FILE); - } - if (fs::exists(OUT_FILE)) - { - fs::remove(OUT_FILE); - } - if (fs::exists(COMPARE_FILE)) - { - fs::remove(COMPARE_FILE); - } + fs::remove(COMPARE_FILE); } + } }; /** @brief Makes outfile is updated with right contents diff --git a/test/test_ethernet_interface.cpp b/test/test_ethernet_interface.cpp index 2181006..1b284a2 100644 --- a/test/test_ethernet_interface.cpp +++ b/test/test_ethernet_interface.cpp @@ -1,10 +1,7 @@ #include "config_parser.hpp" -#include "network_manager.hpp" -#include "mock_syscall.hpp" #include "ipaddress.hpp" - -#include -#include +#include "mock_syscall.hpp" +#include "network_manager.hpp" #include #include @@ -13,6 +10,9 @@ #include #include +#include + +#include namespace phosphor { @@ -21,116 +21,103 @@ namespace network class TestEthernetInterface : public testing::Test { - public: - - sdbusplus::bus::bus bus; - Manager manager; - EthernetInterface interface; - std::string confDir; - TestEthernetInterface() - : bus(sdbusplus::bus::new_default()), - manager(bus, "/xyz/openbmc_test/network", "/tmp/"), - interface(bus, "/xyz/openbmc_test/network/test0", false, manager) - - { - setConfDir(); - } - - void setConfDir() - { - char tmp[] = "/tmp/EthernetInterface.XXXXXX"; - confDir = mkdtemp(tmp); - manager.setConfDir(confDir); - } - - ~TestEthernetInterface() + public: + sdbusplus::bus::bus bus; + Manager manager; + EthernetInterface interface; + std::string confDir; + TestEthernetInterface() : + bus(sdbusplus::bus::new_default()), + manager(bus, "/xyz/openbmc_test/network", "/tmp/"), + interface(bus, "/xyz/openbmc_test/network/test0", false, manager) + + { + setConfDir(); + } + + void setConfDir() + { + char tmp[] = "/tmp/EthernetInterface.XXXXXX"; + confDir = mkdtemp(tmp); + manager.setConfDir(confDir); + } + + ~TestEthernetInterface() + { + if (confDir != "") { - if(confDir != "") - { - fs::remove_all(confDir); - } + fs::remove_all(confDir); } + } + int countIPObjects() + { + return interface.getAddresses().size(); + } - int countIPObjects() + bool isIPObjectExist(const std::string& ipaddress) + { + auto address = interface.getAddresses().find(ipaddress); + if (address == interface.getAddresses().end()) { - return interface.getAddresses().size(); + return false; } + return true; + } - bool isIPObjectExist(const std::string& ipaddress) + bool deleteIPObject(const std::string& ipaddress) + { + auto address = interface.getAddresses().find(ipaddress); + if (address == interface.getAddresses().end()) { - auto address = interface.getAddresses().find(ipaddress); - if (address == interface.getAddresses().end()) - { - return false; - } - return true; - - } - - bool deleteIPObject(const std::string& ipaddress) - { - auto address = interface.getAddresses().find(ipaddress); - if (address == interface.getAddresses().end()) - { - return false; - } - address->second->delete_(); - return true; - } - - std::string getObjectPath(const std::string& ipaddress, - uint8_t subnetMask, - const std::string& gateway) - { - IP::Protocol addressType = IP::Protocol::IPv4; - - return interface.generateObjectPath(addressType, - ipaddress, - subnetMask, - gateway); - } - - void createIPObject(IP::Protocol addressType, - const std::string& ipaddress, - uint8_t subnetMask, - const std::string& gateway) - { - interface.iP(addressType, - ipaddress, - subnetMask, - gateway - ); - + return false; } - - // Validates if the DNS entries have been correctly processed - void validateResolvFile(ServerList values) + address->second->delete_(); + return true; + } + + std::string getObjectPath(const std::string& ipaddress, uint8_t subnetMask, + const std::string& gateway) + { + IP::Protocol addressType = IP::Protocol::IPv4; + + return interface.generateObjectPath(addressType, ipaddress, subnetMask, + gateway); + } + + void createIPObject(IP::Protocol addressType, const std::string& ipaddress, + uint8_t subnetMask, const std::string& gateway) + { + interface.iP(addressType, ipaddress, subnetMask, gateway); + } + + // Validates if the DNS entries have been correctly processed + void validateResolvFile(ServerList values) + { + // Check whether the entries has been written to resolv.conf + fs::path resolvFile = confDir; + resolvFile /= "resolv.conf"; + + // Passed in "value" is what is read from the config file + interface.writeDNSEntries(values, resolvFile); + std::string expectedServers = + "### Generated manually via dbus settings ###"; + expectedServers += + "nameserver 9.1.1.1nameserver 9.2.2.2nameserver 9.3.3.3"; + + std::string actualServers{}; + std::fstream stream(resolvFile.string().c_str(), std::fstream::in); + for (std::string line; std::getline(stream, line);) { - // Check whether the entries has been written to resolv.conf - fs::path resolvFile = confDir; - resolvFile /= "resolv.conf"; - - // Passed in "value" is what is read from the config file - interface.writeDNSEntries(values, resolvFile); - std::string expectedServers = "### Generated manually via dbus settings ###"; - expectedServers += - "nameserver 9.1.1.1nameserver 9.2.2.2nameserver 9.3.3.3"; - - std::string actualServers{}; - std::fstream stream(resolvFile.string().c_str(), std::fstream::in); - for (std::string line; std::getline(stream, line);) - { - actualServers += line; - } - EXPECT_EQ(expectedServers , actualServers); + actualServers += line; } + EXPECT_EQ(expectedServers, actualServers); + } }; TEST_F(TestEthernetInterface, NoIPaddress) { EXPECT_EQ(countIPObjects(), 0); - } TEST_F(TestEthernetInterface, AddIPAddress) @@ -138,7 +125,6 @@ TEST_F(TestEthernetInterface, AddIPAddress) IP::Protocol addressType = IP::Protocol::IPv4; createIPObject(addressType, "10.10.10.10", 16, "10.10.10.1"); EXPECT_EQ(true, isIPObjectExist("10.10.10.10")); - } TEST_F(TestEthernetInterface, AddMultipleAddress) @@ -148,7 +134,6 @@ TEST_F(TestEthernetInterface, AddMultipleAddress) createIPObject(addressType, "20.20.20.20", 16, "20.20.20.1"); EXPECT_EQ(true, isIPObjectExist("10.10.10.10")); EXPECT_EQ(true, isIPObjectExist("20.20.20.20")); - } TEST_F(TestEthernetInterface, DeleteIPAddress) @@ -159,7 +144,6 @@ TEST_F(TestEthernetInterface, DeleteIPAddress) deleteIPObject("10.10.10.10"); EXPECT_EQ(false, isIPObjectExist("10.10.10.10")); EXPECT_EQ(true, isIPObjectExist("20.20.20.20")); - } TEST_F(TestEthernetInterface, DeleteInvalidIPAddress) @@ -180,19 +164,15 @@ TEST_F(TestEthernetInterface, CheckObjectPath) hashString += std::to_string(prefix); hashString += gateway; - - hexId << std::hex << ((std::hash {}( - hashString)) & 0xFFFFFFFF); + hexId << std::hex << ((std::hash{}(hashString)) & 0xFFFFFFFF); expectedObjectPath += hexId.str(); - EXPECT_EQ(expectedObjectPath, getObjectPath(ipaddress, - prefix, - gateway)); + EXPECT_EQ(expectedObjectPath, getObjectPath(ipaddress, prefix, gateway)); } TEST_F(TestEthernetInterface, addNameServers) { - ServerList servers = {"9.1.1.1","9.2.2.2","9.3.3.3"}; + ServerList servers = {"9.1.1.1", "9.2.2.2", "9.3.3.3"}; interface.nameservers(servers); fs::path filePath = confDir; filePath /= "00-bmc-test0.network"; @@ -200,14 +180,14 @@ TEST_F(TestEthernetInterface, addNameServers) config::ReturnCode rc = config::ReturnCode::SUCCESS; config::ValueList values; std::tie(rc, values) = parser.getValues("Network", "DNS"); - EXPECT_EQ(servers , values); + EXPECT_EQ(servers, values); validateResolvFile(values); } TEST_F(TestEthernetInterface, addNTPServers) { - ServerList servers = {"10.1.1.1","10.2.2.2","10.3.3.3"}; + ServerList servers = {"10.1.1.1", "10.2.2.2", "10.3.3.3"}; interface.nTPServers(servers); fs::path filePath = confDir; filePath /= "00-bmc-test0.network"; @@ -215,8 +195,8 @@ TEST_F(TestEthernetInterface, addNTPServers) config::ReturnCode rc = config::ReturnCode::SUCCESS; config::ValueList values; std::tie(rc, values) = parser.getValues("Network", "NTP"); - EXPECT_EQ(servers , values); + EXPECT_EQ(servers, values); } -}// namespce network -}// namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/test/test_network_manager.cpp b/test/test_network_manager.cpp index 2776bcf..1c0a116 100644 --- a/test/test_network_manager.cpp +++ b/test/test_network_manager.cpp @@ -1,20 +1,19 @@ -#include "network_manager.hpp" #include "mock_syscall.hpp" - -#include "xyz/openbmc_project/Common/error.hpp" -#include +#include "network_manager.hpp" #include "timer.hpp" +#include "xyz/openbmc_project/Common/error.hpp" -#include -#include - +#include #include #include -#include #include #include #include +#include +#include + +#include namespace phosphor { @@ -25,49 +24,48 @@ namespace fs = std::experimental::filesystem; class TestNetworkManager : public testing::Test { - public: - - sdbusplus::bus::bus bus; - Manager manager; - std::string confDir; - TestNetworkManager() - : bus(sdbusplus::bus::new_default()), - manager(bus, "/xyz/openbmc_test/abc", "/tmp") - { - setConfDir(); - } + public: + sdbusplus::bus::bus bus; + Manager manager; + std::string confDir; + TestNetworkManager() : + bus(sdbusplus::bus::new_default()), + manager(bus, "/xyz/openbmc_test/abc", "/tmp") + { + setConfDir(); + } - ~TestNetworkManager() + ~TestNetworkManager() + { + if (confDir != "") { - if(confDir != "") - { - fs::remove_all(confDir); - } + fs::remove_all(confDir); } + } - void setConfDir() - { - char tmp[] = "/tmp/NetworkManager.XXXXXX"; - confDir = mkdtemp(tmp); - manager.setConfDir(confDir); - } + void setConfDir() + { + char tmp[] = "/tmp/NetworkManager.XXXXXX"; + confDir = mkdtemp(tmp); + manager.setConfDir(confDir); + } - void createInterfaces() - { - manager.createInterfaces(); - } + void createInterfaces() + { + manager.createInterfaces(); + } - int getSize() - { - return manager.interfaces.size(); - } + int getSize() + { + return manager.interfaces.size(); + } - bool isInterfaceAdded(std::string intf) - { - return manager.interfaces.find(intf) != manager.interfaces.end() ? - true : - false; - } + bool isInterfaceAdded(std::string intf) + { + return manager.interfaces.find(intf) != manager.interfaces.end() + ? true + : false; + } }; // getifaddrs will not return any interface @@ -130,5 +128,5 @@ TEST_F(TestNetworkManager, WithMultipleInterfaces) } } -}// namespce network -}// namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/test/test_rtnetlink.cpp b/test/test_rtnetlink.cpp index 203019d..4be3743 100644 --- a/test/test_rtnetlink.cpp +++ b/test/test_rtnetlink.cpp @@ -1,16 +1,15 @@ -#include "types.hpp" -#include "rtnetlink_server.hpp" -#include "network_manager.hpp" #include "mock_syscall.hpp" +#include "network_manager.hpp" +#include "rtnetlink_server.hpp" #include "timer.hpp" #include "types.hpp" +#include +#include -#include #include -#include -#include +#include namespace phosphor { @@ -35,78 +34,68 @@ void refreshObjects() void initializeTimers() { - std::function refreshFunc( - std::bind(&refreshObjects)); - - refreshObjectTimer = - std::make_unique(refreshFunc); + std::function refreshFunc(std::bind(&refreshObjects)); + refreshObjectTimer = std::make_unique(refreshFunc); } class TestRtNetlink : public testing::Test { - public: - std::string confDir; - phosphor::Descriptor smartSock; - + public: + std::string confDir; + phosphor::Descriptor smartSock; + TestRtNetlink() + { + manager = + std::make_unique(bus, "/xyz/openbmc_test/bcd", "/tmp"); + sd_event* events; + sd_event_default(&events); + eventPtr.reset(events); + events = nullptr; + setConfDir(); + initializeTimers(); + createNetLinkSocket(); + bus.attach_event(eventPtr.get(), SD_EVENT_PRIORITY_NORMAL); + rtnetlink::Server svr(eventPtr, smartSock); + } - TestRtNetlink() - { - manager = - std::make_unique(bus, - "/xyz/openbmc_test/bcd", - "/tmp"); - sd_event* events; - sd_event_default(&events); - eventPtr.reset(events); - events = nullptr; - setConfDir(); - initializeTimers(); - createNetLinkSocket(); - bus.attach_event(eventPtr.get(), SD_EVENT_PRIORITY_NORMAL); - rtnetlink::Server svr(eventPtr, smartSock); - } - - ~TestRtNetlink() + ~TestRtNetlink() + { + if (confDir.empty()) { - if (confDir.empty()) - { - fs::remove_all(confDir); - } + fs::remove_all(confDir); } + } - void setConfDir() - { - char tmp[] = "/tmp/NetworkManager.XXXXXX"; - confDir = mkdtemp(tmp); - manager->setConfDir(confDir); - } + void setConfDir() + { + char tmp[] = "/tmp/NetworkManager.XXXXXX"; + confDir = mkdtemp(tmp); + manager->setConfDir(confDir); + } - bool isInterfaceAdded(std::string intf) - { - return manager->interfaces.find(intf) != manager->interfaces.end()? - true : - false; - } + bool isInterfaceAdded(std::string intf) + { + return manager->interfaces.find(intf) != manager->interfaces.end() + ? true + : false; + } - void createNetLinkSocket() - { - //RtnetLink socket - auto fd = socket(PF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, - NETLINK_ROUTE); - smartSock.set(fd); - } + void createNetLinkSocket() + { + // RtnetLink socket + auto fd = socket(PF_NETLINK, SOCK_RAW | SOCK_NONBLOCK, NETLINK_ROUTE); + smartSock.set(fd); + } }; - TEST_F(TestRtNetlink, WithSingleInterface) { using namespace std::chrono; // Adds the following ip in the getifaddrs list. - mock_addIP("igb5", "127.0.0.1", "255.255.255.128", - IFF_UP | IFF_RUNNING); + mock_addIP("igb5", "127.0.0.1", "255.255.255.128", IFF_UP | IFF_RUNNING); constexpr auto BUFSIZE = 4096; std::array msgBuf = {0}; @@ -126,14 +115,13 @@ TEST_F(TestRtNetlink, WithSingleInterface) int i = 3; while (i--) { - //wait for timer to expire - std::this_thread::sleep_for( - std::chrono::milliseconds(refreshTimeout)); + // wait for timer to expire + std::this_thread::sleep_for(std::chrono::milliseconds(refreshTimeout)); sd_event_run(eventPtr.get(), 10); }; EXPECT_EQ(true, isInterfaceAdded("igb5")); } -}// namespce network -}// namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/test/test_util.cpp b/test/test_util.cpp index bc3ec64..437b3cf 100644 --- a/test/test_util.cpp +++ b/test/test_util.cpp @@ -1,7 +1,9 @@ -#include -#include #include "util.hpp" +#include + +#include + namespace phosphor { namespace network @@ -9,12 +11,11 @@ namespace network class TestUtil : public testing::Test { - public: - TestUtil() - { - // Empty - } - + public: + TestUtil() + { + // Empty + } }; TEST_F(TestUtil, IpValidation) @@ -54,8 +55,6 @@ TEST_F(TestUtil, IpValidation) ipaddress = "1::8"; EXPECT_EQ(true, isValidIP(AF_INET6, ipaddress)); - - } TEST_F(TestUtil, PrefixValidation) @@ -77,10 +76,8 @@ TEST_F(TestUtil, PrefixValidation) prefixLength = 65; EXPECT_EQ(false, isValidPrefix(AF_INET, prefixLength)); - } - TEST_F(TestUtil, MacValidation) { std::string macaddress = "00:00:00:00:00:00"; @@ -97,7 +94,6 @@ TEST_F(TestUtil, MacValidation) macaddress = "hhh:GGG:iii:jjj:kkk:lll"; EXPECT_EQ(false, phosphor::network::mac_address::validate(macaddress)); - } TEST_F(TestUtil, ConvertV4MasktoPrefix) @@ -118,7 +114,7 @@ TEST_F(TestUtil, ConvertV4MasktoPrefix) prefix = toCidr(AF_INET, mask); EXPECT_EQ(prefix, 11); - //Invalid Mask + // Invalid Mask mask = "255.0.255.0"; prefix = toCidr(AF_INET, mask); EXPECT_EQ(prefix, 0); @@ -138,7 +134,7 @@ TEST_F(TestUtil, convertV6MasktoPrefix) prefix = toCidr(AF_INET6, mask); EXPECT_EQ(prefix, 38); - //Invalid Mask + // Invalid Mask mask = "ffff:0fff::"; prefix = toCidr(AF_INET6, mask); EXPECT_EQ(prefix, 0); @@ -179,24 +175,24 @@ TEST_F(TestUtil, convertPrefixToMask) TEST_F(TestUtil, getNetworkAddress) { - std::string address = getNetworkID(AF_INET,"9.3.23.251",24); - EXPECT_EQ("9.3.23.0",address); + std::string address = getNetworkID(AF_INET, "9.3.23.251", 24); + EXPECT_EQ("9.3.23.0", address); - address = getNetworkID(AF_INET,"9.3.23.251",25); - EXPECT_EQ("9.3.23.128",address); + address = getNetworkID(AF_INET, "9.3.23.251", 25); + EXPECT_EQ("9.3.23.128", address); - address = getNetworkID(AF_INET6,"2001:db8:abcd:dd12::0",64); - EXPECT_EQ("2001:db8:abcd:dd12::",address); + address = getNetworkID(AF_INET6, "2001:db8:abcd:dd12::0", 64); + EXPECT_EQ("2001:db8:abcd:dd12::", address); - address = getNetworkID(AF_INET,"a.b.c.d",25); - EXPECT_EQ("",address); + address = getNetworkID(AF_INET, "a.b.c.d", 25); + EXPECT_EQ("", address); - address = getNetworkID(AF_INET6,"2001:db8:gghh:dd12::0",64); - EXPECT_EQ("",address); + address = getNetworkID(AF_INET6, "2001:db8:gghh:dd12::0", 64); + EXPECT_EQ("", address); - address = getNetworkID(AF_INET6,"fe80::201:6cff:fe80:228",64); - EXPECT_EQ("fe80::",address); + address = getNetworkID(AF_INET6, "fe80::201:6cff:fe80:228", 64); + EXPECT_EQ("fe80::", address); } -}// namespce network -}// namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/test/test_vlan_interface.cpp b/test/test_vlan_interface.cpp index 00384f1..1bcd87a 100644 --- a/test/test_vlan_interface.cpp +++ b/test/test_vlan_interface.cpp @@ -1,17 +1,18 @@ -#include "network_manager.hpp" -#include "mock_syscall.hpp" #include "config_parser.hpp" -#include "vlan_interface.hpp" #include "ipaddress.hpp" +#include "mock_syscall.hpp" +#include "network_manager.hpp" +#include "vlan_interface.hpp" -#include -#include - +#include #include #include -#include + #include #include +#include + +#include namespace phosphor { @@ -22,98 +23,89 @@ namespace fs = std::experimental::filesystem; class TestVlanInterface : public testing::Test { - public: + public: + sdbusplus::bus::bus bus; + Manager manager; + EthernetInterface interface; + std::string confDir; + TestVlanInterface() : + bus(sdbusplus::bus::new_default()), + manager(bus, "/xyz/openbmc_test/network", "/tmp"), + interface(bus, "/xyz/openbmc_test/network/test0", false, manager) - sdbusplus::bus::bus bus; - Manager manager; - EthernetInterface interface; - std::string confDir; - TestVlanInterface() - : bus(sdbusplus::bus::new_default()), - manager(bus, "/xyz/openbmc_test/network", "/tmp"), - interface(bus, "/xyz/openbmc_test/network/test0", false, manager) - - { - setConfDir(); - } + { + setConfDir(); + } - ~TestVlanInterface() + ~TestVlanInterface() + { + if (confDir != "") { - if(confDir != "") - { - fs::remove_all(confDir); - } + fs::remove_all(confDir); } + } - void setConfDir() - { - char tmp[] = "/tmp/VlanInterface.XXXXXX"; - confDir = mkdtemp(tmp); - manager.setConfDir(confDir); - } + void setConfDir() + { + char tmp[] = "/tmp/VlanInterface.XXXXXX"; + confDir = mkdtemp(tmp); + manager.setConfDir(confDir); + } - void createVlan(VlanId id) - { - interface.createVLAN(id); - } + void createVlan(VlanId id) + { + interface.createVLAN(id); + } - void deleteVlan(const std::string& interfaceName) - { - interface.deleteVLANObject(interfaceName); - } + void deleteVlan(const std::string& interfaceName) + { + interface.deleteVLANObject(interfaceName); + } - int countIPObjects() - { - return interface.getAddresses().size(); - } + int countIPObjects() + { + return interface.getAddresses().size(); + } - bool isIPObjectExist(const std::string& ipaddress) + bool isIPObjectExist(const std::string& ipaddress) + { + auto address = interface.getAddresses().find(ipaddress); + if (address == interface.getAddresses().end()) { - auto address = interface.getAddresses().find(ipaddress); - if (address == interface.getAddresses().end()) - { - return false; - } - return true; - + return false; } + return true; + } - bool deleteIPObject(const std::string& ipaddress) + bool deleteIPObject(const std::string& ipaddress) + { + auto address = interface.getAddresses().find(ipaddress); + if (address == interface.getAddresses().end()) { - auto address = interface.getAddresses().find(ipaddress); - if (address == interface.getAddresses().end()) - { - return false; - } - address->second->delete_(); - return true; + return false; } + address->second->delete_(); + return true; + } - void createIPObject(IP::Protocol addressType, - const std::string& ipaddress, - uint8_t subnetMask, - const std::string& gateway) - { - interface.iP(addressType, - ipaddress, - subnetMask, - gateway - ); - - } + void createIPObject(IP::Protocol addressType, const std::string& ipaddress, + uint8_t subnetMask, const std::string& gateway) + { + interface.iP(addressType, ipaddress, subnetMask, gateway); + } - bool isValueFound(const std::vector& values, - const std::string& expectedValue) + bool isValueFound(const std::vector& values, + const std::string& expectedValue) + { + for (const auto& value : values) { - for (const auto& value : values) + if (expectedValue == value) { - if (expectedValue == value) - { - return true; - } + return true; } - return false; } + return false; + } }; TEST_F(TestVlanInterface, createVLAN) @@ -140,7 +132,6 @@ TEST_F(TestVlanInterface, createVLAN) expectedValue = "50"; found = isValueFound(values, expectedValue); EXPECT_EQ(found, true); - } TEST_F(TestVlanInterface, deleteVLAN) @@ -153,7 +144,7 @@ TEST_F(TestVlanInterface, deleteVLAN) filePath /= "test0.50.netdev"; if (fs::is_regular_file(filePath.string())) { - fileFound = true; + fileFound = true; } EXPECT_EQ(fileFound, false); } @@ -201,5 +192,5 @@ TEST_F(TestVlanInterface, createMultipleVLAN) deleteVlan("test0.60"); } -}// namespce network -}// namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/test/test_watch.cpp b/test/test_watch.cpp index 3ab3e22..167c903 100644 --- a/test/test_watch.cpp +++ b/test/test_watch.cpp @@ -1,10 +1,10 @@ -#include "watch.hpp" #include "types.hpp" +#include "watch.hpp" -#include - -#include #include +#include + +#include static constexpr auto TRIGGER_FILE = "/tmp/" __BASE_FILE__ "netif_state"; @@ -12,52 +12,50 @@ namespace fs = std::experimental::filesystem; class WatchTest : public ::testing::Test { - public: - // systemd event handler - sd_event* events; + public: + // systemd event handler + sd_event* events; - // Need this so that events can be initialized. - int rc; + // Need this so that events can be initialized. + int rc; - // Gets called as part of each TEST_F construction - WatchTest() - : rc(sd_event_default(&events)), - eventPtr(events) - { - // Create a file containing DNS entries like in netif/state - std::ofstream file(TRIGGER_FILE); - file << ""; + // Gets called as part of each TEST_F construction + WatchTest() : rc(sd_event_default(&events)), eventPtr(events) + { + // Create a file containing DNS entries like in netif/state + std::ofstream file(TRIGGER_FILE); + file << ""; - // Check for successful creation of - // event handler - EXPECT_GE(rc, 0); - } + // Check for successful creation of + // event handler + EXPECT_GE(rc, 0); + } - // Gets called as part of each TEST_F destruction - ~WatchTest() + // Gets called as part of each TEST_F destruction + ~WatchTest() + { + if (fs::exists(TRIGGER_FILE)) { - if (fs::exists(TRIGGER_FILE)) - { - fs::remove(TRIGGER_FILE); - } + fs::remove(TRIGGER_FILE); } + } - // unique_ptr for sd_event - phosphor::network::EventPtr eventPtr; + // unique_ptr for sd_event + phosphor::network::EventPtr eventPtr; - // Count of callback invocation - int count = 0; + // Count of callback invocation + int count = 0; - // This is supposed to get hit twice - // Once at the beginning to see if there is anything - // and the second time when the data is fired. - void callBackHandler(const fs::path& file) - { - count++; + // This is supposed to get hit twice + // Once at the beginning to see if there is anything + // and the second time when the data is fired. + void callBackHandler(const fs::path& file) + { + count++; - // Expect that the file is what we wanted - EXPECT_EQ(file, TRIGGER_FILE); - } + // Expect that the file is what we wanted + EXPECT_EQ(file, TRIGGER_FILE); + } }; /** @brief Makes sure that the inotify event is fired @@ -65,9 +63,9 @@ class WatchTest : public ::testing::Test TEST_F(WatchTest, validateEventNotification) { // Create a watch object and register the handler - phosphor::network::inotify::Watch watch(eventPtr, TRIGGER_FILE, - std::bind(&WatchTest::callBackHandler, this, - std::placeholders::_1)); + phosphor::network::inotify::Watch watch( + eventPtr, TRIGGER_FILE, + std::bind(&WatchTest::callBackHandler, this, std::placeholders::_1)); // Reading the event post subscription callBackHandler(TRIGGER_FILE); @@ -82,7 +80,7 @@ TEST_F(WatchTest, validateEventNotification) // Pump the data and get notification { std::ofstream file(TRIGGER_FILE); - file <<"DNS=1.2.3.4\n"; + file << "DNS=1.2.3.4\n"; } sd_event_run(eventPtr.get(), 10); diff --git a/timer.cpp b/timer.cpp index 1dfa5a8..d257433 100644 --- a/timer.cpp +++ b/timer.cpp @@ -22,7 +22,7 @@ void Timer::initialize() elog(); } - auto r = sd_event_default(&timeEvent); + auto r = sd_event_default(&timeEvent); if (r < 0) { log("Failure in creating the sd_event", @@ -32,8 +32,7 @@ void Timer::initialize() } // Add infinite expiration time - r = sd_event_add_time(timeEvent, - &eventSource, + r = sd_event_add_time(timeEvent, &eventSource, CLOCK_MONOTONIC, // Time base UINT64_MAX, // Expire time - way long time 0, // Use default event accuracy @@ -51,8 +50,7 @@ void Timer::initialize() r = setTimer(SD_EVENT_OFF); if (r < 0) { - log("Failure to disable timer", - entry("ERROR=%d", r)); + log("Failure to disable timer", entry("ERROR=%d", r)); elog(); } @@ -60,8 +58,8 @@ void Timer::initialize() } /** @brief callback handler on timeout */ -int Timer::timeoutHandler(sd_event_source* eventSource, - uint64_t usec, void* userData) +int Timer::timeoutHandler(sd_event_source* eventSource, uint64_t usec, + void* userData) { auto timer = static_cast(userData); timer->expired = true; @@ -104,8 +102,7 @@ int Timer::startTimer(std::chrono::microseconds timeValue) auto r = sd_event_source_set_time(eventSource, expireTime.count()); if (r < 0) { - log("Failure to set timer", - entry("ERROR=%d", r)); + log("Failure to set timer", entry("ERROR=%d", r)); elog(); } @@ -115,8 +112,7 @@ int Timer::startTimer(std::chrono::microseconds timeValue) r = setTimer(SD_EVENT_ONESHOT); if (r < 0) { - log("Failure to start timer", - entry("ERROR=%d", r)); + log("Failure to start timer", entry("ERROR=%d", r)); elog(); } diff --git a/timer.hpp b/timer.hpp index 500a7ae..32b6f17 100644 --- a/timer.hpp +++ b/timer.hpp @@ -16,84 +16,84 @@ namespace network */ class Timer { - public: - /** @brief Only need the default Timer */ - Timer() = delete; - Timer(const Timer&) = delete; - Timer& operator=(const Timer&) = delete; - Timer(Timer&&) = delete; - Timer& operator=(Timer&&) = delete; - - /** @brief Constructs timer object - * - * @param[in] funcCallBack - optional function callback for timer - * expirations - */ - Timer(std::function userCallBack = nullptr): - userCallBack(userCallBack) + public: + /** @brief Only need the default Timer */ + Timer() = delete; + Timer(const Timer&) = delete; + Timer& operator=(const Timer&) = delete; + Timer(Timer&&) = delete; + Timer& operator=(Timer&&) = delete; + + /** @brief Constructs timer object + * + * @param[in] funcCallBack - optional function callback for timer + * expirations + */ + Timer(std::function userCallBack = nullptr) : + userCallBack(userCallBack) + { + // Initialize the timer + initialize(); + } + + ~Timer() + { + if (eventSource) { - // Initialize the timer - initialize(); + eventSource = sd_event_source_unref(eventSource); } - - ~Timer() + if (timeEvent) { - if (eventSource) - { - eventSource = sd_event_source_unref(eventSource); - } - if(timeEvent) - { - timeEvent = sd_event_unref(timeEvent); - } + timeEvent = sd_event_unref(timeEvent); } - - inline auto isExpired() const - { - return expired; - } - - /** @brief Starts the timer with specified expiration value. - * input is an offset from the current steady_clock - */ - int startTimer(std::chrono::microseconds usec); - - /** @brief Enables / disables the timer */ - int setTimer(int action); - - private: - /** @brief the sd_event structure */ - sd_event* timeEvent = nullptr; - - /** @brief Source of events */ - sd_event_source* eventSource = nullptr; - - bool expired = true; - - /** @brief Initializes the timer object with infinite - * expiration time and sets up the callback handler - * - * @return None. - * - * @error std::runtime exception thrown - */ - void initialize(); - - /** @brief Callback function when timer goes off - * - * @param[in] eventSource - Source of the event - * @param[in] usec - time in micro seconds - * @param[in] userData - User data pointer - * - */ - static int timeoutHandler(sd_event_source* eventSource, - uint64_t usec, void* userData); - - /** @brief Gets the current time from steady clock */ - static std::chrono::microseconds getTime(); - - /** @brief Optional function to call on timer expiration */ - std::function userCallBack; + } + + inline auto isExpired() const + { + return expired; + } + + /** @brief Starts the timer with specified expiration value. + * input is an offset from the current steady_clock + */ + int startTimer(std::chrono::microseconds usec); + + /** @brief Enables / disables the timer */ + int setTimer(int action); + + private: + /** @brief the sd_event structure */ + sd_event* timeEvent = nullptr; + + /** @brief Source of events */ + sd_event_source* eventSource = nullptr; + + bool expired = true; + + /** @brief Initializes the timer object with infinite + * expiration time and sets up the callback handler + * + * @return None. + * + * @error std::runtime exception thrown + */ + void initialize(); + + /** @brief Callback function when timer goes off + * + * @param[in] eventSource - Source of the event + * @param[in] usec - time in micro seconds + * @param[in] userData - User data pointer + * + */ + static int timeoutHandler(sd_event_source* eventSource, uint64_t usec, + void* userData); + + /** @brief Gets the current time from steady clock */ + static std::chrono::microseconds getTime(); + + /** @brief Optional function to call on timer expiration */ + std::function userCallBack; }; } // namespace network diff --git a/types.hpp b/types.hpp index c155e40..b8038b4 100644 --- a/types.hpp +++ b/types.hpp @@ -35,12 +35,13 @@ constexpr auto networkFilePrefix = "00-bmc-"; constexpr auto networkFileSuffix = ".network"; constexpr auto deviceFileSuffix = ".netdev"; -}// namespace config -}// namespace systemd +} // namespace config +} // namespace systemd using IntfName = std::string; -struct AddrInfo { +struct AddrInfo +{ uint8_t addrType; std::string ipaddress; uint16_t prefix; @@ -68,12 +69,12 @@ struct EventDeleter }; using EventPtr = std::unique_ptr; -template +template using UniquePtr = std::unique_ptr>; using AddrList = std::list; using IntfAddrMap = std::map; using InterfaceList = std::set; -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/util.cpp b/util.cpp index 4297590..b66f908 100644 --- a/util.cpp +++ b/util.cpp @@ -34,12 +34,12 @@ uint8_t toV6Cidr(const std::string& subnetMask) uint8_t pos = 0; uint8_t prevPos = 0; uint8_t cidr = 0; - uint16_t buff {}; + uint16_t buff{}; do { - //subnet mask look like ffff:ffff:: + // subnet mask look like ffff:ffff:: // or ffff:c000:: - pos = subnetMask.find(":", prevPos); + pos = subnetMask.find(":", prevPos); if (pos == std::string::npos) { break; @@ -53,7 +53,7 @@ uint8_t toV6Cidr(const std::string& subnetMask) { return cidr; } - //converts it into number. + // converts it into number. if (sscanf(str.c_str(), "%hx", &buff) <= 0) { log("Invalid Mask", @@ -69,7 +69,8 @@ uint8_t toV6Cidr(const std::string& subnetMask) if (__builtin_popcount(buff) != 16) { - if (((sizeof(buff) * 8) - (__builtin_ctz(buff))) != __builtin_popcount(buff)) + if (((sizeof(buff) * 8) - (__builtin_ctz(buff))) != + __builtin_popcount(buff)) { log("Invalid Mask", entry("SUBNETMASK=%s", subnetMask.c_str())); @@ -81,12 +82,11 @@ uint8_t toV6Cidr(const std::string& subnetMask) } cidr += 16; - } - while (1); + } while (1); return cidr; } -}// anonymous namespace +} // anonymous namespace uint8_t toCidr(int addressFamily, const std::string& subnetMask) { @@ -107,7 +107,8 @@ uint8_t toCidr(int addressFamily, const std::string& subnetMask) buff = be32toh(buff); // total no of bits - total no of leading zero == total no of ones - if (((sizeof(buff) * 8) - (__builtin_ctz(buff))) == __builtin_popcount(buff)) + if (((sizeof(buff) * 8) - (__builtin_ctz(buff))) == + __builtin_popcount(buff)) { return __builtin_popcount(buff); } @@ -123,19 +124,18 @@ std::string toMask(int addressFamily, uint8_t prefix) { if (addressFamily == AF_INET6) { - //TODO:- conversion for v6 + // TODO:- conversion for v6 return ""; } if (prefix < 1 || prefix > 30) { - log("Invalid Prefix", - entry("PREFIX=%d", prefix)); + log("Invalid Prefix", entry("PREFIX=%d", prefix)); return ""; } /* Create the netmask from the number of bits */ unsigned long mask = 0; - for (auto i = 0 ; i < prefix ; i++) + for (auto i = 0; i < prefix; i++) { mask |= 1 << (31 - i); } @@ -149,12 +149,13 @@ std::string getNetworkID(int addressFamily, const std::string& ipaddress, { unsigned char* pntMask = nullptr; unsigned char* pntNetwork = nullptr; - int bit {}; - int offset {}; - struct in6_addr netmask {}; + int bit{}; + int offset{}; + struct in6_addr netmask + { + }; const u_char maskbit[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0, - 0xf8, 0xfc, 0xfe, 0xff - }; + 0xf8, 0xfc, 0xfe, 0xff}; pntMask = reinterpret_cast(&netmask); @@ -186,13 +187,13 @@ std::string getNetworkID(int addressFamily, const std::string& ipaddress, pntMask = reinterpret_cast(&netmask); pntNetwork = reinterpret_cast(&ipaddressNetwork); - for (int i = 0; i < 16 ; i++) + for (int i = 0; i < 16; i++) { pntNetwork[i] = pntNetwork[i] & pntMask[i]; } - //convert the network address into string fomat. - char networkString[INET6_ADDRSTRLEN] = { 0 }; + // convert the network address into string fomat. + char networkString[INET6_ADDRSTRLEN] = {0}; if (inet_ntop(addressFamily, &ipaddressNetwork, networkString, INET6_ADDRSTRLEN) == NULL) { @@ -239,7 +240,7 @@ bool isValidPrefix(int addressFamily, uint8_t prefixLength) IntfAddrMap getInterfaceAddrs() { - IntfAddrMap intfMap {}; + IntfAddrMap intfMap{}; struct ifaddrs* ifaddr = nullptr; // attempt to fill struct with ifaddrs @@ -254,7 +255,7 @@ IntfAddrMap getInterfaceAddrs() AddrPtr ifaddrPtr(ifaddr); ifaddr = nullptr; - std::string intfName {}; + std::string intfName{}; for (ifaddrs* ifa = ifaddrPtr.get(); ifa != nullptr; ifa = ifa->ifa_next) { @@ -275,36 +276,32 @@ IntfAddrMap getInterfaceAddrs() continue; } intfName = ifa->ifa_name; - AddrInfo info {}; - char ip[INET6_ADDRSTRLEN] = { 0 }; - char subnetMask[INET6_ADDRSTRLEN] = { 0 }; + AddrInfo info{}; + char ip[INET6_ADDRSTRLEN] = {0}; + char subnetMask[INET6_ADDRSTRLEN] = {0}; if (ifa->ifa_addr->sa_family == AF_INET) { inet_ntop(ifa->ifa_addr->sa_family, &(((struct sockaddr_in*)(ifa->ifa_addr))->sin_addr), - ip, - sizeof(ip)); - - inet_ntop(ifa->ifa_addr->sa_family, - &(((struct sockaddr_in*)(ifa->ifa_netmask))->sin_addr), - subnetMask, - sizeof(subnetMask)); + ip, sizeof(ip)); + inet_ntop( + ifa->ifa_addr->sa_family, + &(((struct sockaddr_in*)(ifa->ifa_netmask))->sin_addr), + subnetMask, sizeof(subnetMask)); } else { inet_ntop(ifa->ifa_addr->sa_family, &(((struct sockaddr_in6*)(ifa->ifa_addr))->sin6_addr), - ip, - sizeof(ip)); - - inet_ntop(ifa->ifa_addr->sa_family, - &(((struct sockaddr_in6*)(ifa->ifa_netmask))->sin6_addr), - subnetMask, - sizeof(subnetMask)); + ip, sizeof(ip)); + inet_ntop( + ifa->ifa_addr->sa_family, + &(((struct sockaddr_in6*)(ifa->ifa_netmask))->sin6_addr), + subnetMask, sizeof(subnetMask)); } info.addrType = ifa->ifa_addr->sa_family; @@ -318,7 +315,7 @@ IntfAddrMap getInterfaceAddrs() InterfaceList getInterfaces() { - InterfaceList interfaces {}; + InterfaceList interfaces{}; struct ifaddrs* ifaddr = nullptr; // attempt to fill struct with ifaddrs @@ -337,8 +334,7 @@ InterfaceList getInterfaces() { // walk interfaces // if loopback, or not running ignore - if ((ifa->ifa_flags & IFF_LOOPBACK) || - !(ifa->ifa_flags & IFF_RUNNING)) + if ((ifa->ifa_flags & IFF_LOOPBACK) || !(ifa->ifa_flags & IFF_RUNNING)) { continue; } @@ -347,27 +343,24 @@ InterfaceList getInterfaces() return interfaces; } - void deleteInterface(const std::string& intf) { pid_t pid = fork(); - int status {}; + int status{}; if (pid == 0) { execl("/sbin/ip", "ip", "link", "delete", "dev", intf.c_str(), nullptr); auto error = errno; - log("Couldn't delete the device", - entry("ERRNO=%d", error), + log("Couldn't delete the device", entry("ERRNO=%d", error), entry("INTF=%s", intf.c_str())); elog(); } else if (pid < 0) { auto error = errno; - log("Error occurred during fork", - entry("ERRNO=%d", error)); + log("Error occurred during fork", entry("ERRNO=%d", error)); elog(); } else if (pid > 0) @@ -375,13 +368,13 @@ void deleteInterface(const std::string& intf) while (waitpid(pid, &status, 0) == -1) { if (errno != EINTR) - { /* Error other than EINTR */ + { /* Error other than EINTR */ status = -1; break; } } - if(status < 0) + if (status < 0) { log("Unable to delete the interface", entry("INTF=%s", intf.c_str()), @@ -395,7 +388,7 @@ bool getDHCPValue(const std::string& confDir, const std::string& intf) { bool dhcp = false; // Get the interface mode value from systemd conf - //using namespace std::string_literals; + // using namespace std::string_literals; fs::path confPath = confDir; std::string fileName = systemd::config::networkFilePrefix + intf + systemd::config::networkFileSuffix; @@ -409,7 +402,7 @@ bool getDHCPValue(const std::string& confDir, const std::string& intf) if (rc != config::ReturnCode::SUCCESS) { log("Unable to get the value for Network[DHCP]", - entry("RC=%d", rc)); + entry("RC=%d", rc)); return dhcp; } // There will be only single value for DHCP key. @@ -427,7 +420,7 @@ void executeCommandinChildProcess(const char* path, char** args) { using namespace std::string_literals; pid_t pid = fork(); - int status {}; + int status{}; if (pid == 0) { @@ -436,9 +429,9 @@ void executeCommandinChildProcess(const char* path, char** args) // create the command from var args. std::string command = path + " "s; - for(int i = 0; args[i]; i++) + for (int i = 0; args[i]; i++) { - command += args[i] + " "s; + command += args[i] + " "s; } log("Couldn't exceute the command", @@ -449,8 +442,7 @@ void executeCommandinChildProcess(const char* path, char** args) else if (pid < 0) { auto error = errno; - log("Error occurred during fork", - entry("ERRNO=%d", error)); + log("Error occurred during fork", entry("ERRNO=%d", error)); elog(); } else if (pid > 0) @@ -458,16 +450,16 @@ void executeCommandinChildProcess(const char* path, char** args) while (waitpid(pid, &status, 0) == -1) { if (errno != EINTR) - { //Error other than EINTR + { // Error other than EINTR status = -1; break; } } - if(status < 0) + if (status < 0) { std::string command = path + " "s; - for(int i = 0; args[i]; i++) + for (int i = 0; args[i]; i++) { command += args[i] + " "s; } @@ -478,9 +470,8 @@ void executeCommandinChildProcess(const char* path, char** args) elog(); } } - } -} //namespace internal +} // namespace internal namespace mac_address { @@ -494,12 +485,12 @@ constexpr auto methodGet = "Get"; using DbusObjectPath = std::string; using DbusService = std::string; using DbusInterface = std::string; -using ObjectTree = std::map>>; +using ObjectTree = + std::map>>; constexpr auto invBus = "xyz.openbmc_project.Inventory.Manager"; constexpr auto invNetworkIntf = - "xyz.openbmc_project.Inventory.Item.NetworkInterface"; + "xyz.openbmc_project.Inventory.Item.NetworkInterface"; constexpr auto invRoot = "/xyz/openbmc_project/inventory"; std::string getfromInventory(sdbusplus::bus::bus& bus) @@ -509,10 +500,8 @@ std::string getfromInventory(sdbusplus::bus::bus& bus) auto depth = 0; - auto mapperCall = bus.new_method_call(mapperBus, - mapperObj, - mapperIntf, - "GetSubTree"); + auto mapperCall = + bus.new_method_call(mapperBus, mapperObj, mapperIntf, "GetSubTree"); mapperCall.append(invRoot, depth, interfaces); @@ -540,18 +529,15 @@ std::string getfromInventory(sdbusplus::bus::bus& bus) sdbusplus::message::variant value; - auto method = bus.new_method_call( - service.c_str(), - objPath.c_str(), - propIntf, - methodGet); + auto method = bus.new_method_call(service.c_str(), objPath.c_str(), + propIntf, methodGet); method.append(invNetworkIntf, "MACAddress"); auto reply = bus.call(method); if (reply.is_method_error()) { - log("Failed to get MACAddress", + log("Failed to get MACAddress", entry("PATH=%s", objPath.c_str()), entry("INTERFACE=%s", invNetworkIntf)); elog(); @@ -561,6 +547,6 @@ std::string getfromInventory(sdbusplus::bus::bus& bus) return value.get(); } -}//namespace mac_address -}//namespace network -}//namespace phosphor +} // namespace mac_address +} // namespace network +} // namespace phosphor diff --git a/util.hpp b/util.hpp index 3df928d..b3ec771 100644 --- a/util.hpp +++ b/util.hpp @@ -1,6 +1,7 @@ #pragma once #include "config.h" + #include "types.hpp" #include @@ -56,19 +57,17 @@ inline uint64_t convertToInt(const std::string& value) { unsigned char mac[6]; - sscanf(value.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", - mac + 0, mac + 1, mac + 2, mac + 3, mac + 4, mac + 5); - return - static_cast(mac[0]) << 40 | - static_cast(mac[1]) << 32 | - static_cast(mac[2]) << 24 | - static_cast(mac[3]) << 16 | - static_cast(mac[4]) << 8 | - static_cast(mac[5]); + sscanf(value.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", mac + 0, mac + 1, + mac + 2, mac + 3, mac + 4, mac + 5); + return static_cast(mac[0]) << 40 | + static_cast(mac[1]) << 32 | + static_cast(mac[2]) << 24 | + static_cast(mac[3]) << 16 | + static_cast(mac[4]) << 8 | static_cast(mac[5]); } -}//namespace internal -}//namespace mac_address +} // namespace internal +} // namespace mac_address constexpr auto networkdService = "systemd-networkd.service"; constexpr auto timeSynchdService = "systemd-timesyncd.service"; @@ -129,15 +128,11 @@ IntfAddrMap getInterfaceAddrs(); inline void restartSystemdUnit(const std::string& unit) { auto bus = sdbusplus::bus::new_default(); - auto method = bus.new_method_call( - SYSTEMD_BUSNAME, - SYSTEMD_PATH, - SYSTEMD_INTERFACE, - "RestartUnit"); + auto method = bus.new_method_call(SYSTEMD_BUSNAME, SYSTEMD_PATH, + SYSTEMD_INTERFACE, "RestartUnit"); method.append(unit, "replace"); bus.call_noreply(method); - } /** @brief Get all the interfaces from the system. @@ -171,66 +166,68 @@ void executeCommandinChildProcess(const char* path, char** args); * @param[in] path -path of the binary file which needs to be execeuted. * @param[in] tArgs - arguments of the command. */ -template +template void execute(const char* path, ArgTypes&&... tArgs) { - using expandType = char*[]; + using expandType = char* []; - expandType args = { const_cast(tArgs)..., nullptr }; + expandType args = {const_cast(tArgs)..., nullptr}; internal::executeCommandinChildProcess(path, args); } -} //namespace network +} // namespace network class Descriptor { - private: - /** default value */ - int fd = -1; - - public: - Descriptor() = default; - Descriptor(const Descriptor&) = delete; - Descriptor& operator=(const Descriptor&) = delete; - Descriptor(Descriptor&&) = delete; - Descriptor& operator=(Descriptor &&) = delete; - - explicit Descriptor(int fd) : fd(fd) {} - - /* @brief sets the internal file descriptor with the given descriptor - * and closes the old descriptor. - * @param[in] descriptor - File/Socket descriptor. - */ - void set(int descriptor) + private: + /** default value */ + int fd = -1; + + public: + Descriptor() = default; + Descriptor(const Descriptor&) = delete; + Descriptor& operator=(const Descriptor&) = delete; + Descriptor(Descriptor&&) = delete; + Descriptor& operator=(Descriptor&&) = delete; + + explicit Descriptor(int fd) : fd(fd) + { + } + + /* @brief sets the internal file descriptor with the given descriptor + * and closes the old descriptor. + * @param[in] descriptor - File/Socket descriptor. + */ + void set(int descriptor) + { + // same descriptor given + if (fd == descriptor) { - // same descriptor given - if (fd == descriptor) - { - return; - } - - // close the old descriptor - if (fd >= 0) - { - close(fd); - } - - fd = descriptor; + return; } - ~Descriptor() + // close the old descriptor + if (fd >= 0) { - if (fd >= 0) - { - close(fd); - } + close(fd); } - int operator()() const + fd = descriptor; + } + + ~Descriptor() + { + if (fd >= 0) { - return fd; + close(fd); } + } + + int operator()() const + { + return fd; + } }; -} //namespace phosphor +} // namespace phosphor diff --git a/vlan_interface.cpp b/vlan_interface.cpp index e7854de..6ef1a0c 100644 --- a/vlan_interface.cpp +++ b/vlan_interface.cpp @@ -1,6 +1,7 @@ +#include "config.h" + #include "vlan_interface.hpp" -#include "config.h" #include "ethernet_interface.hpp" #include "network_manager.hpp" @@ -21,15 +22,13 @@ using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; VlanInterface::VlanInterface(sdbusplus::bus::bus& bus, - const std::string& objPath, - bool dhcpEnabled, - uint32_t vlanID, - EthernetInterface& intf, - Manager& parent ) : - VlanIface(bus,objPath.c_str()), - DeleteIface(bus,objPath.c_str()), - EthernetInterface(bus, objPath, dhcpEnabled, parent, false), - parentInterface(intf) + const std::string& objPath, bool dhcpEnabled, + uint32_t vlanID, EthernetInterface& intf, + Manager& parent) : + VlanIface(bus, objPath.c_str()), + DeleteIface(bus, objPath.c_str()), + EthernetInterface(bus, objPath, dhcpEnabled, parent, false), + parentInterface(intf) { id(vlanID); VlanIface::interfaceName(EthernetInterface::interfaceName()); @@ -52,16 +51,19 @@ void VlanInterface::writeDeviceFile() catch (std::ios_base::failure& e) { log("Unable to open the VLAN device file", - entry("FILE=%s", confPath.c_str()), - entry("ERROR=%s", e.what())); + entry("FILE=%s", confPath.c_str()), + entry("ERROR=%s", e.what())); elog(); - } - stream << "[" << "NetDev" << "]\n"; + stream << "[" + << "NetDev" + << "]\n"; stream << "Name=" << EthernetInterface::interfaceName() << "\n"; - stream << "Kind=vlan" << "\n"; - stream << "[VLAN]" << "\n"; + stream << "Kind=vlan" + << "\n"; + stream << "[VLAN]" + << "\n"; stream << "Id=" << id() << "\n"; stream.close(); } @@ -71,5 +73,5 @@ void VlanInterface::delete_() parentInterface.deleteVLANObject(EthernetInterface::interfaceName()); } -}//namespace network -}//namespace phosphor +} // namespace network +} // namespace phosphor diff --git a/vlan_interface.hpp b/vlan_interface.hpp index e1feda7..3ef98eb 100644 --- a/vlan_interface.hpp +++ b/vlan_interface.hpp @@ -17,7 +17,6 @@ namespace network class EthernetInterface; class Manager; - using DeleteIface = sdbusplus::xyz::openbmc_project::Object::server::Delete; using VlanIface = sdbusplus::xyz::openbmc_project::Network::server::VLAN; @@ -29,52 +28,48 @@ class VlanInterface : public VlanIface, public DeleteIface, public EthernetInterface { - public: - VlanInterface() = delete; - VlanInterface(const VlanInterface&) = delete; - VlanInterface& operator=(const VlanInterface&) = delete; - VlanInterface(VlanInterface&&) = delete; - VlanInterface& operator=(VlanInterface&&) = delete; - virtual ~VlanInterface() = default; - - /** @brief Constructor to put object onto bus at a dbus path. - * @param[in] bus - Bus to attach to. - * @param[in] objPath - Path to attach at. - * @param[in] dhcpEnabled - DHCP enable value. - * @param[in] vlanID - vlan identifier. - * @param[in] intf - ethernet interface object. - * @param[in] manager - network manager object. - */ - VlanInterface(sdbusplus::bus::bus& bus, - const std::string& objPath, - bool dhcpEnabled, - uint32_t vlanID, - EthernetInterface& intf, - Manager& manager); - - /** @brief Delete this d-bus object. - */ - void delete_() override; - - /** @brief writes the device configuration. - systemd reads this configuration file - and creates the vlan interface.*/ - void writeDeviceFile(); - - /** @brief copy the mac address from the parent interface.*/ - void updateMacAddress() - { - MacAddressIntf::mACAddress(parentInterface.mACAddress()); - } - - private: - - /** @brief VLAN Identifier. */ - using VlanIface::id; - - EthernetInterface& parentInterface; - - friend class TestVlanInterface; + public: + VlanInterface() = delete; + VlanInterface(const VlanInterface&) = delete; + VlanInterface& operator=(const VlanInterface&) = delete; + VlanInterface(VlanInterface&&) = delete; + VlanInterface& operator=(VlanInterface&&) = delete; + virtual ~VlanInterface() = default; + + /** @brief Constructor to put object onto bus at a dbus path. + * @param[in] bus - Bus to attach to. + * @param[in] objPath - Path to attach at. + * @param[in] dhcpEnabled - DHCP enable value. + * @param[in] vlanID - vlan identifier. + * @param[in] intf - ethernet interface object. + * @param[in] manager - network manager object. + */ + VlanInterface(sdbusplus::bus::bus& bus, const std::string& objPath, + bool dhcpEnabled, uint32_t vlanID, EthernetInterface& intf, + Manager& manager); + + /** @brief Delete this d-bus object. + */ + void delete_() override; + + /** @brief writes the device configuration. + systemd reads this configuration file + and creates the vlan interface.*/ + void writeDeviceFile(); + + /** @brief copy the mac address from the parent interface.*/ + void updateMacAddress() + { + MacAddressIntf::mACAddress(parentInterface.mACAddress()); + } + + private: + /** @brief VLAN Identifier. */ + using VlanIface::id; + + EthernetInterface& parentInterface; + + friend class TestVlanInterface; }; } // namespace network diff --git a/watch.cpp b/watch.cpp index ffac972..89fef81 100644 --- a/watch.cpp +++ b/watch.cpp @@ -17,17 +17,10 @@ namespace inotify using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; -Watch::Watch(phosphor::network::EventPtr& eventPtr, - fs::path path, - UserCallBack userFunc, - int flags, - uint32_t mask, - uint32_t events) : +Watch::Watch(phosphor::network::EventPtr& eventPtr, fs::path path, + UserCallBack userFunc, int flags, uint32_t mask, uint32_t events) : path(path), - userFunc(userFunc), - flags(flags), - mask(mask), - events(events), + userFunc(userFunc), flags(flags), mask(mask), events(events), fd(inotifyInit()) { // Check if watch file exists @@ -50,12 +43,8 @@ Watch::Watch(phosphor::network::EventPtr& eventPtr, // Register the fd with sd_event infrastructure and setup a // callback handler to be invoked on events - auto rc = sd_event_add_io(eventPtr.get(), - nullptr, - fd(), - events, - Watch::processEvents, - this); + auto rc = sd_event_add_io(eventPtr.get(), nullptr, fd(), events, + Watch::processEvents, this); if (rc < 0) { // Failed to add to event loop @@ -70,17 +59,14 @@ int Watch::inotifyInit() auto fd = inotify_init1(flags); if (fd < 0) { - log("Error from inotify_init1", - entry("ERRNO=%d", errno)); + log("Error from inotify_init1", entry("ERRNO=%d", errno)); elog(); } return fd; } -int Watch::processEvents(sd_event_source* eventSource, - int fd, - uint32_t retEvents, - void* userData) +int Watch::processEvents(sd_event_source* eventSource, int fd, + uint32_t retEvents, void* userData) { auto watch = static_cast(userData); @@ -117,8 +103,8 @@ int Watch::processEvents(sd_event_source* eventSource, auto mask = event->mask & watch->mask; if (mask) { - if((event->len > 0) && - (strstr(event->name, stateFile.string().c_str()))) + if ((event->len > 0) && + (strstr(event->name, stateFile.string().c_str()))) { if (watch->userFunc) { diff --git a/watch.hpp b/watch.hpp index 6a274aa..bffed3e 100644 --- a/watch.hpp +++ b/watch.hpp @@ -1,8 +1,8 @@ #pragma once #include "dns_updater.hpp" -#include "util.hpp" #include "types.hpp" +#include "util.hpp" #include #include @@ -31,82 +31,77 @@ using UserCallBack = std::function; */ class Watch { - public: - Watch() = delete; - Watch(const Watch&) = delete; - Watch& operator=(const Watch&) = delete; - Watch(Watch&&) = delete; - Watch& operator=(Watch&&) = delete; - - /** @brief Hooks inotify watch with sd-event - * - * @param[in] eventPtr - Reference to sd_event wrapped in unique_ptr - * @param[in] path - File path to be watched - * @param[in] userFunc - User specific callback function on events - * @param[in] flags - Flags to be supplied to inotify - * @param[in] mask - Mask of events to be supplied to inotify - * @param[in] events - Events to be watched - */ - Watch(phosphor::network::EventPtr& eventPtr, - const fs::path path, - UserCallBack userFunc, - int flags = IN_NONBLOCK, - uint32_t mask = IN_CLOSE_WRITE, - uint32_t events = EPOLLIN); - - /** @brief Remove inotify watch and close fd's */ - ~Watch() + public: + Watch() = delete; + Watch(const Watch&) = delete; + Watch& operator=(const Watch&) = delete; + Watch(Watch&&) = delete; + Watch& operator=(Watch&&) = delete; + + /** @brief Hooks inotify watch with sd-event + * + * @param[in] eventPtr - Reference to sd_event wrapped in unique_ptr + * @param[in] path - File path to be watched + * @param[in] userFunc - User specific callback function on events + * @param[in] flags - Flags to be supplied to inotify + * @param[in] mask - Mask of events to be supplied to inotify + * @param[in] events - Events to be watched + */ + Watch(phosphor::network::EventPtr& eventPtr, const fs::path path, + UserCallBack userFunc, int flags = IN_NONBLOCK, + uint32_t mask = IN_CLOSE_WRITE, uint32_t events = EPOLLIN); + + /** @brief Remove inotify watch and close fd's */ + ~Watch() + { + if ((fd() >= 0) && (wd >= 0)) { - if ((fd() >= 0) && (wd >= 0)) - { - inotify_rm_watch(fd(), wd); - } + inotify_rm_watch(fd(), wd); } - - private: - /** @brief Callback invoked when inotify event fires - * - * @details On a matching event, calls back into user supplied - * function if there is one registered - * - * @param[in] eventSource - Event source - * @param[in] fd - Inotify fd - * @param[in] retEvents - Events that matched for fd - * @param[in] userData - Pointer to Watch object - * - * @returns 0 on success, -1 on fail - */ - static int processEvents(sd_event_source* eventSource, - int fd, - uint32_t retEvents, - void* userData); - - /** @brief Initializes an inotify instance - * - * @return Descriptor on success, -1 on failure - */ - int inotifyInit(); - - /** @brief File path to be watched */ - const fs::path path; - - /** @brief User callback function */ - UserCallBack userFunc; - - /** @brief Inotify flags */ - int flags; - - /** @brief Mask of events */ - uint32_t mask; - - /** @brief Events to be watched */ - uint32_t events; - - /** @brief Watch descriptor */ - int wd = -1; - - /** @brief File descriptor manager */ - phosphor::Descriptor fd; + } + + private: + /** @brief Callback invoked when inotify event fires + * + * @details On a matching event, calls back into user supplied + * function if there is one registered + * + * @param[in] eventSource - Event source + * @param[in] fd - Inotify fd + * @param[in] retEvents - Events that matched for fd + * @param[in] userData - Pointer to Watch object + * + * @returns 0 on success, -1 on fail + */ + static int processEvents(sd_event_source* eventSource, int fd, + uint32_t retEvents, void* userData); + + /** @brief Initializes an inotify instance + * + * @return Descriptor on success, -1 on failure + */ + int inotifyInit(); + + /** @brief File path to be watched */ + const fs::path path; + + /** @brief User callback function */ + UserCallBack userFunc; + + /** @brief Inotify flags */ + int flags; + + /** @brief Mask of events */ + uint32_t mask; + + /** @brief Events to be watched */ + uint32_t events; + + /** @brief Watch descriptor */ + int wd = -1; + + /** @brief File descriptor manager */ + phosphor::Descriptor fd; }; } // namespace inotify -- cgit v1.2.1