diff --git a/.github/actions/clang_format/action.yml b/.github/actions/clang_format/action.yml index c228abe77d..30a9f44f8f 100644 --- a/.github/actions/clang_format/action.yml +++ b/.github/actions/clang_format/action.yml @@ -33,6 +33,9 @@ runs: shell: bash run: | + # Print clanformat version used. + echo "Clang-format version: $(clang-format --version)" + # Don't apply changes, just check arguments="--dry-run " diff --git a/.gitignore b/.gitignore index 33ba1d926c..a35c969e0d 100644 --- a/.gitignore +++ b/.gitignore @@ -37,8 +37,5 @@ __pycache__ ### Python Virtualenv venv -# Auto generated build files -src/**/build/* - # External dependencies src/external/* diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c63f41c6b2..8f0a28a6ad 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -31,4 +31,4 @@ configure_target(Agent) if(BUILD_TESTS) enable_testing() -endif() \ No newline at end of file +endif() diff --git a/src/Makefile b/src/Makefile index f243123fb4..2abdcf1dca 100644 --- a/src/Makefile +++ b/src/Makefile @@ -11,42 +11,16 @@ uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not') uname_P := $(shell sh -c 'uname -p 2>/dev/null || echo not') -uname_R := $(shell sh -c 'uname -r 2>/dev/null || echo not') -uname_V := $(shell sh -c 'uname -v 2>/dev/null || echo not') uname_M := $(shell sh -c 'uname -m 2>/dev/null || echo not') ifeq (${uname_S},Linux) PRECOMPILED_OS:=linux else -ifeq (${uname_S},AIX) - PRECOMPILED_OS:=aix -else -ifeq (${uname_S},SunOS) - PRECOMPILED_OS:=solaris -else ifeq (${uname_S},Darwin) PRECOMPILED_OS:=darwin else -ifeq (${uname_S},FreeBSD) - PRECOMPILED_OS:=freebsd -else -ifeq (${uname_S},NetBSD) - PRECOMPILED_OS:=netbsd -else -ifeq (${uname_S},OpenBSD) - PRECOMPILED_OS:=openbsd -else -ifeq (${uname_S},HP-UX) - PRECOMPILED_OS:=hpux -else - # Unknow platform -endif # HPUX -endif # OpenBSD -endif # NetBSD -endif # FreeBSD + # Unknow platform endif # Darwin -endif # SunOS -endif # AIX endif # Linux # ################################ @@ -61,49 +35,17 @@ DEPS_VERSION = 30 RESOURCES_URL_BASE := https://packages.wazuh.com/deps/ RESOURCES_URL := $(RESOURCES_URL_BASE)$(DEPS_VERSION) -ifneq (,$(filter ${uname_S},Linux Darwin HP-UX)) +ifneq (,$(filter ${uname_S},Linux Darwin)) cpu_arch := ${uname_M} ifneq (,$(filter ${cpu_arch},x86_64 amd64)) PRECOMPILED_ARCH := /amd64 else -ifneq (,$(filter ${cpu_arch},i386 i686)) - PRECOMPILED_ARCH := /i386 -else ifneq (,$(filter ${cpu_arch},aarch64 arm64)) PRECOMPILED_ARCH := /aarch64 -else -ifneq (,$(filter ${cpu_arch},armv8l armv7l arm32 armhf)) - PRECOMPILED_ARCH := /arm32 -else -ifeq (${cpu_arch},ppc64le) - PRECOMPILED_ARCH := /ppc64le -else -ifneq (,$(filter ${cpu_arch},ia64)) - PRECOMPILED_ARCH := /ia64 else PRECOMPILED_ARCH := /${uname_P} endif endif -endif -endif -endif -endif -else -ifneq (,$(filter ${uname_S},SunOS AIX)) - cpu_arch := ${uname_P} -ifeq (${cpu_arch},powerpc) - PRECOMPILED_ARCH := /powerpc -else -ifneq (,$(filter ${cpu_arch},sparc sun4u)) - PRECOMPILED_ARCH := /sparc -else -ifneq (,$(filter ${cpu_arch},i386 i86pc)) - PRECOMPILED_ARCH := /i386 -else - PRECOMPILED_ARCH := /${uname_M} -endif -endif -endif else cpu_arch := ${uname_M} ifneq (,$(filter ${cpu_arch},unknown Unknown not)) @@ -111,12 +53,11 @@ ifneq (,$(filter ${cpu_arch},unknown Unknown not)) endif PRECOMPILED_ARCH := /${cpu_arch} endif -endif PRECOMPILED_RES := $(PRECOMPILED_OS)$(PRECOMPILED_ARCH) # Agent dependencies -EXTERNAL_RES := libdb procps pacman rpm +EXTERNAL_RES := libdb procps rpm EXTERNAL_DIR := $(EXTERNAL_RES:%=external/%) EXTERNAL_TAR := $(EXTERNAL_RES:%=external/%.tar.gz) diff --git a/src/agent/CMakeLists.txt b/src/agent/CMakeLists.txt index 3b16647a2c..519fcaf459 100644 --- a/src/agent/CMakeLists.txt +++ b/src/agent/CMakeLists.txt @@ -34,7 +34,7 @@ set(SOURCES add_library(Agent ${SOURCES}) target_include_directories(Agent PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src) -target_link_libraries(Agent PUBLIC ConfigurationParser Communicator AgentInfo CommandHandler MultiTypeQueue ModuleManager PRIVATE OpenSSL::SSL OpenSSL::Crypto Boost::asio Boost::beast Logger) +target_link_libraries(Agent PUBLIC ConfigurationParser Communicator AgentInfo CommandHandler MultiTypeQueue ModuleManager PRIVATE OpenSSL::SSL OpenSSL::Crypto Boost::asio Boost::beast) include(../cmake/ConfigureTarget.cmake) configure_target(Agent) diff --git a/src/agent/configuration_parser/src/configuration_parser.cpp b/src/agent/configuration_parser/src/configuration_parser.cpp index 87eeb9b4b1..bd8c8ffbdb 100644 --- a/src/agent/configuration_parser/src/configuration_parser.cpp +++ b/src/agent/configuration_parser/src/configuration_parser.cpp @@ -19,10 +19,25 @@ namespace configuration LogError("Using default values due to error parsing wazuh.conf file: {}", e.what()); tbl = toml::parse_str( - R"([agent] + R"( + [agent] server_mgmt_api_port = "55000" agent_comms_api_port = "8080" - manager_ip = "localhost")", + manager_ip = "localhost" + + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )", toml::spec::v(1, 0, 0)); } } diff --git a/src/agent/include/agent.hpp b/src/agent/include/agent.hpp index 6d7ae50ac0..91efb4fcad 100644 --- a/src/agent/include/agent.hpp +++ b/src/agent/include/agent.hpp @@ -5,10 +5,10 @@ #include #include #include +#include #include #include #include -#include #include diff --git a/src/agent/src/agent.cpp b/src/agent/src/agent.cpp index 8365ba71ce..ffd928a159 100644 --- a/src/agent/src/agent.cpp +++ b/src/agent/src/agent.cpp @@ -20,6 +20,7 @@ Agent::Agent(std::unique_ptr signalHandler) m_agentInfo.GetKey(), [this](std::string table, std::string key) -> std::string { return m_configurationParser.GetConfig(std::move(table), std::move(key)); }) + , m_moduleManager(m_messageQueue, m_configurationParser) { m_taskManager.Start(std::thread::hardware_concurrency()); } @@ -31,8 +32,6 @@ Agent::~Agent() void Agent::Run() { - Configuration config; - m_taskManager.EnqueueTask(m_communicator.WaitForTokenExpirationAndAuthenticate()); m_taskManager.EnqueueTask(m_communicator.GetCommandsFromManager( @@ -52,13 +51,12 @@ void Agent::Run() [this]() { return GetCommandFromQueue(m_messageQueue); }, [this]() { return PopCommandFromQueue(m_messageQueue); }, [](command_store::Command& cmd) { return DispatchCommand(cmd); })); - - m_moduleManager.setMessageQueue(m_messageQueue); - m_moduleManager.addModule(Inventory::instance()); - m_moduleManager.setup(config); - m_taskManager.EnqueueTask([this]() { m_moduleManager.start(); }); + + m_moduleManager.AddModule(Inventory::Instance()); + m_moduleManager.Setup(); + m_taskManager.EnqueueTask([this]() { m_moduleManager.Start(); }); m_signalHandler->WaitForSignal(); - m_moduleManager.stop(); + m_moduleManager.Stop(); m_communicator.Stop(); } diff --git a/src/agent/tests/agent_test.cpp b/src/agent/tests/agent_test.cpp index 0b1a3775be..2178277d60 100644 --- a/src/agent/tests/agent_test.cpp +++ b/src/agent/tests/agent_test.cpp @@ -23,9 +23,7 @@ TEST(AgentTests, AgentStopsWhenSignalReceived) EXPECT_CALL(*mockSignalHandlerPtr, WaitForSignal()) .Times(1) - .WillOnce([]() { - std::this_thread::sleep_for(std::chrono::seconds(1)); - }); + .WillOnce([]() { std::this_thread::sleep_for(std::chrono::seconds(1)); }); Agent agent(std::move(mockSignalHandler)); diff --git a/src/common/CMakeLists.txt b/src/common/CMakeLists.txt index a644b888e7..609032b1ac 100644 --- a/src/common/CMakeLists.txt +++ b/src/common/CMakeLists.txt @@ -1,23 +1,23 @@ -add_subdirectory(logger) -add_subdirectory(utils) -add_subdirectory(version_op) -add_subdirectory(time_op) -add_subdirectory(file_op) -add_subdirectory(privsep_op) -add_subdirectory(pthreads_op) -add_subdirectory(error_messages) -add_subdirectory(mem_op) add_subdirectory(binaries_op) -add_subdirectory(regex_op) -add_subdirectory(randombytes) add_subdirectory(bzip2_op) +add_subdirectory(data_provider) +add_subdirectory(dbsync) add_subdirectory(debug_op) +add_subdirectory(error_messages) +add_subdirectory(file_op) +add_subdirectory(hashHelper) +add_subdirectory(logger) add_subdirectory(logging_helper) +add_subdirectory(mem_op) add_subdirectory(networkHelper) -add_subdirectory(data_provider) -add_subdirectory(dbsync) +add_subdirectory(privsep_op) +add_subdirectory(pthreads_op) +add_subdirectory(randombytes) +add_subdirectory(regex_op) add_subdirectory(sqliteWrapper) -add_subdirectory(hashHelper) +add_subdirectory(time_op) +add_subdirectory(utils) +add_subdirectory(version_op) if(BUILD_TESTS) enable_testing() diff --git a/src/common/data_provider/CMakeLists.txt b/src/common/data_provider/CMakeLists.txt index c4907b3d0f..e8e2e9d2f9 100644 --- a/src/common/data_provider/CMakeLists.txt +++ b/src/common/data_provider/CMakeLists.txt @@ -94,7 +94,7 @@ include_directories(${SRC_FOLDER}/common/stringHelper/include/) include_directories(${SRC_FOLDER}/common/timeHelper/include/) include_directories(${SRC_FOLDER}/shared_modules/common/) include_directories(${SRC_FOLDER}/external/libdb/build_unix/) -if(LINUX) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") include_directories(${SRC_FOLDER}/external/rpm/include/) include_directories(${SRC_FOLDER}/external/rpm/builddir/output/include/) # Avoid download externals from http-request submodule @@ -104,14 +104,10 @@ if(LINUX) include_directories(${SRC_FOLDER}/common/http-request/shared/) endif() -if(CMAKE_SYSTEM_NAME STREQUAL "HP-UX") - link_directories(${INSTALL_PREFIX}/lib) -endif(CMAKE_SYSTEM_NAME STREQUAL "HP-UX") - link_directories(${SRC_FOLDER}) link_directories(${SRC_FOLDER}/external/procps/) link_directories(${SRC_FOLDER}/external/libdb/build_unix/) -if(LINUX) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") link_directories(${SRC_FOLDER}/external/rpm/builddir/) link_directories(${SRC_FOLDER}/common/http-request/build) endif() @@ -125,14 +121,6 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") add_definitions(-DWIN32=1 -D_WIN32_WINNT=0x600 -DWIN_EXPORT) -elseif(CMAKE_CHECK_CENTOS5) - file(GLOB SYSINFO_SRC - "${CMAKE_CURRENT_SOURCE_DIR}/src/*Linux.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/network/*Linux.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/osinfo/sysOsParsers.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/packages/packageLinuxParser.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/packages/packageLinuxParserRpmLegacy.cpp") - add_definitions(-DLINUX_TYPE=LinuxType::LEGACY) # Partial compilation in legacy systems elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") file(GLOB SYSINFO_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/*Linux.cpp" @@ -159,26 +147,6 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") "${CMAKE_CURRENT_SOURCE_DIR}/src/osinfo/sysOsParsers.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/src/hardware/*X86_64Mac.cpp") endif() -elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") - file(GLOB SYSINFO_SRC - "${CMAKE_CURRENT_SOURCE_DIR}/src/*FreeBSD.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/*CommonBSD.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/network/*BSD.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/osinfo/sysOsParsers.cpp") -elseif(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") - file(GLOB SYSINFO_SRC - "${CMAKE_CURRENT_SOURCE_DIR}/src/*OpenBSD.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/*CommonBSD.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/network/*BSD.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/osinfo/sysOsParsers.cpp") -elseif(CMAKE_SYSTEM_NAME STREQUAL "SunOS") - file(GLOB SYSINFO_SRC - "${CMAKE_CURRENT_SOURCE_DIR}/src/UtilsWrapperUnix.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/*Solaris.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/packages/*Solaris.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/network/networkSolarisHelper.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/network/*Solaris.cpp" - "${CMAKE_CURRENT_SOURCE_DIR}/src/osinfo/sysOsParsers.cpp") else() file(GLOB SYSINFO_SRC "${CMAKE_CURRENT_SOURCE_DIR}/src/*Unix.cpp" diff --git a/src/common/data_provider/src/network/networkFamilyDataAFactory.h b/src/common/data_provider/src/network/networkFamilyDataAFactory.h index 2635cca58d..0935d0585f 100644 --- a/src/common/data_provider/src/network/networkFamilyDataAFactory.h +++ b/src/common/data_provider/src/network/networkFamilyDataAFactory.h @@ -17,7 +17,6 @@ #include "networkInterfaceLinux.h" #include "networkInterfaceBSD.h" #include "networkInterfaceWindows.h" -#include "networkInterfaceSolaris.h" #include "sharedDefs.h" template @@ -63,14 +62,4 @@ class FactoryNetworkFamilyCreator final } }; -template <> -class FactoryNetworkFamilyCreator final -{ - public: - static std::shared_ptr create(const std::shared_ptr& interfaceWrapper) - { - return FactorySolarisNetwork::create(interfaceWrapper); - } -}; - #endif // _NETWORK_FAMILY_DATA_AFACTORY_H diff --git a/src/common/data_provider/src/network/networkInterfaceSolaris.cpp b/src/common/data_provider/src/network/networkInterfaceSolaris.cpp deleted file mode 100644 index 9f9daa157e..0000000000 --- a/src/common/data_provider/src/network/networkInterfaceSolaris.cpp +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * December 21, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#include "networkInterfaceSolaris.h" -#include "sys/socket.h" - - -std::shared_ptr FactorySolarisNetwork::create(const std::shared_ptr& interfaceWrapper) -{ - std::shared_ptr ret; - - if (interfaceWrapper) - { - const auto family { interfaceWrapper->family() }; - - if (AF_INET == family) - { - ret = std::make_shared>(interfaceWrapper); - } - else if (AF_INET6 == family) - { - ret = std::make_shared>(interfaceWrapper); - } - else if (AF_UNSPEC == family) - { - ret = std::make_shared>(interfaceWrapper); - } - - // else: unknown family - } - else - { - throw std::runtime_error { "Error nullptr interfaceWrapper instance." }; - } - - return ret; -} - -template <> -void SolarisNetworkImpl::buildNetworkData(nlohmann::json& network) -{ - const auto address { m_interfaceAddress->address() }; - - if (!address.empty()) - { - nlohmann::json ipv4JS { }; - ipv4JS["address"] = address; - ipv4JS["netmask"] = m_interfaceAddress->netmask(); - ipv4JS["broadcast"] = m_interfaceAddress->broadcast(); - ipv4JS["metric"] = m_interfaceAddress->metrics(); - ipv4JS["dhcp"] = m_interfaceAddress->dhcp(); - - network["IPv4"].push_back(ipv4JS); - } - else - { - throw std::runtime_error { "Invalid IpV4 address." }; - } -} -template <> -void SolarisNetworkImpl::buildNetworkData(nlohmann::json& network) -{ - const auto address { m_interfaceAddress->addressV6() }; - - if (!address.empty()) - { - nlohmann::json ipv6JS {}; - ipv6JS["address"] = address; - ipv6JS["netmask"] = m_interfaceAddress->netmaskV6(); - ipv6JS["broadcast"] = m_interfaceAddress->broadcastV6(); - ipv6JS["metric"] = m_interfaceAddress->metricsV6(); - ipv6JS["dhcp"] = m_interfaceAddress->dhcp(); - - network["IPv6"].push_back(ipv6JS); - } - else - { - throw std::runtime_error { "Invalid IpV6 address." }; - } -} - -template <> -void SolarisNetworkImpl::buildNetworkData(nlohmann::json& network) -{ - // Extraction of common adapter data - network["name"] = m_interfaceAddress->name(); - network["adapter"] = m_interfaceAddress->adapter(); - network["state"] = m_interfaceAddress->state(); - network["type"] = m_interfaceAddress->type(); - network["mac"] = m_interfaceAddress->MAC(); - - const auto stats { m_interfaceAddress->stats() }; - network["tx_packets"] = stats.txPackets; - network["rx_packets"] = stats.rxPackets; - network["tx_bytes"] = stats.txBytes; - network["rx_bytes"] = stats.rxBytes; - network["tx_errors"] = stats.txErrors; - network["rx_errors"] = stats.rxErrors; - network["tx_dropped"] = stats.txDropped; - network["rx_dropped"] = stats.rxDropped; - - network["mtu"] = m_interfaceAddress->mtu(); - network["gateway"] = m_interfaceAddress->gateway(); -} diff --git a/src/common/data_provider/src/network/networkInterfaceSolaris.h b/src/common/data_provider/src/network/networkInterfaceSolaris.h deleted file mode 100644 index c83a00755b..0000000000 --- a/src/common/data_provider/src/network/networkInterfaceSolaris.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * December 21, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#ifndef _NETWORK_INTERFACE_SOLARIS_H -#define _NETWORK_INTERFACE_SOLARIS_H -#include - -#include "inetworkInterface.h" -#include "inetworkWrapper.h" - -class FactorySolarisNetwork -{ - public: - static std::shared_ptrcreate(const std::shared_ptr& interfaceWrapper); -}; - -template -class SolarisNetworkImpl final : public IOSNetwork -{ - std::shared_ptr m_interfaceAddress; - public: - explicit SolarisNetworkImpl(const std::shared_ptr& interfaceAddress) - : m_interfaceAddress(interfaceAddress) - { } - // LCOV_EXCL_START - ~SolarisNetworkImpl() = default; - // LCOV_EXCL_STOP - void buildNetworkData(nlohmann::json& /*network*/) override - { - throw std::runtime_error { "Specialization not implemented" }; - } -}; - -#endif // _NETWORK_INTERFACE_SOLARIS_H diff --git a/src/common/data_provider/src/network/networkSolarisHelper.cpp b/src/common/data_provider/src/network/networkSolarisHelper.cpp deleted file mode 100644 index 1d552d6576..0000000000 --- a/src/common/data_provider/src/network/networkSolarisHelper.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * December 16, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#include -#include "networkSolarisHelper.hpp" -#include "UtilsWrapperUnix.hpp" -#include - -int NetworkSolarisHelper::getInterfacesCount(int fd, sa_family_t family) -{ - auto interfaceCount { 0 }; - - struct lifnum ifn = { .lifn_family = family, .lifn_flags = 0, .lifn_count = 0 }; - - UtilsWrapperUnix::ioctl(fd, SIOCGLIFNUM, reinterpret_cast(&ifn)); - interfaceCount = ifn.lifn_count; - return interfaceCount; -} - -void NetworkSolarisHelper::getInterfacesConfig(int fd, lifconf& networkInterfacesConf) -{ - UtilsWrapperUnix::ioctl(fd, SIOCGLIFCONF, reinterpret_cast(&networkInterfacesConf)); -} diff --git a/src/common/data_provider/src/network/networkSolarisHelper.hpp b/src/common/data_provider/src/network/networkSolarisHelper.hpp deleted file mode 100644 index d39d6e7ff8..0000000000 --- a/src/common/data_provider/src/network/networkSolarisHelper.hpp +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * December 16, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#ifndef _NETWORK_SOLARIS_HELPER_H -#define _NETWORK_SOLARIS_HELPER_H - -#include - -class NetworkSolarisHelper final -{ - public: - static int getInterfacesCount(int fd, sa_family_t family); - static void getInterfacesConfig(int fd, lifconf& networkInterface); -}; - -#endif //_NETWORK_SOLARIS_HELPER_H diff --git a/src/common/data_provider/src/network/networkSolarisWrapper.hpp b/src/common/data_provider/src/network/networkSolarisWrapper.hpp deleted file mode 100644 index 106af37adf..0000000000 --- a/src/common/data_provider/src/network/networkSolarisWrapper.hpp +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * December 25, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#ifndef _NETWORK_SOLARIS_WRAPPER_H -#define _NETWORK_SOLARIS_WRAPPER_H - -#include -#include -#include -#include -#include -#include - -#include "inetworkWrapper.h" -#include "UtilsWrapperUnix.hpp" -#include "sharedDefs.h" -#include "networkHelper.h" -#include "cmdHelper.h" -#include "stringHelper.h" - -enum ROUTING_FIELDS -{ - ROUTING_DESTINATION, - ROUTING_GATEWAY, - ROUTING_FLAGS, - ROUTING_REF, - ROUTING_USE, - ROUTING_IFACE_NAME, - ROUTING_SIZE_FIELDS -}; - -enum MAC_FIELDS -{ - MAC_FIELD_NAME, - MAC_ADDRESS, - MAC_SIZE_FIELDS -}; - -class NetworkSolarisInterface final : public INetworkInterfaceWrapper -{ - lifreq* m_networkInterface; - const int m_fileDescriptor; - const sa_family_t m_family; - const uint64_t m_interfaceFlags; - - public: - explicit NetworkSolarisInterface(const sa_family_t family, int fd, std::pair interface) - : m_networkInterface {interface.first} - , m_fileDescriptor {fd} - , m_family {family} - , m_interfaceFlags {interface.second} - { - } - - std::string name() const override - { - return m_networkInterface->lifr_name ? m_networkInterface->lifr_name : ""; - } - - std::string adapter() const override - { - return ""; - } - - int family() const override - { - return m_family; - } - - std::string address() const override - { - std::string address; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFADDR, reinterpret_cast(m_networkInterface)); - struct sockaddr_in* data = reinterpret_cast(&m_networkInterface->lifr_addr); - address = Utils::NetworkHelper::IAddressToBinary(this->family(), &data->sin_addr); - } - catch (...) - { - } - - return address; - } - - std::string netmask() const override - { - std::string address; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFNETMASK, reinterpret_cast(m_networkInterface)); - struct sockaddr_in* data = reinterpret_cast(&m_networkInterface->lifr_addr); - address = Utils::NetworkHelper::IAddressToBinary(this->family(), &data->sin_addr); - } - catch (...) - { - } - - return address; - } - - std::string broadcast() const override - { - std::string retVal { UNKNOWN_VALUE }; - - if (m_interfaceFlags & IFF_BROADCAST) - { - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFBRDADDR, reinterpret_cast(m_networkInterface)); - struct sockaddr_in* data = reinterpret_cast(&m_networkInterface->lifr_broadaddr); - retVal = Utils::NetworkHelper::IAddressToBinary(this->family(), &data->sin_addr); - } - catch (...) - { - } - } - - return retVal; - } - - std::string addressV6() const override - { - std::string address; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFADDR, reinterpret_cast(m_networkInterface)); - struct sockaddr_in6* data = reinterpret_cast(&m_networkInterface->lifr_addr); - address = Utils::NetworkHelper::IAddressToBinary(this->family(), &data->sin6_addr); - } - catch (...) - { - } - - return address; - } - - std::string netmaskV6() const override - { - std::string address; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFNETMASK, reinterpret_cast(m_networkInterface)); - struct sockaddr_in6* data = reinterpret_cast(&m_networkInterface->lifr_addr); - address = Utils::NetworkHelper::IAddressToBinary(this->family(), &data->sin6_addr); - } - catch (...) - { - } - - return address; - } - - std::string broadcastV6() const override - { - std::string retVal; - - if (m_interfaceFlags & IFF_BROADCAST) - { - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFBRDADDR, reinterpret_cast(m_networkInterface)); - struct sockaddr_in6* data = reinterpret_cast(&m_networkInterface->lifr_addr); - retVal = Utils::NetworkHelper::IAddressToBinary(this->family(), &data->sin6_addr); - } - catch (...) - { - } - } - - return retVal; - } - - std::string gateway() const override - { - std::string retVal; - const auto buffer { Utils::exec("netstat -rn") }; - - if (!buffer.empty()) - { - const auto lines { Utils::split(buffer, '\n') }; - - for (auto line : lines) - { - Utils::replaceAll(line, " ", " "); - const auto fields { Utils::split(line, ' ') }; - - if (fields.size() == ROUTING_SIZE_FIELDS && fields.front().compare("default") == 0) - { - if (fields[ROUTING_IFACE_NAME].compare(this->name()) == 0) - { - retVal = fields[ROUTING_GATEWAY]; - } - - break; - } - } - } - - return retVal; - } - - std::string metrics() const override - { - std::string metric; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFMETRIC, reinterpret_cast(m_networkInterface)); - metric = std::to_string(m_networkInterface->lifr_metric); - } - catch (...) - { - } - - return metric; - } - - std::string metricsV6() const override - { - std::string metric; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFMETRIC, reinterpret_cast(m_networkInterface)); - metric = std::to_string(m_networkInterface->lifr_metric); - } - catch (const std::exception& e) - { - std::cerr << e.what() << '\n'; - } - - return metric; - } - - std::string dhcp() const override - { - return m_interfaceFlags & IFF_DHCPRUNNING ? "enabled" : "disabled"; - } - - uint32_t mtu() const override - { - uint32_t retVal { 0 }; - - try - { - UtilsWrapperUnix::ioctl(m_fileDescriptor, SIOCGLIFMTU, reinterpret_cast(m_networkInterface)); - retVal = m_networkInterface->lifr_mtu; - } - catch (...) - { - } - - return retVal; - } - - LinkStats stats() const override - { - auto buffer { Utils::exec("kstat -n " + this->name() + " -c net", 256) }; - LinkStats statistic { 0, 0, 0, 0, 0, 0, 0, 0 }; - - if (!buffer.empty()) - { - constexpr auto RX_PACKET_INDEX { "ipackets64" }; - constexpr auto RX_BYTES_INDEX { "rbytes64" }; - constexpr auto TX_PACKET_INDEX { "opackets64" }; - constexpr auto TX_BYTES_INDEX { "obytes64" }; - constexpr auto RX_DROPS_INDEX { "dl_idrops" }; - constexpr auto TX_DROPS_INDEX { "dl_odrops" }; - constexpr auto RX_ERRORS_INDEX { "ierrors" }; - constexpr auto TX_ERRORS_INDEX { "oerrors" }; - - std::map data; - auto value { 0 }; - size_t valueSize { 0 }; - auto lines { Utils::split(buffer, '\n') }; - - lines.erase(lines.begin()); - lines.erase(lines.begin()); - lines.erase(lines.end()); - - try - { - for (auto& line : lines) - { - Utils::replaceAll(line, "\t", " "); - Utils::replaceAll(line, " ", " "); - auto fields { Utils::split(line, ' ') }; - - value = std::stoi(fields.back(), &valueSize); - - if (fields.back().size() == valueSize) - { - data[fields.at(1)] = value; - } - else - { - data[fields.at(1)] = 0; - } - } - } - catch (...) - { - } - - auto it {data.find(RX_PACKET_INDEX)}; - - statistic.rxPackets = static_cast( it != data.end() ? data.at(RX_PACKET_INDEX) : 0); - it = data.find(RX_BYTES_INDEX); - statistic.rxBytes = static_cast( it != data.end() ? data.at(RX_BYTES_INDEX) : 0); - it = data.find(TX_PACKET_INDEX); - statistic.txPackets = static_cast( it != data.end() ? data.at(TX_PACKET_INDEX) : 0); - it = data.find(TX_BYTES_INDEX); - statistic.txBytes = static_cast( it != data.end() ? data.at(TX_BYTES_INDEX) : 0); - it = data.find(RX_DROPS_INDEX); - statistic.rxDropped = static_cast( it != data.end() ? data.at(RX_DROPS_INDEX) : 0); - it = data.find(TX_DROPS_INDEX); - statistic.txDropped = static_cast( it != data.end() ? data.at(TX_DROPS_INDEX) : 0); - it = data.find(RX_ERRORS_INDEX); - statistic.rxErrors = static_cast( it != data.end() ? data.at(RX_ERRORS_INDEX) : 0); - it = data.find(TX_ERRORS_INDEX); - statistic.txErrors = static_cast( it != data.end() ? data.at(TX_ERRORS_INDEX) : 0); - } - - return statistic; - } - - std::string type() const override - { - const auto buffer { Utils::exec("dladm show-phys " + this->name(), 512) }; - constexpr auto COLUMN_TYPE_INTERFACE { "MEDIA" }; - std::string type; - - if (!buffer.empty() && (buffer.find("unknown subcommand") == std::string::npos)) - { - auto lines { Utils::split(buffer, '\n') }; - std::vector headers; - std::vector values; - - for (auto line : lines) - { - Utils::replaceAll(line, "\t", ""); - Utils::replaceAll(line, " ", " "); - - if (headers.size() == 0) - { - headers = Utils::split(line, ' '); - } - else - { - values = Utils::split(line, ' '); - } - } - - try - { - const auto it = std::find(headers.begin(), headers.end(), COLUMN_TYPE_INTERFACE); - - if (it != headers.end() && values.size() > static_cast(it - headers.begin())) - { - type = values.at(it - headers.begin()); - } - } - catch (...) - { - } - } - - return type; - } - - std::string state() const override - { - return m_interfaceFlags & IFF_UP ? "up" : "down"; - } - - std::string MAC() const override - { - std::string mac { UNKNOWN_VALUE }; - const auto buffer { Utils::exec("ifconfig " + this->name()) }; - - if (!buffer.empty()) - { - const auto lines { Utils::split(buffer, '\n') }; - - for (auto line : lines) - { - Utils::replaceAll(line, "\t", ""); - const auto fields { Utils::split(line, ' ') }; - - if (fields.size() == MAC_SIZE_FIELDS && fields.front().compare("ether") == 0) - { - auto components { Utils::split(fields[MAC_ADDRESS], ':') }; - std::stringstream value { }; - - value << std::hex << std::setfill('0'); - - for (auto& item : components) - { - std::transform(item.begin(), item.end(), item.begin(), ::toupper); - value << std::setw(2) << item; - - if (&item != &components.back()) - { - value << ":"; - } - } - - mac = value.str(); - break; - } - } - } - - return mac; - } -}; - -#endif // _NETWORK_SOLARIS_WRAPPER_H diff --git a/src/common/data_provider/src/osinfo/sysOsParsers.cpp b/src/common/data_provider/src/osinfo/sysOsParsers.cpp index 956a2a0d75..2c419d5576 100644 --- a/src/common/data_provider/src/osinfo/sysOsParsers.cpp +++ b/src/common/data_provider/src/osinfo/sysOsParsers.cpp @@ -254,14 +254,6 @@ bool DebianOsParser::parseFile(std::istream& in, nlohmann::json& output) return findVersionInStream(in, output, PATTERN_MATCH); } -bool ArchOsParser::parseFile(std::istream& in, nlohmann::json& output) -{ - constexpr auto PATTERN_MATCH{R"([0-9].*\.[0-9]*)"}; - output["os_name"] = "Arch Linux"; - output["os_platform"] = "arch"; - return findVersionInStream(in, output, PATTERN_MATCH); -} - bool SlackwareOsParser::parseFile(std::istream& in, nlohmann::json& output) { constexpr auto PATTERN_MATCH{R"([0-9].*\.[0-9]*)"}; @@ -313,63 +305,6 @@ bool FedoraOsParser::parseFile(std::istream& in, nlohmann::json& output) return ret; } -bool SolarisOsParser::parseFile(std::istream& in, nlohmann::json& output) -{ - const std::string HEADER_STRING{"Solaris "}; - output["os_name"] = "SunOS"; - output["os_platform"] = "sunos"; - std::string line; - size_t pos{std::string::npos}; - - while (pos == std::string::npos && std::getline(in, line)) - { - line = Utils::trim(line); - pos = line.find(HEADER_STRING); - - if (std::string::npos != pos) - { - line = line.substr(pos + HEADER_STRING.size()); - pos = line.find(" "); - - if (pos != std::string::npos) - { - line = line.substr(0, pos); - } - - output["os_version"] = Utils::trim(line); - findMajorMinorVersionInString(Utils::trim(line), output); - } - } - - return std::string::npos == pos ? false : true; -} - -bool HpUxOsParser::parseUname(const std::string& in, nlohmann::json& output) -{ - constexpr auto PATTERN_MATCH{R"(B\.([0-9].*\.[0-9]*))"}; - std::string match; - std::regex pattern{PATTERN_MATCH}; - const auto ret {Utils::findRegexInString(in, match, pattern, 1)}; - - if (ret) - { - output["os_version"] = match; - findMajorMinorVersionInString(match, output); - } - - output["os_name"] = "HP-UX"; - output["os_platform"] = "hp-ux"; - return ret; -} - -bool AlpineOsParser::parseFile(std::istream& in, nlohmann::json& output) -{ - constexpr auto PATTERN_MATCH{R"((?:[0-9]+\.)?(?:[0-9]+\.)?(?:[0-9]+))"}; - output["os_name"] = "Alpine Linux"; - output["os_platform"] = "alpine"; - return findVersionInStream(in, output, PATTERN_MATCH); -} - bool MacOsParser::parseSwVersion(const std::string& in, nlohmann::json& output) { constexpr auto SEPARATOR{':'}; diff --git a/src/common/data_provider/src/osinfo/sysOsParsers.h b/src/common/data_provider/src/osinfo/sysOsParsers.h index fbe11b78f3..99b674cae1 100644 --- a/src/common/data_provider/src/osinfo/sysOsParsers.h +++ b/src/common/data_provider/src/osinfo/sysOsParsers.h @@ -78,14 +78,6 @@ class DebianOsParser : public ISysOsParser bool parseFile(std::istream& in, nlohmann::json& output) override; }; -class ArchOsParser : public ISysOsParser -{ - public: - ArchOsParser() = default; - ~ArchOsParser() = default; - bool parseFile(std::istream& in, nlohmann::json& output) override; -}; - class SlackwareOsParser : public ISysOsParser { public: @@ -118,30 +110,6 @@ class FedoraOsParser : public ISysOsParser bool parseFile(std::istream& in, nlohmann::json& output) override; }; -class SolarisOsParser : public ISysOsParser -{ - public: - SolarisOsParser() = default; - ~SolarisOsParser() = default; - bool parseFile(std::istream& in, nlohmann::json& output) override; -}; - -class HpUxOsParser : public ISysOsParser -{ - public: - HpUxOsParser() = default; - ~HpUxOsParser() = default; - bool parseUname(const std::string& in, nlohmann::json& output) override; -}; - -class AlpineOsParser : public ISysOsParser -{ - public: - AlpineOsParser() = default; - ~AlpineOsParser() = default; - bool parseFile(std::istream& in, nlohmann::json& output) override; -}; - class MacOsParser { public: @@ -182,11 +150,6 @@ class FactorySysOsParser final return std::make_unique(); } - if (platform == "solaris") - { - return std::make_unique(); - } - if (platform == "debian") { return std::make_unique(); @@ -207,26 +170,11 @@ class FactorySysOsParser final return std::make_unique(); } - if (platform == "arch") - { - return std::make_unique(); - } - if (platform == "rhel") { return std::make_unique(); } - if (platform == "hp-ux") - { - return std::make_unique(); - } - - if (platform == "alpine") - { - return std::make_unique(); - } - throw std::runtime_error { "Unsupported platform." diff --git a/src/common/data_provider/src/packages/packageFamilyDataAFactory.h b/src/common/data_provider/src/packages/packageFamilyDataAFactory.h index 400b1134c1..a4560f2457 100644 --- a/src/common/data_provider/src/packages/packageFamilyDataAFactory.h +++ b/src/common/data_provider/src/packages/packageFamilyDataAFactory.h @@ -15,7 +15,6 @@ #include #include #include "packageMac.h" -#include "packageSolaris.h" #include "sharedDefs.h" template @@ -53,14 +52,4 @@ class FactoryPackageFamilyCreator final } }; -template <> -class FactoryPackageFamilyCreator final -{ - public: - static std::shared_ptr create(const std::shared_ptr& packageWrapper) - { - return FactorySolarisPackage::create(packageWrapper); - } -}; - #endif // _PACKAGE_FAMILY_DATA_AFACTORY_H diff --git a/src/common/data_provider/src/packages/packageLinuxApkParserHelper.h b/src/common/data_provider/src/packages/packageLinuxApkParserHelper.h deleted file mode 100644 index b8b3d514c1..0000000000 --- a/src/common/data_provider/src/packages/packageLinuxApkParserHelper.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015-2021, Wazuh Inc. - * January 03, 2023. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#ifndef _PACKAGE_LINUX_APK_PARSER_HELPER_H -#define _PACKAGE_LINUX_APK_PARSER_HELPER_H - -#include -#include "sharedDefs.h" -#include - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-function" - -namespace PackageLinuxHelper -{ - static const std::map> s_mapAlpineFields = - { - {'P', {typeid(std::string), "name"}}, - {'V', {typeid(std::string), "version"}}, - {'A', {typeid(std::string), "architecture"}}, - {'I', {typeid(int32_t), "size"}}, - {'T', {typeid(std::string), "description"}}, - }; - - static nlohmann::json parseApk(const std::vector>& entries) - { - nlohmann::json packageInfo; - - packageInfo["architecture"] = UNKNOWN_VALUE; - packageInfo["size"] = 0; - packageInfo["format"] = "apk"; - packageInfo["vendor"] = "Alpine Linux"; - packageInfo["install_time"] = UNKNOWN_VALUE; - packageInfo["location"] = UNKNOWN_VALUE; - packageInfo["groups"] = UNKNOWN_VALUE; - packageInfo["priority"] = UNKNOWN_VALUE; - packageInfo["source"] = UNKNOWN_VALUE; - // The multiarch field won't have a default value - - // Lambda to check if a string is empty and assign default value. - const auto loadData = [&packageInfo](const std::pair& key, - const std::string & value) - { - if (!value.empty()) - { - if (key.first == typeid(std::string)) - { - packageInfo[key.second] = value; - } - else if (key.first == typeid(int32_t)) - { - try - { - packageInfo[key.second] = std::stol(value); - } - catch (const std::exception&) - { - packageInfo[key.second] = 0; - } - } - } - }; - - for (const auto& item : entries) - { - loadData(s_mapAlpineFields.at(item.first), item.second); - } - - if (!packageInfo.contains("name") || - !packageInfo.contains("version")) - { - packageInfo.clear(); - } - - return packageInfo; - } -} - -#pragma GCC diagnostic pop - -#endif // _PACKAGE_LINUX_APK_PARSER_HELPER_H diff --git a/src/common/data_provider/src/packages/packageLinuxDataRetriever.h b/src/common/data_provider/src/packages/packageLinuxDataRetriever.h index ad74275882..8c7a371482 100644 --- a/src/common/data_provider/src/packages/packageLinuxDataRetriever.h +++ b/src/common/data_provider/src/packages/packageLinuxDataRetriever.h @@ -37,14 +37,6 @@ void getRpmInfoLegacy(std::function callback); */ void getDpkgInfo(const std::string& libPath, std::function callback); -/** - * @brief Fills a JSON object with all available apk-related information - * @param libPath Path to apk's database directory - * @param callback Callback to be called for every single element being found - */ -void getApkInfo(const std::string& libPath, std::function callback); - - /** * @brief Fills a JSON object with all available snap-related information * @param callback Callback to be called for every single element being found @@ -82,11 +74,6 @@ class FactoryPackagesCreator final getRpmInfo(callback); } - if (Utils::existsDir(APK_PATH)) - { - getApkInfo(APK_DB_PATH, callback); - } - if (Utils::existsDir(SNAP_PATH)) { getSnapInfo(callback); diff --git a/src/common/data_provider/src/packages/packageLinuxParserApk.cpp b/src/common/data_provider/src/packages/packageLinuxParserApk.cpp deleted file mode 100644 index 5a581d62e5..0000000000 --- a/src/common/data_provider/src/packages/packageLinuxParserApk.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * December 19, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#include -#include -#include "packageLinuxApkParserHelper.h" - -void getApkInfo(const std::string& fileName, std::function callback) -{ - std::ifstream apkDb(fileName); - std::string line {}; - std::vector> data; - - // https://wiki.alpinelinux.org/wiki/Apk_spec#APKINDEX_Format - std::array keys{'P', 'V', 'A', 'I', 'T'}; - const auto separator = ':'; - - if (apkDb.is_open()) - { - while (getline(apkDb, line)) - { - if (!line.empty()) - { - if (std::find(std::cbegin(keys), std::cend(keys), line.front()) != std::cend(keys)) - { - data.emplace_back(line.front(), line.substr(line.find_first_of(separator) + 1)); - } - } - else - { - auto packageInfo = PackageLinuxHelper::parseApk(data); - data.clear(); - - if (!packageInfo.empty()) - { - callback(packageInfo); - } - } - } - } -} diff --git a/src/common/data_provider/src/packages/packageSolaris.cpp b/src/common/data_provider/src/packages/packageSolaris.cpp deleted file mode 100644 index f815fb5f8d..0000000000 --- a/src/common/data_provider/src/packages/packageSolaris.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * January 11, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#include "packageSolaris.h" - -std::shared_ptr FactorySolarisPackage::create(const std::shared_ptr& pkgWrapper) -{ - return std::make_shared(pkgWrapper); -} - -SolarisPackageImpl::SolarisPackageImpl(const std::shared_ptr& packageWrapper) - : m_packageWrapper(packageWrapper) -{ } - -void SolarisPackageImpl::buildPackageData(nlohmann::json& package) -{ - package["name"] = m_packageWrapper->name(); - package["version"] = m_packageWrapper->version(); - package["groups"] = m_packageWrapper->groups(); - package["description"] = m_packageWrapper->description(); - package["architecture"] = m_packageWrapper->architecture(); - package["format"] = m_packageWrapper->format(); - package["source"] = m_packageWrapper->source(); - package["location"] = m_packageWrapper->location(); - package["priority"] = m_packageWrapper->priority(); - package["size"] = m_packageWrapper->size(); - package["vendor"] = m_packageWrapper->vendor(); - package["install_time"] = m_packageWrapper->install_time(); - // The multiarch field won't have a default value -} diff --git a/src/common/data_provider/src/packages/packageSolaris.h b/src/common/data_provider/src/packages/packageSolaris.h deleted file mode 100644 index 0104f36739..0000000000 --- a/src/common/data_provider/src/packages/packageSolaris.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * January 11, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - - -#ifndef _PACKAGE_SOLARIS_H -#define _PACKAGE_SOLARIS_H - -#include "ipackageInterface.h" -#include "ipackageWrapper.h" - -class FactorySolarisPackage -{ - public: - static std::shared_ptrcreate(const std::shared_ptr& pkgWrapper); -}; - -class SolarisPackageImpl final : public IPackage -{ - const std::shared_ptr m_packageWrapper; - - public: - explicit SolarisPackageImpl(const std::shared_ptr& packageWrapper); - - // LCOV_EXCL_START - ~SolarisPackageImpl() = default; - // LCOV_EXCL_STOP - - void buildPackageData(nlohmann::json& packge) override; -}; - -#endif // _PACKAGE_SOLARIS_H diff --git a/src/common/data_provider/src/packages/solarisWrapper.h b/src/common/data_provider/src/packages/solarisWrapper.h deleted file mode 100644 index 7dde0958a2..0000000000 --- a/src/common/data_provider/src/packages/solarisWrapper.h +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Wazuh SYSINFO - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#ifndef _SOLARIS_WRAPPER_H -#define _SOLARIS_WRAPPER_H - -#include -#include -#include - -#include "ipackageWrapper.h" -#include "sharedDefs.h" -#include "stringHelper.h" - -constexpr auto NAME_FILE_INFO { "pkginfo" }; -constexpr auto NAME_FIELD { "PKG" }; -constexpr auto ARCH_FIELD { "ARCH" }; -constexpr auto VERSION_FIELD { "VERSION" }; -constexpr auto GROUPS_FIELD { "CATEGORY" }; -constexpr auto DESC_FIELD { "NAME" }; -constexpr auto LOCATION_FIELD { "SUNW_PKG_DIR" }; -constexpr auto VENDOR_FIELD { "VENDOR" }; -constexpr auto INSTALL_TIME_FIELD { "INSTDATE" }; - -// Date format is Oct 06 2015 08:51 -enum DateFormat -{ - MONTH_INDEX, - DAY_INDEX, - YEAR_INDEX, - TIME_INDEX, - DATE_FORMAT_SIZE -}; - -// VERSION=1.2.3,REVISION=1234 -enum VersionFields -{ - VERSION_VALUE_INDEX, - REVISION_KEY_VALUE_INDEX -}; - -static const std::map MONTH = -{ - {"Jan", "01"}, - {"Feb", "02"}, - {"Mar", "03"}, - {"Apr", "04"}, - {"May", "05"}, - {"Jun", "06"}, - {"Jul", "07"}, - {"Aug", "08"}, - {"Sep", "09"}, - {"Oct", "10"}, - {"Nov", "11"}, - {"Dec", "12"} -}; - -class SolarisWrapper final : public IPackageWrapper -{ - public: - SolarisWrapper(const std::string& pkgDirectory) - : m_format{"pkg"} - { - getPkgData(pkgDirectory); - } - - ~SolarisWrapper() = default; - - - std::string name() const override - { - std::string name; - auto it {m_data.find(NAME_FIELD)}; - - if (it != m_data.end()) - { - constexpr auto VENDOR_NAME_PKG_PATTERN { "^[A-Z+-]{1,4}" }; - std::regex namePkgRegex { VENDOR_NAME_PKG_PATTERN }; - std::smatch match; - name = it->second; - - if (std::regex_search(name, match, namePkgRegex)) - { - name = match.suffix(); - } - } - - return name; - } - - std::string version() const override - { - std::string version; - auto it {m_data.find(VERSION_FIELD)}; - - if (it != m_data.end()) - { - version = it->second; - const auto fields { Utils::split(version, ',') }; - - if (fields.size() > 1) - { - version = fields.at(VERSION_VALUE_INDEX); - } - } - - return version; - } - - std::string groups() const override - { - auto it {m_data.find(GROUPS_FIELD)}; - - return it != m_data.end() ? it->second : UNKNOWN_VALUE; - } - - std::string description() const override - { - auto it {m_data.find(DESC_FIELD)}; - - return it != m_data.end() ? it->second : UNKNOWN_VALUE; - } - - std::string architecture() const override - { - auto it {m_data.find(ARCH_FIELD)}; - - return it != m_data.end() ? it->second : UNKNOWN_VALUE; - } - - std::string format() const override - { - return m_format; - } - - std::string osPatch() const override - { - return UNKNOWN_VALUE; - } - - std::string source() const override - { - return UNKNOWN_VALUE; - } - - std::string location() const override - { - std::string retVal {UNKNOWN_VALUE}; - auto it {m_data.find(LOCATION_FIELD)}; - - if (it != m_data.end() && !it->second.empty()) - { - retVal = it->second; - } - - return retVal; - } - - std::string priority() const override - { - return UNKNOWN_VALUE; - } - - int size() const override - { - return 0; - } - - std::string vendor() const override - { - auto it {m_data.find(VENDOR_FIELD)}; - - return it != m_data.end() ? it->second : UNKNOWN_VALUE; - } - - std::string install_time() const override - { - std::stringstream installTime; - auto it { m_data.find(INSTALL_TIME_FIELD) }; - - if (it != m_data.end()) - { - const auto fields { Utils::split(it->second, ' ') }; - - try - { - installTime << std::setw(4) << std::setfill('0') << fields.at(YEAR_INDEX); - installTime << '/' << std::setw(2) << std::setfill('0') << MONTH.at(fields.at(MONTH_INDEX)); - installTime << '/' << std::setw(2) << std::setfill('0') << fields.at(DAY_INDEX); - installTime << ' ' << fields.at(TIME_INDEX) << ":00"; - } - catch (...) - { - } - } - - return installTime.str(); - } - - std::string multiarch() const override - { - return std::string(); - } - - private: - std::string m_format; - std::map m_data; - - void getPkgData(const std::string& pkgDirectory) - { - std::fstream file { pkgDirectory + "/" + NAME_FILE_INFO, std::ios_base::in }; - constexpr auto KEY { 0 }; - constexpr auto VALUE { 1 }; - - if (file.is_open()) - { - std::string line; - - while (file.good()) - { - std::getline(file, line); - // Convert 'line' to UTF-8 - Utils::ISO8859ToUTF8(line); - const auto fields { Utils::split(line, '=') }; - - if (fields.size() > 1) - { - m_data[fields.at(KEY)] = fields.at(VALUE); - } - - } - } - } -}; - -#endif // _SOLARIS_WRAPPER_H diff --git a/src/common/data_provider/src/sharedDefs.h b/src/common/data_provider/src/sharedDefs.h index 63dfb5b547..21ae886427 100644 --- a/src/common/data_provider/src/sharedDefs.h +++ b/src/common/data_provider/src/sharedDefs.h @@ -31,8 +31,6 @@ constexpr auto DPKG_STATUS_PATH {"/var/lib/dpkg/status"}; constexpr auto RPM_PATH {"/var/lib/rpm/"}; -constexpr auto APK_PATH {"/lib/apk/db"}; -constexpr auto APK_DB_PATH {"/lib/apk/db/installed"}; constexpr auto SNAP_PATH {"/var/lib/snapd"}; constexpr auto UNKNOWN_VALUE {" "}; @@ -48,7 +46,6 @@ enum OSPlatformType LINUX, BSDBASED, WINDOWS, - SOLARIS }; enum LinuxType diff --git a/src/common/data_provider/src/sysInfoFreeBSD.cpp b/src/common/data_provider/src/sysInfoFreeBSD.cpp deleted file mode 100644 index 0d3a80bad0..0000000000 --- a/src/common/data_provider/src/sysInfoFreeBSD.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * October 7, 2020. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ -#include "sysInfo.hpp" -#include "cmdHelper.h" -#include "stringHelper.h" -#include "osinfo/sysOsParsers.h" -#include -#include -#include -#include "sharedDefs.h" - -static void getMemory(nlohmann::json& info) -{ - constexpr auto vmPageSize{"vm.stats.vm.v_page_size"}; - constexpr auto vmTotal{"vm.vmtotal"}; - uint64_t ram{0}; - const std::vector mib{CTL_HW, HW_PHYSMEM}; - size_t len{sizeof(ram)}; - auto ret{sysctl(const_cast(mib.data()), mib.size(), &ram, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading total RAM." - }; - } - - const auto ramTotal{ram / KByte}; - info["ram_total"] = ramTotal; - u_int pageSize{0}; - len = sizeof(pageSize); - ret = sysctlbyname(vmPageSize, &pageSize, &len, nullptr, 0); - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading page size." - }; - } - - struct vmtotal vmt {}; - - len = sizeof(vmt); - - ret = sysctlbyname(vmTotal, &vmt, &len, nullptr, 0); - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading total memory." - }; - } - - const auto ramFree{(vmt.t_free * pageSize) / KByte}; - info["ram_free"] = ramFree; - info["ram_usage"] = 100 - (100 * ramFree / ramTotal); -} - - -static int getCpuMHz() -{ - unsigned long cpuMHz{0}; - constexpr auto clockRate{"hw.clockrate"}; - size_t len{sizeof(cpuMHz)}; - const auto ret{sysctlbyname(clockRate, &cpuMHz, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading cpu frequency." - }; - } - - return cpuMHz; -} - -static std::string getSerialNumber() -{ - return UNKNOWN_VALUE; -} - -static int getCpuCores() -{ - int cores{0}; - size_t len{sizeof(cores)}; - const std::vector mib{CTL_HW, HW_NCPU}; - const auto ret{sysctl(const_cast(mib.data()), mib.size(), &cores, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading cpu cores number." - }; - } - - return cores; -} - -static std::string getCpuName() -{ - const std::vector mib{CTL_HW, HW_MODEL}; - size_t len{0}; - auto ret{sysctl(const_cast(mib.data()), mib.size(), nullptr, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error getting cpu name size." - }; - } - - const auto spBuff{std::make_unique(len + 1)}; - - if (!spBuff) - { - throw std::runtime_error - { - "Error allocating memory to read the cpu name." - }; - } - - ret = sysctl(const_cast(mib.data()), mib.size(), spBuff.get(), &len, nullptr, 0); - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error getting cpu name" - }; - } - - spBuff.get()[len] = 0; - return std::string{reinterpret_cast(spBuff.get())}; -} - -nlohmann::json SysInfo::getHardware() const -{ - nlohmann::json hardware; - hardware["board_serial"] = getSerialNumber(); - hardware["cpu_name"] = getCpuName(); - hardware["cpu_cores"] = getCpuCores(); - hardware["cpu_mhz"] = double(getCpuMHz()); - getMemory(hardware); - return hardware; -} - -nlohmann::json SysInfo::getPackages() const -{ - nlohmann::json ret; - getPackages([&ret](nlohmann::json & data) - { - ret.push_back(data); - }); - return ret; -} - -nlohmann::json SysInfo::getProcessesInfo() const -{ - // Currently not supported for this OS - return nlohmann::json {}; -} - -nlohmann::json SysInfo::getOsInfo() const -{ - nlohmann::json ret; - struct utsname uts {}; - const auto spParser{FactorySysOsParser::create("bsd")}; - - if (!spParser->parseUname(Utils::exec("uname -r"), ret)) - { - ret["os_name"] = "BSD"; - ret["os_platform"] = "bsd"; - ret["os_version"] = UNKNOWN_VALUE; - } - - if (uname(&uts) >= 0) - { - ret["sysname"] = uts.sysname; - ret["hostname"] = uts.nodename; - ret["version"] = uts.version; - ret["architecture"] = uts.machine; - ret["release"] = uts.release; - } - - return ret; -} - -nlohmann::json SysInfo::getPorts() const -{ - // Currently not supported for this OS. - return nlohmann::json {}; -} - -void SysInfo::getProcessesInfo(std::function /*callback*/) const -{ - // Currently not supported for this OS. -} - -void SysInfo::getPackages(std::function callback) const -{ - const auto query{Utils::exec(R"(pkg query -a "%n|%m|%v|%q|%c")")}; - - if (!query.empty()) - { - const auto lines{Utils::split(query, '\n')}; - - for (const auto& line : lines) - { - const auto data{Utils::split(line, '|')}; - nlohmann::json package; - package["name"] = data[0]; - package["vendor"] = data[1]; - package["version"] = data[2]; - package["install_time"] = UNKNOWN_VALUE; - package["location"] = UNKNOWN_VALUE; - package["architecture"] = data[3]; - package["groups"] = UNKNOWN_VALUE; - package["description"] = data[4]; - package["size"] = 0; - package["priority"] = UNKNOWN_VALUE; - package["source"] = UNKNOWN_VALUE; - package["format"] = "pkg"; - // The multiarch field won't have a default value - - callback(package); - } - } -} - -nlohmann::json SysInfo::getHotfixes() const -{ - // Currently not supported for this OS. - return nlohmann::json(); -} diff --git a/src/common/data_provider/src/sysInfoLinux.cpp b/src/common/data_provider/src/sysInfoLinux.cpp index 8a3ad10ba4..7585b9bd62 100644 --- a/src/common/data_provider/src/sysInfoLinux.cpp +++ b/src/common/data_provider/src/sysInfoLinux.cpp @@ -302,11 +302,9 @@ static bool getOsInfoFromFiles(nlohmann::json& info) {"rhel", "/etc/redhat-release" }, {"gentoo", "/etc/gentoo-release" }, {"suse", "/etc/SuSE-release" }, - {"arch", "/etc/arch-release" }, {"debian", "/etc/debian_version" }, {"slackware", "/etc/slackware-version"}, {"ubuntu", "/etc/lsb-release" }, - {"alpine", "/etc/alpine-release" }, }; const auto parseFnc { diff --git a/src/common/data_provider/src/sysInfoOpenBSD.cpp b/src/common/data_provider/src/sysInfoOpenBSD.cpp deleted file mode 100644 index 3dd8131d14..0000000000 --- a/src/common/data_provider/src/sysInfoOpenBSD.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * October 7, 2020. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ -#include "sysInfo.hpp" -#include "cmdHelper.h" -#include "timeHelper.h" -#include "osinfo/sysOsParsers.h" -#include "stringHelper.h" -#include "sharedDefs.h" -#include -#include - -static void getMemory(nlohmann::json& info) -{ - uint64_t ram{0}; - const std::vector mib{CTL_HW, HW_PHYSMEM}; - size_t len{sizeof(ram)}; - auto ret{sysctl(const_cast(mib.data()), mib.size(), &ram, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading total RAM." - }; - } - - const auto ramTotal{ram / KByte}; - info["ram_total"] = ramTotal; - info["ram_free"] = 0; - info["ram_usage"] = 0; -} - -static int getCpuMHz() -{ - unsigned long cpuMHz{0}; - const std::vector mib{CTL_HW, HW_CPUSPEED}; - size_t len{sizeof(cpuMHz)}; - const auto ret{sysctl(const_cast(mib.data()), mib.size(), &cpuMHz, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading cpu frequency." - }; - } - - return cpuMHz; -} - -static std::string getSerialNumber() -{ - const std::vector mib{CTL_HW, HW_SERIALNO}; - size_t len{0}; - auto ret{sysctl(const_cast(mib.data()), mib.size(), nullptr, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error getting board serial size." - }; - } - - const auto spBuff{std::make_unique(len + 1)}; - - if (!spBuff) - { - throw std::runtime_error - { - "Error allocating memory to read the board serial." - }; - } - - ret = sysctl(const_cast(mib.data()), mib.size(), spBuff.get(), &len, nullptr, 0); - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error getting board serial" - }; - } - - spBuff.get()[len] = 0; - return std::string{reinterpret_cast(spBuff.get())}; -} - -static int getCpuCores() -{ - int cores{0}; - size_t len{sizeof(cores)}; - const std::vector mib{CTL_HW, HW_NCPU}; - const auto ret{sysctl(const_cast(mib.data()), mib.size(), &cores, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error reading cpu cores number." - }; - } - - return cores; -} - -static std::string getCpuName() -{ - const std::vector mib{CTL_HW, HW_MODEL}; - size_t len{0}; - auto ret{sysctl(const_cast(mib.data()), mib.size(), nullptr, &len, nullptr, 0)}; - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error getting cpu name size." - }; - } - - const auto spBuff{std::make_unique(len + 1)}; - - if (!spBuff) - { - throw std::runtime_error - { - "Error allocating memory to read the cpu name." - }; - } - - ret = sysctl(const_cast(mib.data()), mib.size(), spBuff.get(), &len, nullptr, 0); - - if (ret) - { - throw std::system_error - { - ret, - std::system_category(), - "Error getting cpu name" - }; - } - - spBuff.get()[len] = 0; - return std::string{reinterpret_cast(spBuff.get())}; -} - -nlohmann::json SysInfo::getHardware() const -{ - nlohmann::json hardware; - hardware["board_serial"] = getSerialNumber(); - hardware["cpu_name"] = getCpuName(); - hardware["cpu_cores"] = getCpuCores(); - hardware["cpu_mhz"] = double(getCpuMHz()); - getMemory(hardware); - return hardware; -} - -nlohmann::json SysInfo::getProcessesInfo() const -{ - // Currently not supported for this OS - return nlohmann::json {}; -} - -nlohmann::json SysInfo::getPackages() const -{ - // Currently not supported for this OS - return nlohmann::json {}; -} - -nlohmann::json SysInfo::getOsInfo() const -{ - nlohmann::json ret; - struct utsname uts {}; - const auto spParser{FactorySysOsParser::create("bsd")}; - - if (!spParser->parseUname(Utils::exec("uname -r"), ret)) - { - ret["os_name"] = "BSD"; - ret["os_platform"] = "bsd"; - ret["os_version"] = UNKNOWN_VALUE; - } - - if (uname(&uts) >= 0) - { - ret["sysname"] = uts.sysname; - ret["hostname"] = uts.nodename; - ret["version"] = uts.version; - ret["architecture"] = uts.machine; - ret["release"] = uts.release; - } - - return ret; -} - -nlohmann::json SysInfo::getPorts() const -{ - // Currently not supported for this OS - return nlohmann::json {}; -} - -void SysInfo::getProcessesInfo(std::function /*callback*/) const -{ - // Currently not supported for this OS. -} - -void SysInfo::getPackages(std::function /*callback*/) const -{ - // Currently not supported for this OS. -} - -nlohmann::json SysInfo::getHotfixes() const -{ - // Currently not supported for this OS. - return nlohmann::json(); -} diff --git a/src/common/data_provider/src/sysInfoSolaris.cpp b/src/common/data_provider/src/sysInfoSolaris.cpp deleted file mode 100644 index 9a104400f6..0000000000 --- a/src/common/data_provider/src/sysInfoSolaris.cpp +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * January 11, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ -#include -#include -#include - -#include "osinfo/sysOsParsers.h" -#include "sharedDefs.h" -#include "sysInfo.hpp" -#include "cmdHelper.h" -#include "timeHelper.h" -#include "filesystemHelper.h" -#include "packages/packageSolaris.h" -#include "packages/solarisWrapper.h" -#include "packages/packageFamilyDataAFactory.h" -#include "network/networkSolarisHelper.hpp" -#include "network/networkSolarisWrapper.hpp" -#include "network/networkFamilyDataAFactory.h" -#include "UtilsWrapperUnix.hpp" -#include "uniqueFD.hpp" - -constexpr auto SUN_APPS_PATH {"/var/sadm/pkg/"}; - - -static void getOsInfoFromUname(nlohmann::json& info) -{ - bool result{false}; - std::string platform; - const auto osPlatform{Utils::exec("uname")}; - - constexpr auto SOLARIS_RELEASE_FILE{"/etc/release"}; - const auto spParser{FactorySysOsParser::create("solaris")}; - std::fstream file{SOLARIS_RELEASE_FILE, std::ios_base::in}; - result = spParser && file.is_open() && spParser->parseFile(file, info); - - if (!result) - { - info["os_name"] = "Unix"; - info["os_platform"] = "Unix"; - info["os_version"] = UNKNOWN_VALUE; - } -} - -static std::string getSerialNumber() -{ - return UNKNOWN_VALUE; -} - -static std::string getCpuName() -{ - return UNKNOWN_VALUE; -} - -static int getCpuMHz() -{ - return 0; -} - -static int getCpuCores() -{ - return 0; -} - -static void getMemory(nlohmann::json& /*info*/) -{ - -} - -nlohmann::json SysInfo::getHardware() const -{ - nlohmann::json hardware; - hardware["board_serial"] = getSerialNumber(); - hardware["cpu_name"] = getCpuName(); - hardware["cpu_cores"] = getCpuCores(); - hardware["cpu_mhz"] = double(getCpuMHz()); - getMemory(hardware); - return hardware; -} - -static void getPackagesFromPath(const std::string& pkgDirectory, std::function callback) -{ - const auto packages { Utils::enumerateDir(pkgDirectory) }; - - for (const auto& package : packages) - { - nlohmann::json jsPackage; - const auto fullPath { pkgDirectory + package }; - const auto pkgWrapper{ std::make_shared(fullPath) }; - - FactoryPackageFamilyCreator::create(pkgWrapper)->buildPackageData(jsPackage); - - if (!jsPackage.at("name").get_ref().empty()) - { - // Only return valid content packages - callback(jsPackage); - } - } -} - -nlohmann::json SysInfo::getPackages() const -{ - nlohmann::json packages; - - getPackages([&packages](nlohmann::json & data) - { - packages.push_back(data); - }); - - return packages; -} - -nlohmann::json SysInfo::getOsInfo() const -{ - nlohmann::json ret; - struct utsname uts {}; - getOsInfoFromUname(ret); - - if (uname(&uts) >= 0) - { - ret["sysname"] = uts.sysname; - ret["hostname"] = uts.nodename; - ret["version"] = uts.version; - ret["architecture"] = uts.machine; - ret["release"] = uts.release; - } - - return ret; -} -nlohmann::json SysInfo::getProcessesInfo() const -{ - return nlohmann::json(); -} -nlohmann::json SysInfo::getNetworks() const -{ - nlohmann::json networks; - Utils::UniqueFD socketV4 ( UtilsWrapperUnix::createSocket(AF_INET, SOCK_DGRAM, 0) ); - Utils::UniqueFD socketV6 ( UtilsWrapperUnix::createSocket(AF_INET6, SOCK_DGRAM, 0) ); - const auto interfaceCount { NetworkSolarisHelper::getInterfacesCount(socketV4.get(), AF_UNSPEC) }; - - if (interfaceCount > 0) - { - std::vector buffer(interfaceCount); - lifconf lifc = - { - AF_UNSPEC, - 0, - static_cast(buffer.size() * sizeof(lifreq)), - reinterpret_cast(buffer.data()) - }; - - NetworkSolarisHelper::getInterfacesConfig(socketV4.get(), lifc); - - std::map>> interfaces; - - for (auto& item : buffer) - { - struct lifreq interfaceReq = {}; - std::memcpy(interfaceReq.lifr_name, item.lifr_name, sizeof(item.lifr_name)); - - if (-1 != UtilsWrapperUnix::ioctl(AF_INET == item.lifr_addr.ss_family ? socketV4.get() : socketV6.get(), - SIOCGLIFFLAGS, - reinterpret_cast(&interfaceReq))) - { - if ((IFF_UP & interfaceReq.lifr_flags) && !(IFF_LOOPBACK & interfaceReq.lifr_flags)) - { - interfaces[item.lifr_name].push_back(std::make_pair(&item, interfaceReq.lifr_flags)); - } - } - } - - for (const auto& item : interfaces) - { - if (item.second.size()) - { - const auto firstItem { item.second.front() }; - const auto firstItemFD { AF_INET == firstItem.first->lifr_addr.ss_family ? socketV4.get() : socketV6.get() }; - - nlohmann::json network; - - for (const auto& itemr : item.second) - { - if (AF_INET == itemr.first->lifr_addr.ss_family) - { - // IPv4 data - const auto wrapper { std::make_shared(AF_INET, socketV4.get(), itemr) }; - FactoryNetworkFamilyCreator::create(wrapper)->buildNetworkData(network); - } - else if (AF_INET6 == itemr.first->lifr_addr.ss_family) - { - // IPv6 data - const auto wrapper { std::make_shared(AF_INET6, socketV6.get(), itemr) }; - FactoryNetworkFamilyCreator::create(wrapper)->buildNetworkData(network); - } - } - - const auto wrapper { std::make_shared(AF_UNSPEC, firstItemFD, firstItem) }; - FactoryNetworkFamilyCreator::create(wrapper)->buildNetworkData(network); - - networks["iface"].push_back(network); - } - } - } - - return networks; -} -nlohmann::json SysInfo::getPorts() const -{ - return nlohmann::json(); -} -void SysInfo::getProcessesInfo(std::function /*callback*/) const -{ - // TODO -} - -void SysInfo::getPackages(std::function callback) const -{ - const auto pkgDirectory { SUN_APPS_PATH }; - - if (Utils::existsDir(pkgDirectory)) - { - getPackagesFromPath(pkgDirectory, callback); - } -} - -nlohmann::json SysInfo::getHotfixes() const -{ - // Currently not supported for this OS. - return nlohmann::json(); -} diff --git a/src/common/data_provider/src/sysInfoUnix.cpp b/src/common/data_provider/src/sysInfoUnix.cpp index 45fa2785ed..c6675ad58d 100644 --- a/src/common/data_provider/src/sysInfoUnix.cpp +++ b/src/common/data_provider/src/sysInfoUnix.cpp @@ -18,29 +18,9 @@ static void getOsInfoFromUname(nlohmann::json& info) { - bool result{false}; - std::string platform; - const auto osPlatform{Utils::exec("uname")}; - - if (osPlatform.find("SunOS") != std::string::npos) - { - constexpr auto SOLARIS_RELEASE_FILE{"/etc/release"}; - const auto spParser{FactorySysOsParser::create("solaris")}; - std::fstream file{SOLARIS_RELEASE_FILE, std::ios_base::in}; - result = spParser && file.is_open() && spParser->parseFile(file, info); - } - else if (osPlatform.find("HP-UX") != std::string::npos) - { - const auto spParser{FactorySysOsParser::create("hp-ux")}; - result = spParser && spParser->parseUname(Utils::exec("uname -r"), info); - } - - if (!result) - { - info["os_name"] = "Unix"; - info["os_platform"] = "Unix"; - info["os_version"] = UNKNOWN_VALUE; - } + info["os_name"] = "Unix"; + info["os_platform"] = "Unix"; + info["os_version"] = UNKNOWN_VALUE; } diff --git a/src/common/data_provider/tests/CMakeLists.txt b/src/common/data_provider/tests/CMakeLists.txt index 6e488f0b4a..ffbf706a3e 100644 --- a/src/common/data_provider/tests/CMakeLists.txt +++ b/src/common/data_provider/tests/CMakeLists.txt @@ -15,18 +15,12 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") add_subdirectory(sysInfoPackagesLinuxHelper) add_subdirectory(sysInfoPackagesBerkeleyDB) add_subdirectory(sysInfoNetworkLinux) - add_subdirectory(sysInfoNetworkSolaris) add_subdirectory(sysInfoRpmPackageManager) add_subdirectory(sysInfoPackageLinuxParserRpm) - add_subdirectory(sysInfoPackagesSolaris) elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") add_subdirectory(sysInfoHardwareMac) add_subdirectory(sysInfoNetworkBSD) add_subdirectory(sysInfoPackagesMAC) -elseif(CMAKE_SYSTEM_NAME STREQUAL "FreeBSD") - add_subdirectory(sysInfoNetworkBSD) -elseif(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") - add_subdirectory(sysInfoNetworkBSD) elseif(CMAKE_SYSTEM_NAME STREQUAL "Windows") add_subdirectory(sysInfoWin) add_subdirectory(sysInfoNetworkWindows) diff --git a/src/common/data_provider/tests/sysInfo/sysInfoParsers_test.cpp b/src/common/data_provider/tests/sysInfo/sysInfoParsers_test.cpp index 39ab2351f0..be43a5b497 100644 --- a/src/common/data_provider/tests/sysInfo/sysInfoParsers_test.cpp +++ b/src/common/data_provider/tests/sysInfo/sysInfoParsers_test.cpp @@ -90,57 +90,6 @@ TEST_F(SysInfoParsersTest, UnixCentos) EXPECT_EQ("8", output["os_major"]); } -TEST_F(SysInfoParsersTest, UnixArch) -{ - constexpr auto UNIX_RELEASE_FILE - { - R"( - NAME="Arch Linux" - PRETTY_NAME="Arch Linux" - ID=arch - BUILD_ID=rolling - ANSI_COLOR="38;2;23;147;209" - HOME_URL="https://www.archlinux.org/" - DOCUMENTATION_URL="https://wiki.archlinux.org/" - SUPPORT_URL="https://bbs.archlinux.org/" - BUG_REPORT_URL="https://bugs.archlinux.org/" - LOGO=archlinux - )" - }; - nlohmann::json output; - std::stringstream info{UNIX_RELEASE_FILE}; - const auto spParser{FactorySysOsParser::create("unix")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("Arch Linux", output["os_name"]); - EXPECT_EQ("arch", output["os_platform"]); -} - -TEST_F(SysInfoParsersTest, UnixAlpine) -{ - constexpr auto UNIX_RELEASE_FILE - { - R"( - NAME="Alpine Linux" - ID=alpine - VERSION_ID=3.17.1 - PRETTY_NAME="Alpine Linux v3.17" - HOME_URL="https://alpinelinux.org/" - BUG_REPORT_URL="https://gitlab.alpinelinux.org/alpine/aports/-/issues" - )" - }; - nlohmann::json output; - std::stringstream info{UNIX_RELEASE_FILE}; - const auto spParser{FactorySysOsParser::create("unix")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("3.17.1", output["os_version"]); - EXPECT_EQ("Alpine Linux", output["os_name"]); - EXPECT_EQ("alpine", output["os_platform"]); - EXPECT_EQ("3", output["os_major"]); - EXPECT_EQ("17", output["os_minor"]); - EXPECT_EQ("1", output["os_patch"]); -} - - TEST_F(SysInfoParsersTest, Ubuntu) { constexpr auto UBUNTU_RELEASE_FILE @@ -254,38 +203,6 @@ TEST_F(SysInfoParsersTest, CentosBased) EXPECT_EQ("8.8", output["os_version"]); } -TEST_F(SysInfoParsersTest, BSDFreeBSD) -{ - constexpr auto FREE_BSD_UNAME - { - "12.1-STABLE" - }; - nlohmann::json output; - const auto spParser{FactorySysOsParser::create("bsd")}; - EXPECT_TRUE(spParser->parseUname(FREE_BSD_UNAME, output)); - EXPECT_EQ("12.1", output["os_version"]); - EXPECT_EQ("BSD", output["os_name"]); - EXPECT_EQ("bsd", output["os_platform"]); - EXPECT_EQ("12", output["os_major"]); - EXPECT_EQ("1", output["os_minor"]); -} - -TEST_F(SysInfoParsersTest, BSDOpenBSD) -{ - constexpr auto FREE_BSD_UNAME - { - "6.6" - }; - nlohmann::json output; - const auto spParser{FactorySysOsParser::create("bsd")}; - EXPECT_TRUE(spParser->parseUname(FREE_BSD_UNAME, output)); - EXPECT_EQ("6.6", output["os_version"]); - EXPECT_EQ("BSD", output["os_name"]); - EXPECT_EQ("bsd", output["os_platform"]); - EXPECT_EQ("6", output["os_major"]); - EXPECT_EQ("6", output["os_minor"]); -} - TEST_F(SysInfoParsersTest, RedHatCentos) { constexpr auto REDHAT_RELEASE_FILE @@ -373,23 +290,6 @@ TEST_F(SysInfoParsersTest, Debian) EXPECT_EQ("6", output["os_minor"]); } -TEST_F(SysInfoParsersTest, Arch) -{ - constexpr auto ARCH_VERSION_FILE - { - "10.6" - }; - nlohmann::json output; - std::stringstream info{ARCH_VERSION_FILE}; - const auto spParser{FactorySysOsParser::create("arch")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("10.6", output["os_version"]); - EXPECT_EQ("Arch Linux", output["os_name"]); - EXPECT_EQ("arch", output["os_platform"]); - EXPECT_EQ("10", output["os_major"]); - EXPECT_EQ("6", output["os_minor"]); -} - TEST_F(SysInfoParsersTest, Slackware) { constexpr auto SLACKWARE_VERSION_FILE @@ -463,105 +363,6 @@ TEST_F(SysInfoParsersTest, Fedora) EXPECT_EQ("22", output["os_major"]); } -TEST_F(SysInfoParsersTest, Solaris) -{ - constexpr auto SOLARIS_VERSION_FILE - { - R"( - Oracle Solaris 11.3 X86 - Copyright (c) 1983, 2015, Oracle and/or its affiliates. All rights reserved. - Assembled 06 October 2015 - )" - }; - nlohmann::json output; - std::stringstream info{SOLARIS_VERSION_FILE}; - const auto spParser{FactorySysOsParser::create("solaris")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("11.3", output["os_version"]); - EXPECT_EQ("SunOS", output["os_name"]); - EXPECT_EQ("sunos", output["os_platform"]); - EXPECT_EQ("11", output["os_major"]); - EXPECT_EQ("3", output["os_minor"]); -} - -TEST_F(SysInfoParsersTest, Solaris1) -{ - constexpr auto SOLARIS_VERSION_FILE - { - R"( - Oracle Solaris 10 1/13 s10x_u11wos_24a X86 - Copyright (c) 1983, 2013, Oracle and/or its affiliates. All rights reserved. - Assembled 17 January 2013 - )" - }; - nlohmann::json output; - std::stringstream info{SOLARIS_VERSION_FILE}; - const auto spParser{FactorySysOsParser::create("solaris")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("10", output["os_version"]); - EXPECT_EQ("SunOS", output["os_name"]); - EXPECT_EQ("sunos", output["os_platform"]); - EXPECT_EQ("10", output["os_major"]); -} - -TEST_F(SysInfoParsersTest, Solaris2) -{ - constexpr auto SOLARIS_VERSION_FILE - { - R"( - Solaris 10 5/09 s10x_u7wos_08 X86 - Copyright 2009 Sun Microsystems, Inc. All rights reserved. - Use is subject to license terms. - Assembled 17 January 2013 - )" - }; - nlohmann::json output; - std::stringstream info{SOLARIS_VERSION_FILE}; - const auto spParser{FactorySysOsParser::create("solaris")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("10", output["os_version"]); - EXPECT_EQ("SunOS", output["os_name"]); - EXPECT_EQ("sunos", output["os_platform"]); - EXPECT_EQ("10", output["os_major"]); -} - -TEST_F(SysInfoParsersTest, HPUX) -{ - // https://docstore.mik.ua/manuals/hp-ux/en/5992-4826/pr01s02.html - constexpr auto HPUX_UNAME - { - "B.11.23" - }; - nlohmann::json output; - const auto spParser{FactorySysOsParser::create("hp-ux")}; - EXPECT_TRUE(spParser->parseUname(HPUX_UNAME, output)); - EXPECT_EQ("11.23", output["os_version"]); - EXPECT_EQ("HP-UX", output["os_name"]); - EXPECT_EQ("hp-ux", output["os_platform"]); - EXPECT_EQ("11", output["os_major"]); - EXPECT_EQ("23", output["os_minor"]); -} - -TEST_F(SysInfoParsersTest, Alpine) -{ - constexpr auto ALPINE_RELEASE_FILE - { - R"( - 3.17.1 - )" - }; - nlohmann::json output; - std::stringstream info{ALPINE_RELEASE_FILE}; - const auto spParser{FactorySysOsParser::create("alpine")}; - EXPECT_TRUE(spParser->parseFile(info, output)); - EXPECT_EQ("3.17.1", output["os_version"]); - EXPECT_EQ("Alpine Linux", output["os_name"]); - EXPECT_EQ("alpine", output["os_platform"]); - EXPECT_EQ("3", output["os_major"]); - EXPECT_EQ("17", output["os_minor"]); - EXPECT_EQ("1", output["os_patch"]); -} - TEST_F(SysInfoParsersTest, UknownPlatform) { EXPECT_THROW(FactorySysOsParser::create("some unknown platform"), std::runtime_error); diff --git a/src/common/data_provider/tests/sysInfoNetworkSolaris/CMakeLists.txt b/src/common/data_provider/tests/sysInfoNetworkSolaris/CMakeLists.txt deleted file mode 100644 index 175f51814f..0000000000 --- a/src/common/data_provider/tests/sysInfoNetworkSolaris/CMakeLists.txt +++ /dev/null @@ -1,33 +0,0 @@ -cmake_minimum_required(VERSION 3.12.4) - -project(sysInfoNetworkSolaris_unit_test) - -set(CMAKE_CXX_FLAGS_DEBUG "-g --coverage") - -file(GLOB sysinfo_UNIT_TEST_SRC - "*.cpp") - -file(GLOB SYSINFO_SRC - "${CMAKE_SOURCE_DIR}/src/network/networkInterfaceSolaris.cpp") - -add_executable(sysInfoNetworkSolaris_unit_test - ${sysinfo_UNIT_TEST_SRC} - ${SYSINFO_SRC}) - -target_link_libraries(sysInfoNetworkSolaris_unit_test - debug gtestd - debug gmockd - debug gtest_maind - debug gmock_maind - optimized gtest - optimized gmock - optimized gtest_main - optimized gmock_main - pthread - sqlite3 - cjson - dl -) - -add_test(NAME sysInfoNetworkSolaris_unit_test - COMMAND sysInfoNetworkSolaris_unit_test) diff --git a/src/common/data_provider/tests/sysInfoNetworkSolaris/main.cpp b/src/common/data_provider/tests/sysInfoNetworkSolaris/main.cpp deleted file mode 100644 index 08fb839052..0000000000 --- a/src/common/data_provider/tests/sysInfoNetworkSolaris/main.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include "gtest/gtest.h" - -int main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/common/data_provider/tests/sysInfoNetworkSolaris/sysInfoNetworkSolaris_test.cpp b/src/common/data_provider/tests/sysInfoNetworkSolaris/sysInfoNetworkSolaris_test.cpp deleted file mode 100644 index 5cd4baa14d..0000000000 --- a/src/common/data_provider/tests/sysInfoNetworkSolaris/sysInfoNetworkSolaris_test.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * October 28, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ -#include - -#include "sysInfoNetworkSolaris_test.h" -#include "network/networkFamilyDataAFactory.h" - -void SysInfoNetworkSolarisTest::SetUp() {}; - -void SysInfoNetworkSolarisTest::TearDown() -{ -}; - -using ::testing::_; -using ::testing::Return; - -class sysInfoNetworkSolarisWrapperMock : public INetworkInterfaceWrapper -{ - public: - sysInfoNetworkSolarisWrapperMock() = default; - virtual ~sysInfoNetworkSolarisWrapperMock() = default; - MOCK_METHOD( int, family, (), (const, override)); - MOCK_METHOD( std::string, name, (), (const, override)); - MOCK_METHOD( std::string, adapter, (), (const, override)); - MOCK_METHOD( std::string, address, (), (const, override)); - MOCK_METHOD( std::string, netmask, (), (const, override)); - MOCK_METHOD( std::string, broadcast, (), (const, override)); - MOCK_METHOD( std::string, addressV6, (), (const, override)); - MOCK_METHOD( std::string, netmaskV6, (), (const, override)); - MOCK_METHOD( std::string, broadcastV6, (), (const, override)); - MOCK_METHOD( std::string, gateway, (), (const, override)); - MOCK_METHOD( std::string, metrics, (), (const, override)); - MOCK_METHOD( std::string, metricsV6, (), (const, override)); - MOCK_METHOD( std::string, dhcp, (), (const, override)); - MOCK_METHOD( uint32_t, mtu, (), (const, override)); - MOCK_METHOD( LinkStats, stats, (), (const, override)); - MOCK_METHOD( std::string, type, (), (const, override)); - MOCK_METHOD( std::string, state, (), (const, override)); - MOCK_METHOD( std::string, MAC, (), (const, override)); -}; - -TEST_F(SysInfoNetworkSolarisTest, Test_AF_INET_THROW) -{ - auto mock { std::make_shared() }; - nlohmann::json ifaddr { }; - EXPECT_CALL(*mock, family()).Times(1).WillOnce(Return(AF_INET)); - EXPECT_CALL(*mock, address()).Times(1).WillOnce(Return("")); - EXPECT_ANY_THROW(FactoryNetworkFamilyCreator::create(mock)->buildNetworkData(ifaddr)); -} - -TEST_F(SysInfoNetworkSolarisTest, Test_AF_INET) -{ - auto mock { std::make_shared() }; - nlohmann::json ifaddr { }; - EXPECT_CALL(*mock, family()).Times(1).WillOnce(Return(AF_INET)); - EXPECT_CALL(*mock, address()).Times(1).WillOnce(Return("192.168.0.47")); - EXPECT_CALL(*mock, netmask()).Times(1).WillOnce(Return("255.255.255.0")); - EXPECT_CALL(*mock, broadcast()).Times(1).WillOnce(Return("192.168.0.255")); - EXPECT_CALL(*mock, metrics()).Times(1).WillOnce(Return("0")); - EXPECT_CALL(*mock, dhcp()).Times(1).WillOnce(Return("disabled")); - EXPECT_NO_THROW(FactoryNetworkFamilyCreator::create(mock)->buildNetworkData(ifaddr)); - - for (auto& element : ifaddr.at("IPv4")) - { - EXPECT_EQ("192.168.0.47", element.at("address").get_ref()); - EXPECT_EQ("255.255.255.0", element.at("netmask").get_ref()); - EXPECT_EQ("192.168.0.255", element.at("broadcast").get_ref()); - EXPECT_EQ("0", element.at("metric").get_ref()); - EXPECT_EQ("disabled", element.at("dhcp").get_ref()); - } -} - -TEST_F(SysInfoNetworkSolarisTest, Test_AF_INET6_THROW) -{ - auto mock { std::make_shared() }; - nlohmann::json ifaddr { }; - EXPECT_CALL(*mock, family()).Times(1).WillOnce(Return(AF_INET6)); - EXPECT_CALL(*mock, addressV6()).Times(1).WillOnce(Return("")); - EXPECT_ANY_THROW(FactoryNetworkFamilyCreator::create(mock)->buildNetworkData(ifaddr)); -} - -TEST_F(SysInfoNetworkSolarisTest, Test_AF_INET6) -{ - auto mock { std::make_shared() }; - nlohmann::json ifaddr { }; - EXPECT_CALL(*mock, family()).Times(1).WillOnce(Return(AF_INET6)); - EXPECT_CALL(*mock, addressV6()).Times(1).WillOnce(Return("fe80::a00:27ff:fedd:cc5b")); - EXPECT_CALL(*mock, netmaskV6()).Times(1).WillOnce(Return("ffc0::")); - EXPECT_CALL(*mock, broadcastV6()).Times(1).WillOnce(Return("")); - EXPECT_CALL(*mock, metricsV6()).Times(1).WillOnce(Return("0")); - EXPECT_CALL(*mock, dhcp()).Times(1).WillOnce(Return("enabled")); - EXPECT_NO_THROW(FactoryNetworkFamilyCreator::create(mock)->buildNetworkData(ifaddr)); - - for (auto& element : ifaddr.at("IPv6")) - { - EXPECT_EQ("fe80::a00:27ff:fedd:cc5b", element.at("address").get_ref()); - EXPECT_EQ("ffc0::", element.at("netmask").get_ref()); - EXPECT_EQ("", element.at("broadcast").get_ref()); - EXPECT_EQ("0", element.at("metric").get_ref()); - EXPECT_EQ("enabled", element.at("dhcp").get_ref()); - } -} - -TEST_F(SysInfoNetworkSolarisTest, Test_AF_UNSPEC) -{ - auto mock { std::make_shared() }; - nlohmann::json ifaddr { }; - EXPECT_CALL(*mock, family()).Times(1).WillOnce(Return(AF_UNSPEC)); - EXPECT_CALL(*mock, name()).Times(1).WillOnce(Return("net0")); - EXPECT_CALL(*mock, adapter()).Times(1).WillOnce(Return("")); - EXPECT_CALL(*mock, state()).Times(1).WillOnce(Return("up")); - EXPECT_CALL(*mock, type()).Times(1).WillOnce(Return("Ethernet")); - EXPECT_CALL(*mock, MAC()).Times(1).WillOnce(Return("")); - EXPECT_CALL(*mock, stats()).Times(1).WillOnce(Return(LinkStats{436300, 220902, 641204623, 12252455, 0, 0, 0, 0})); - EXPECT_CALL(*mock, mtu()).Times(1).WillOnce(Return(1500u)); - EXPECT_CALL(*mock, gateway()).Times(1).WillOnce(Return("10.0.2.2")); - EXPECT_NO_THROW(FactoryNetworkFamilyCreator::create(mock)->buildNetworkData(ifaddr)); - - EXPECT_EQ("net0", ifaddr.at("name").get_ref()); - EXPECT_EQ("", ifaddr.at("adapter").get_ref()); - EXPECT_EQ("up", ifaddr.at("state").get_ref()); - EXPECT_EQ("Ethernet", ifaddr.at("type").get_ref()); - EXPECT_EQ("", ifaddr.at("mac").get_ref()); - - EXPECT_EQ(220902u, ifaddr.at("tx_packets").get()); - EXPECT_EQ(436300u, ifaddr.at("rx_packets").get()); - EXPECT_EQ(12252455u, ifaddr.at("tx_bytes").get()); - EXPECT_EQ(641204623u, ifaddr.at("rx_bytes").get()); - EXPECT_EQ(0u, ifaddr.at("tx_errors").get()); - EXPECT_EQ(0u, ifaddr.at("rx_errors").get()); - EXPECT_EQ(0u, ifaddr.at("tx_dropped").get()); - EXPECT_EQ(0u, ifaddr.at("rx_dropped").get()); - - EXPECT_EQ(1500u, ifaddr.at("mtu").get()); - EXPECT_EQ("10.0.2.2", ifaddr.at("gateway").get_ref()); -} - -TEST_F(SysInfoNetworkSolarisTest, Test_THROW_NULLPTR) -{ - nlohmann::json ifaddr { }; - EXPECT_ANY_THROW(FactoryNetworkFamilyCreator::create(nullptr)->buildNetworkData(ifaddr)); -} diff --git a/src/common/data_provider/tests/sysInfoNetworkSolaris/sysInfoNetworkSolaris_test.h b/src/common/data_provider/tests/sysInfoNetworkSolaris/sysInfoNetworkSolaris_test.h deleted file mode 100644 index 46e47bac28..0000000000 --- a/src/common/data_provider/tests/sysInfoNetworkSolaris/sysInfoNetworkSolaris_test.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * October 28, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ -#ifndef _SYSINFO_NETWORK_SOLARIS_TEST_H -#define _SYSINFO_NETWORK_SOLARIS_TEST_H -#include "gtest/gtest.h" -#include "gmock/gmock.h" - -class SysInfoNetworkSolarisTest : public ::testing::Test -{ - - protected: - - SysInfoNetworkSolarisTest() = default; - virtual ~SysInfoNetworkSolarisTest() = default; - - void SetUp() override; - void TearDown() override; -}; - -#endif //_SYSINFO_NETWORK_SOLARIS_TEST_H diff --git a/src/common/data_provider/tests/sysInfoPackagesLinuxHelper/sysInfoPackagesLinuxHelper_test.cpp b/src/common/data_provider/tests/sysInfoPackagesLinuxHelper/sysInfoPackagesLinuxHelper_test.cpp index 354e8938b7..bb67413137 100644 --- a/src/common/data_provider/tests/sysInfoPackagesLinuxHelper/sysInfoPackagesLinuxHelper_test.cpp +++ b/src/common/data_provider/tests/sysInfoPackagesLinuxHelper/sysInfoPackagesLinuxHelper_test.cpp @@ -11,13 +11,9 @@ #include "sysInfoPackagesLinuxHelper_test.h" #include "packages/packageLinuxParserHelper.h" -#include "packages/packageLinuxParserHelperExtra.h" #include "packages/packageLinuxRpmParserHelper.h" #include "packages/packageLinuxRpmParserHelperLegacy.h" -#include "packages/packageLinuxApkParserHelper.h" #include "packages/rpmPackageManager.h" -#include -#include #include "sharedDefs.h" using ::testing::_; @@ -328,111 +324,6 @@ TEST_F(SysInfoPackagesLinuxHelperTest, parseDpkgInformation) EXPECT_EQ("zlib", jsPackageInfo["source"]); } -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkNameKeyNotFound) -{ - std::vector> input; - input.push_back(std::pair('V', "1.2.3-r4")); - input.push_back(std::pair('A', "x86_64")); - input.push_back(std::pair('I', "634880")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ(true, jsPackageInfo.empty()); -} - -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkVersionKeyNotFound) -{ - std::vector> input; - input.push_back(std::pair('P', "musl")); - input.push_back(std::pair('A', "x86_64")); - input.push_back(std::pair('I', "634880")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ(true, jsPackageInfo.empty()); -} - -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkArchitectureKeyNotFound) -{ - std::vector> input; - input.push_back(std::pair('P', "musl")); - input.push_back(std::pair('V', "1.2.3-r4")); - input.push_back(std::pair('I', "634880")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ("musl", jsPackageInfo.at("name")); - EXPECT_EQ("1.2.3-r4", jsPackageInfo.at("version")); - EXPECT_EQ(UNKNOWN_VALUE, jsPackageInfo.at("architecture")); - EXPECT_EQ(634880, jsPackageInfo.at("size")); - EXPECT_EQ("the musl c library (libc) implementation", jsPackageInfo.at("description")); - EXPECT_EQ("apk", jsPackageInfo.at("format")); - EXPECT_EQ("Alpine Linux", jsPackageInfo.at("vendor")); -} - -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkNameValueEmpty) -{ - std::vector> input; - input.push_back(std::pair('P', "")); - input.push_back(std::pair('V', "1.2.3-r4")); - input.push_back(std::pair('A', "x86_64")); - input.push_back(std::pair('I', "634880")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ(true, jsPackageInfo.empty()); -} - -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkVersionValueEmpty) -{ - std::vector> input; - input.push_back(std::pair('P', "musl")); - input.push_back(std::pair('V', "")); - input.push_back(std::pair('A', "x86_64")); - input.push_back(std::pair('I', "634880")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ(true, jsPackageInfo.empty()); -} - -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkSizeValueEmpty) -{ - std::vector> input; - input.push_back(std::pair('P', "musl")); - input.push_back(std::pair('V', "1.2.3-r4")); - input.push_back(std::pair('A', "x86_64")); - input.push_back(std::pair('I', "")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ("musl", jsPackageInfo.at("name")); - EXPECT_EQ("1.2.3-r4", jsPackageInfo.at("version")); - EXPECT_EQ("x86_64", jsPackageInfo.at("architecture")); - EXPECT_EQ(0, jsPackageInfo.at("size")); - EXPECT_EQ("the musl c library (libc) implementation", jsPackageInfo.at("description")); - EXPECT_EQ("apk", jsPackageInfo.at("format")); - EXPECT_EQ("Alpine Linux", jsPackageInfo.at("vendor")); -} - -TEST_F(SysInfoPackagesLinuxHelperTest, parseApkSuccess) -{ - std::vector> input; - input.push_back(std::pair('P', "musl")); - input.push_back(std::pair('V', "1.2.3-r4")); - input.push_back(std::pair('A', "x86_64")); - input.push_back(std::pair('I', "634880")); - input.push_back(std::pair('T', "the musl c library (libc) implementation")); - - const auto& jsPackageInfo { PackageLinuxHelper::parseApk(input) }; - EXPECT_EQ("musl", jsPackageInfo.at("name")); - EXPECT_EQ("1.2.3-r4", jsPackageInfo.at("version")); - EXPECT_EQ(634880, jsPackageInfo.at("size")); - EXPECT_EQ("the musl c library (libc) implementation", jsPackageInfo.at("description")); - EXPECT_EQ("apk", jsPackageInfo.at("format")); - EXPECT_EQ("Alpine Linux", jsPackageInfo.at("vendor")); -} - TEST_F(SysInfoPackagesLinuxHelperTest, parseSnapCorrectMapping) { const auto& jsPackageInfo { PackageLinuxHelper::parseSnap( R"( diff --git a/src/common/data_provider/tests/sysInfoPackagesSolaris/CMakeLists.txt b/src/common/data_provider/tests/sysInfoPackagesSolaris/CMakeLists.txt deleted file mode 100644 index a3e3c0a43b..0000000000 --- a/src/common/data_provider/tests/sysInfoPackagesSolaris/CMakeLists.txt +++ /dev/null @@ -1,31 +0,0 @@ -cmake_minimum_required(VERSION 3.12.4) - -project(sysInfoSolarisPackage_unit_test) - -set(CMAKE_CXX_FLAGS_DEBUG "-g --coverage") - -file(GLOB sysinfo_UNIT_TEST_SRC - "*.cpp") - -file(GLOB SYSINFO_SRC - "${CMAKE_SOURCE_DIR}/src/packages/packageSolaris.cpp") - -add_executable(sysInfoSolarisPackage_unit_test - ${sysinfo_UNIT_TEST_SRC} - ${SYSINFO_SRC}) - -target_link_libraries(sysInfoSolarisPackage_unit_test - debug gtestd - debug gmockd - debug gtest_maind - debug gmock_maind - optimized gtest - optimized gmock - optimized gtest_main - optimized gmock_main - pthread - sqlite3 -) - -add_test(NAME sysInfoSolarisPackage_unit_test - COMMAND sysInfoSolarisPackage_unit_test) diff --git a/src/common/data_provider/tests/sysInfoPackagesSolaris/main.cpp b/src/common/data_provider/tests/sysInfoPackagesSolaris/main.cpp deleted file mode 100644 index 4e4f649247..0000000000 --- a/src/common/data_provider/tests/sysInfoPackagesSolaris/main.cpp +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#include "gtest/gtest.h" - -int main(int argc, char** argv) -{ - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); -} diff --git a/src/common/data_provider/tests/sysInfoPackagesSolaris/sysInfoSolarisPackages_test.cpp b/src/common/data_provider/tests/sysInfoPackagesSolaris/sysInfoSolarisPackages_test.cpp deleted file mode 100644 index ba18c78cc7..0000000000 --- a/src/common/data_provider/tests/sysInfoPackagesSolaris/sysInfoSolarisPackages_test.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#include "sysInfoSolarisPackages_test.h" -#include "packages/packageFamilyDataAFactory.h" -#include "packages/packageSolaris.h" - -void SysInfoSolarisPackagesTest::SetUp() {}; - -void SysInfoSolarisPackagesTest::TearDown() {}; - -using ::testing::_; -using ::testing::Return; - -class SysInfoSolarisPackagesWrapperMock: public IPackageWrapper -{ - public: - SysInfoSolarisPackagesWrapperMock() = default; - virtual ~SysInfoSolarisPackagesWrapperMock() = default; - MOCK_METHOD(std::string, name, (), (const override)); - MOCK_METHOD(std::string, version, (), (const override)); - MOCK_METHOD(std::string, groups, (), (const override)); - MOCK_METHOD(std::string, description, (), (const override)); - MOCK_METHOD(std::string, architecture, (), (const override)); - MOCK_METHOD(std::string, format, (), (const override)); - MOCK_METHOD(std::string, osPatch, (), (const override)); - MOCK_METHOD(std::string, source, (), (const override)); - MOCK_METHOD(std::string, location, (), (const override)); - MOCK_METHOD(std::string, priority, (), (const override)); - MOCK_METHOD(int, size, (), (const override)); - MOCK_METHOD(std::string, vendor, (), (const override)); - MOCK_METHOD(std::string, install_time, (), (const override)); - MOCK_METHOD(std::string, multiarch, (), (const override)); -}; - -TEST_F(SysInfoSolarisPackagesTest, Test_Success_Data) -{ - auto mock { std::make_shared() }; - nlohmann::json packages {}; - - EXPECT_CALL(*mock, name()).Times(1).WillOnce(Return("libstdc++6")); - EXPECT_CALL(*mock, version()).Times(1).WillOnce(Return("5.5.0")); - EXPECT_CALL(*mock, groups()).Times(1).WillOnce(Return("application")); - EXPECT_CALL(*mock, description()).Times(1).WillOnce(Return("libstdc++6 - The GNU Compiler Collection, libstdc++.so.6")); - EXPECT_CALL(*mock, architecture()).Times(1).WillOnce(Return("i386")); - EXPECT_CALL(*mock, format()).Times(1).WillOnce(Return("pkg")); - EXPECT_CALL(*mock, source()).Times(1).WillOnce(Return("")); - EXPECT_CALL(*mock, location()).Times(1).WillOnce(Return("")); - EXPECT_CALL(*mock, priority()).Times(1).WillOnce(Return("")); - EXPECT_CALL(*mock, size()).Times(1).WillOnce(Return(0)); - EXPECT_CALL(*mock, vendor()).Times(1).WillOnce(Return("Oracle corporation")); - EXPECT_CALL(*mock, install_time()).Times(1).WillOnce(Return("2022/01/13 14:48:58")); - - EXPECT_NO_THROW(FactoryPackageFamilyCreator::create(mock)->buildPackageData(packages)); - - EXPECT_EQ("libstdc++6", packages.at("name").get_ref()); - EXPECT_EQ("5.5.0", packages.at("version").get_ref()); - EXPECT_EQ("application", packages.at("groups").get_ref()); - EXPECT_EQ("libstdc++6 - The GNU Compiler Collection, libstdc++.so.6", packages.at("description").get_ref()); - EXPECT_EQ("i386", packages.at("architecture").get_ref()); - EXPECT_EQ("pkg", packages.at("format").get_ref()); - EXPECT_EQ("", packages.at("source").get_ref()); - EXPECT_EQ("", packages.at("location").get_ref()); - EXPECT_EQ("", packages.at("priority").get_ref()); - EXPECT_EQ(0, packages.at("size").get()); - EXPECT_EQ("Oracle corporation", packages.at("vendor").get_ref()); - EXPECT_EQ("2022/01/13 14:48:58", packages.at("install_time").get_ref()); -} diff --git a/src/common/data_provider/tests/sysInfoPackagesSolaris/sysInfoSolarisPackages_test.h b/src/common/data_provider/tests/sysInfoPackagesSolaris/sysInfoSolarisPackages_test.h deleted file mode 100644 index ee94b89dd6..0000000000 --- a/src/common/data_provider/tests/sysInfoPackagesSolaris/sysInfoSolarisPackages_test.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Wazuh SysInfo - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2022. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - -#ifndef _SYSINFO_SOLARIS_PACKAGES_TEST_H -#define _SYSINFO_SOLARIS_PACKAGES_TEST_H -#include "gtest/gtest.h" -#include "gmock/gmock.h" - -class SysInfoSolarisPackagesTest : public ::testing::Test -{ - - protected: - - SysInfoSolarisPackagesTest() = default; - virtual ~SysInfoSolarisPackagesTest() = default; - - void SetUp() override; - void TearDown() override; -}; - -#endif //_SYSINFO_SOLARIS_PACKAGES_TEST_H diff --git a/src/common/data_provider/testtool/CMakeLists.txt b/src/common/data_provider/testtool/CMakeLists.txt index fdaa799af0..dafb1e860e 100644 --- a/src/common/data_provider/testtool/CMakeLists.txt +++ b/src/common/data_provider/testtool/CMakeLists.txt @@ -38,16 +38,6 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") ws2_32 -static-libstdc++ ) -elseif (CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") - target_link_libraries(sysinfo_test_tool - sysinfo - pthread) -elseif (CMAKE_SYSTEM_NAME STREQUAL "AIX" OR CMAKE_SYSTEM_NAME STREQUAL "HP-UX") - target_link_libraries(sysinfo_test_tool - sysinfo - dl - pthread - ) else() target_link_libraries(sysinfo_test_tool sysinfo @@ -55,14 +45,6 @@ else() pthread proc ) - - if(SOLARIS) - target_link_libraries(sysinfo_test_tool - sysinfo - nsl - socket - ) - endif(SOLARIS) endif(CMAKE_SYSTEM_NAME STREQUAL "Windows") if(APPLE) diff --git a/src/common/dbsync/CMakeLists.txt b/src/common/dbsync/CMakeLists.txt index f37dc700e1..9838af39e2 100644 --- a/src/common/dbsync/CMakeLists.txt +++ b/src/common/dbsync/CMakeLists.txt @@ -52,12 +52,7 @@ include_directories(${COMMON_FOLDER}/stringHelper/include/) include_directories(${COMMON_FOLDER}/threadDispatcher/include/) include_directories(${COMMON_FOLDER}/utils/) -if(CMAKE_SYSTEM_NAME STREQUAL "HP-UX") - link_directories(${INSTALL_PREFIX}/lib) - add_definitions(-DPROMISE_TYPE=PromiseType::SLEEP) -else() - add_definitions(-DPROMISE_TYPE=PromiseType::NORMAL) -endif(CMAKE_SYSTEM_NAME STREQUAL "HP-UX") +add_definitions(-DPROMISE_TYPE=PromiseType::NORMAL) link_directories(${SRC_FOLDER}) @@ -79,22 +74,11 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") # MinGW generates position-independent-code for DLL by default ) elseif(UNIX AND NOT APPLE) - if(NOT CMAKE_SYSTEM_NAME STREQUAL "AIX" AND NOT CMAKE_SYSTEM_NAME STREQUAL "HP-UX") - string(APPEND CMAKE_SHARED_LINKER_FLAGS " -Wl,-rpath=$ORIGIN") - endif(NOT CMAKE_SYSTEM_NAME STREQUAL "AIX" AND NOT CMAKE_SYSTEM_NAME STREQUAL "HP-UX") + string(APPEND CMAKE_SHARED_LINKER_FLAGS " -Wl,-rpath=$ORIGIN") endif(CMAKE_SYSTEM_NAME STREQUAL "Windows") target_link_libraries(dbsync utils nlohmann_json::nlohmann_json cjson unofficial::sqlite3::sqlite3) -if(CMAKE_BUILD_TYPE STREQUAL "Release") - if(CMAKE_SYSTEM_NAME STREQUAL "AIX") - string(REPLACE ";" ":" CXX_IMPLICIT_LINK_DIRECTORIES_STR "${CMAKE_CXX_IMPLICIT_LINK_DIRECTORIES}") - string(REPLACE ";" ":" PLATFORM_REQUIRED_RUNTIME_PATH_STR "${CMAKE_PLATFORM_REQUIRED_RUNTIME_PATH}") - target_link_libraries(dbsync -Wl,-blibpath:${INSTALL_PREFIX}/lib:${CXX_IMPLICIT_LINK_DIRECTORIES_STR}:${PLATFORM_REQUIRED_RUNTIME_PATH_STR}) - endif(CMAKE_SYSTEM_NAME STREQUAL "AIX") -endif(CMAKE_BUILD_TYPE STREQUAL "Release") - - if(UNIT_TEST) if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") target_link_libraries(dbsync -fprofile-arcs) diff --git a/src/common/dbsync/example/CMakeLists.txt b/src/common/dbsync/example/CMakeLists.txt index 6aef6ad456..f51144325e 100644 --- a/src/common/dbsync/example/CMakeLists.txt +++ b/src/common/dbsync/example/CMakeLists.txt @@ -24,10 +24,6 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") pthread -static-libgcc -static-libstdc++ ) -elseif(CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") - target_link_libraries(dbsync_example - dbsync - pthread) else() target_link_libraries(dbsync_example dbsync diff --git a/src/common/dbsync/testtool/CMakeLists.txt b/src/common/dbsync/testtool/CMakeLists.txt index 67eb81e7f0..72bb78a016 100644 --- a/src/common/dbsync/testtool/CMakeLists.txt +++ b/src/common/dbsync/testtool/CMakeLists.txt @@ -28,10 +28,6 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") dbsync -static-libstdc++ ) -elseif (CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") - target_link_libraries(dbsync_test_tool - dbsync - pthread) else() target_link_libraries(dbsync_test_tool dbsync diff --git a/src/common/hashHelper/include/hashHelper.h b/src/common/hashHelper/include/hashHelper.h index c210be9b75..d2369e8697 100644 --- a/src/common/hashHelper/include/hashHelper.h +++ b/src/common/hashHelper/include/hashHelper.h @@ -148,9 +148,9 @@ namespace Utils HashData hash; while (inputFile.read(buffer.data(), buffer.size())) { - hash.update(buffer.data(), inputFile.gcount()); + hash.update(buffer.data(), static_cast(inputFile.gcount())); } - hash.update(buffer.data(), inputFile.gcount()); + hash.update(buffer.data(), static_cast(inputFile.gcount())); return hash.hash(); } diff --git a/src/common/http-request/.clang-format b/src/common/http-request/.clang-format deleted file mode 100644 index 764273061d..0000000000 --- a/src/common/http-request/.clang-format +++ /dev/null @@ -1,46 +0,0 @@ -AlignAfterOpenBracket: Align -AlignConsecutiveMacros: 'true' -AlignConsecutiveAssignments: 'false' -AlignConsecutiveDeclarations: 'false' -AlignEscapedNewlines: Right -AlignOperands: 'true' -AlignTrailingComments: 'true' -AllowAllArgumentsOnNextLine: 'true' -AllowAllConstructorInitializersOnNextLine: 'true' -AllowAllParametersOfDeclarationOnNextLine: 'true' -AllowShortBlocksOnASingleLine: 'false' -AllowShortCaseLabelsOnASingleLine: 'true' -AllowShortFunctionsOnASingleLine: Empty -AllowShortIfStatementsOnASingleLine: Never -AllowShortLambdasOnASingleLine: Inline -AllowShortLoopsOnASingleLine: 'true' -AlwaysBreakBeforeMultilineStrings: 'false' -AlwaysBreakTemplateDeclarations: 'Yes' -BinPackArguments: 'false' -BinPackParameters: 'false' -BreakBeforeBraces: Allman -BreakConstructorInitializers: BeforeComma -BreakInheritanceList: BeforeComma -FixNamespaceComments: 'true' -IncludeBlocks: Preserve -IndentCaseLabels: 'true' -SortIncludes: 'true' -SpaceAfterCStyleCast: 'false' -SpaceAfterLogicalNot: 'false' -SpaceAfterTemplateKeyword: 'false' -SpaceBeforeAssignmentOperators: 'true' -Cpp11BracedListStyle: 'true' -SpaceBeforeParens: ControlStatements -SpaceBeforeCpp11BracedList: 'true' -SpaceBeforeCtorInitializerColon: 'true' -SpaceBeforeInheritanceColon: 'true' -SpaceInEmptyParentheses: 'false' -Standard: Auto -SpacesInAngles: 'false' -IndentWidth: '4' -TabWidth: '4' -AccessModifierOffset: '-4' -UseTab: Never -PointerAlignment: Left -ColumnLimit: 120 - diff --git a/src/common/http-request/include/HTTPRequest.hpp b/src/common/http-request/include/HTTPRequest.hpp index 3e7ec6a742..fd2c1e6813 100644 --- a/src/common/http-request/include/HTTPRequest.hpp +++ b/src/common/http-request/include/HTTPRequest.hpp @@ -13,10 +13,10 @@ #define _HTTP_REQUEST_HPP #include "IURLRequest.hpp" -#include #include "singleton.hpp" #include #include +#include #include #include diff --git a/src/common/http-request/include/UNIXSocketRequest.hpp b/src/common/http-request/include/UNIXSocketRequest.hpp index f17253719f..37a09a4926 100644 --- a/src/common/http-request/include/UNIXSocketRequest.hpp +++ b/src/common/http-request/include/UNIXSocketRequest.hpp @@ -13,11 +13,11 @@ #define _UNIX_SOCKET_REQUEST_HPP #include "IURLRequest.hpp" -#include #include "singleton.hpp" #include #include #include +#include #include #include diff --git a/src/common/http-request/shared/builder.hpp b/src/common/http-request/shared/builder.hpp index fc3525ea87..0f4bd79f8f 100644 --- a/src/common/http-request/shared/builder.hpp +++ b/src/common/http-request/shared/builder.hpp @@ -17,40 +17,38 @@ namespace Utils { +/** + * @brief This class provides a simple interface to construct an object using a Builder pattern. + * + * @tparam T Type of the object to be built. + * @tparam Ts Arguments. + */ +template +class Builder +{ +public: /** - * @brief This class provides a simple interface to construct an object using a Builder pattern. + * @brief This method is used to build an object. * - * @tparam T Type of the object to be built. - * @tparam Ts Arguments. + * @param args Arguments. + * @return T Object built. */ - template - class Builder + static T builder(Ts... args) { - public: - /** - * @brief This method is used to build an object. - * - * @param args Arguments. - * @return T Object built. - */ - static T builder(Ts... args) - { - return T(std::move(args)...); // Default constructor - } + return T(std::move(args)...); // Default constructor + } - /** - * @brief This method returns a reference to the object. - * @return T Reference to the object. - */ - T & build() - { - return static_cast(*this); // Return reference to self - } - }; -} + /** + * @brief This method returns a reference to the object. + * @return T Reference to the object. + */ + T& build() + { + return static_cast(*this); // Return reference to self + } +}; +} // namespace Utils #pragma GCC diagnostic pop #endif // _BUILDER_PATTERN_HPP - - diff --git a/src/common/http-request/shared/curlException.hpp b/src/common/http-request/shared/curlException.hpp index 7ae1c7f02f..011689a519 100644 --- a/src/common/http-request/shared/curlException.hpp +++ b/src/common/http-request/shared/curlException.hpp @@ -18,58 +18,60 @@ namespace Curl { +/** + * @brief Custom exception for Curl wrapper. + * + */ +class CurlException : public std::exception +{ +public: /** - * @brief Custom exception for Curl wrapper. + * @brief Returns HTTP response code ID. * + * @return long HTTP response code ID. */ - class CurlException : public std::exception + long responseCode() const noexcept { - public: - /** - * @brief Returns HTTP response code ID. - * - * @return long HTTP response code ID. - */ - long responseCode() const noexcept - { - return m_responseCode; - } + return m_responseCode; + } - /** - * @brief Return error message. - * - * @return const char* Error message. - */ - const char* what() const noexcept override - { - return m_error.what(); - } + /** + * @brief Return error message. + * + * @return const char* Error message. + */ + const char* what() const noexcept override + { + return m_error.what(); + } - /** - * @brief Construct a new Curl Exception object - * - * @param errorMessage Error message to show. - * @param responseCode HTTP response code ID. - */ - CurlException(const std::string& errorMessage, const long responseCode) - : m_error {errorMessage} - , m_responseCode {responseCode} - {} + /** + * @brief Construct a new Curl Exception object + * + * @param errorMessage Error message to show. + * @param responseCode HTTP response code ID. + */ + CurlException(const std::string& errorMessage, const long responseCode) + : m_error {errorMessage} + , m_responseCode {responseCode} + { + } - /** - * @brief Construct a new Curl Exception object - * - * @param curlException Pair object with an error message and a response code ID. - */ - explicit CurlException(const std::pair& curlException) - : m_error {curlException.first} - , m_responseCode {curlException.second} - {} + /** + * @brief Construct a new Curl Exception object + * + * @param curlException Pair object with an error message and a response code ID. + */ + explicit CurlException(const std::pair& curlException) + : m_error {curlException.first} + , m_responseCode {curlException.second} + { + } - private: - std::runtime_error m_error; - const long m_responseCode; - }; -} +private: + std::runtime_error m_error; + const long m_responseCode; +}; +} // namespace Curl #endif // _CURL_EXCEPTION_HPP diff --git a/src/common/http-request/shared/customDeleter.hpp b/src/common/http-request/shared/customDeleter.hpp index a64ca7d36a..2f23d0fb55 100644 --- a/src/common/http-request/shared/customDeleter.hpp +++ b/src/common/http-request/shared/customDeleter.hpp @@ -12,7 +12,7 @@ #ifndef _CUSTOM_DELETER_HPP #define _CUSTOM_DELETER_HPP -template +template /** * @brief Custom deleter for unique_ptr. * @tparam F Function type. @@ -20,8 +20,8 @@ template */ class CustomDeleter { - public: - template +public: + template /** * @brief Call function to delete the object. * @param arg Object to delete. diff --git a/src/common/http-request/shared/singleton.hpp b/src/common/http-request/shared/singleton.hpp index c0903e09e8..84e9b30bd7 100644 --- a/src/common/http-request/shared/singleton.hpp +++ b/src/common/http-request/shared/singleton.hpp @@ -20,22 +20,22 @@ template class Singleton { - public: - /** - * @brief Returns the instance of the singleton class. - * @return Instance of the singleton class. - */ - static T& instance() - { - static T s_instance; - return s_instance; - } - protected: - Singleton() = default; - virtual ~Singleton() = default; - Singleton(const Singleton&) = delete; - Singleton& operator=(const Singleton&) = delete; +public: + /** + * @brief Returns the instance of the singleton class. + * @return Instance of the singleton class. + */ + static T& instance() + { + static T s_instance; + return s_instance; + } + +protected: + Singleton() = default; + virtual ~Singleton() = default; + Singleton(const Singleton&) = delete; + Singleton& operator=(const Singleton&) = delete; }; #endif // _SINGLETON_HPP - diff --git a/src/common/http-request/shared/tests/mocks/mockFsWrapper.hpp b/src/common/http-request/shared/tests/mocks/mockFsWrapper.hpp index fb0b39c828..ffd656d816 100644 --- a/src/common/http-request/shared/tests/mocks/mockFsWrapper.hpp +++ b/src/common/http-request/shared/tests/mocks/mockFsWrapper.hpp @@ -29,4 +29,3 @@ class MockFsWrapper }; #endif // _MOCKFSWRAPPER_HPP - diff --git a/src/common/http-request/src/HTTPRequest.cpp b/src/common/http-request/src/HTTPRequest.cpp index ca518aa4b7..02ea2487e6 100644 --- a/src/common/http-request/src/HTTPRequest.cpp +++ b/src/common/http-request/src/HTTPRequest.cpp @@ -12,9 +12,9 @@ #include "HTTPRequest.hpp" #include "curlWrapper.hpp" #include "factoryRequestImplemetator.hpp" -#include #include "urlRequest.hpp" #include +#include #include #include diff --git a/src/common/http-request/src/curlSingleHandler.hpp b/src/common/http-request/src/curlSingleHandler.hpp index 27be203297..f7f89d465e 100644 --- a/src/common/http-request/src/curlSingleHandler.hpp +++ b/src/common/http-request/src/curlSingleHandler.hpp @@ -13,9 +13,9 @@ #define _CURL_SINGLE_HANDLER_HPP #include "ICURLHandler.hpp" -#include #include "curlException.hpp" #include "customDeleter.hpp" +#include #include #include #include diff --git a/src/common/http-request/src/curlWrapper.hpp b/src/common/http-request/src/curlWrapper.hpp index f9956080af..c9c5aea2fc 100644 --- a/src/common/http-request/src/curlWrapper.hpp +++ b/src/common/http-request/src/curlWrapper.hpp @@ -14,13 +14,13 @@ #include "ICURLHandler.hpp" #include "IRequestImplementator.hpp" -#include #include "curlHandlerCache.hpp" #include "curlMultiHandler.hpp" #include "curlSingleHandler.hpp" #include "customDeleter.hpp" #include #include +#include #include #include #include diff --git a/src/common/http-request/src/urlRequest.hpp b/src/common/http-request/src/urlRequest.hpp index ce9eaa399c..b36b405854 100644 --- a/src/common/http-request/src/urlRequest.hpp +++ b/src/common/http-request/src/urlRequest.hpp @@ -16,12 +16,12 @@ #include "builder.hpp" #include "customDeleter.hpp" #include "fsWrapper.hpp" -#include #include "secureCommunication.hpp" #include #include #include #include +#include #include #include #include diff --git a/src/common/privsep_op/include/privsep_op.h b/src/common/privsep_op/include/privsep_op.h index 57af0d7774..212f333408 100644 --- a/src/common/privsep_op/include/privsep_op.h +++ b/src/common/privsep_op/include/privsep_op.h @@ -15,13 +15,7 @@ #include "shared.h" -#if defined(SUN_MAJOR_VERSION) && defined(SUN_MINOR_VERSION) && \ - (SUN_MAJOR_VERSION < 11) || \ - ((SUN_MAJOR_VERSION == 11) && (SUN_MINOR_VERSION < 4)) -#define w_ctime(x,y,z) ctime_r(x,y,z) -#else #define w_ctime(x,y,z) ctime_r(x,y) -#endif /** * @brief Find a user by name diff --git a/src/common/privsep_op/src/privsep_op.c b/src/common/privsep_op/src/privsep_op.c index 7ae9185169..169967c32a 100644 --- a/src/common/privsep_op/src/privsep_op.c +++ b/src/common/privsep_op/src/privsep_op.c @@ -22,11 +22,7 @@ #include "os_err.h" struct passwd *w_getpwnam(const char *name, struct passwd *pwd, char *buf, size_t buflen) { -#if defined(SUN_MAJOR_VERSION) && defined(SUN_MINOR_VERSION) && \ - (SUN_MAJOR_VERSION < 11) || \ - ((SUN_MAJOR_VERSION == 11) && (SUN_MINOR_VERSION < 4)) - return getpwnam_r(name, pwd, buf, buflen); -#else + struct passwd *result = NULL; int retval = getpwnam_r(name, pwd, buf, buflen, &result); @@ -35,15 +31,10 @@ struct passwd *w_getpwnam(const char *name, struct passwd *pwd, char *buf, size_ } return result; -#endif } struct passwd *w_getpwuid(uid_t uid, struct passwd *pwd, char *buf, int buflen) { -#if defined(SUN_MAJOR_VERSION) && defined(SUN_MINOR_VERSION) && \ - (SUN_MAJOR_VERSION < 11) || \ - ((SUN_MAJOR_VERSION == 11) && (SUN_MINOR_VERSION < 4)) - return getpwuid_r(uid, pwd, buf, buflen); -#else + struct passwd *result = NULL; int retval = getpwuid_r(uid, pwd, buf, buflen, &result); @@ -52,15 +43,10 @@ struct passwd *w_getpwuid(uid_t uid, struct passwd *pwd, char *buf, int bufle } return result; -#endif } struct group *w_getgrnam(const char *name, struct group *grp, char *buf, int buflen) { -#if defined(SUN_MAJOR_VERSION) && defined(SUN_MINOR_VERSION) && \ - (SUN_MAJOR_VERSION < 11) || \ - ((SUN_MAJOR_VERSION == 11) && (SUN_MINOR_VERSION < 4)) - return getgrnam_r(name, grp, buf, buflen); -#else + struct group *result = NULL; int retval = getgrnam_r(name, grp, buf, buflen, &result); @@ -69,15 +55,10 @@ struct group *w_getgrnam(const char *name, struct group *grp, char *buf, int } return result; -#endif } struct group *w_getgrgid(gid_t gid, struct group *grp, char *buf, int buflen) { -#if defined(SUN_MAJOR_VERSION) && defined(SUN_MINOR_VERSION) && \ - (SUN_MAJOR_VERSION < 11) || \ - ((SUN_MAJOR_VERSION == 11) && (SUN_MINOR_VERSION < 4)) - return getgrgid_r(gid, grp, buf, buflen); -#else + struct group *result = NULL; int retval = getgrgid_r(gid, grp, buf, buflen, &result); @@ -86,7 +67,6 @@ struct group *w_getgrgid(gid_t gid, struct group *grp, char *buf, int buflen) { } return result; -#endif } uid_t Privsep_GetUser(const char *name) diff --git a/src/common/stringHelper/include/stringHelper.h b/src/common/stringHelper/include/stringHelper.h index 28dfb807a9..fe8e727482 100644 --- a/src/common/stringHelper/include/stringHelper.h +++ b/src/common/stringHelper/include/stringHelper.h @@ -46,21 +46,21 @@ namespace Utils for (auto it = data.begin(); it != data.end(); ++it) { - const uint8_t ch = *it; + const uint8_t ch = static_cast(static_cast(*it)); // ASCII character if (ch < UTF8_2BYTE_FIRST_CODE_VALUE) { - strOut.push_back(ch); + strOut.push_back(static_cast(ch)); } // Extended ASCII else { // 2-byte sequence // 110xxxxx - strOut.push_back(UTF8_2BYTE_SEQ | ch >> UTF8_2BYTE_SEQ_VALUE_LEN); + strOut.push_back(static_cast(UTF8_2BYTE_SEQ | (ch >> UTF8_2BYTE_SEQ_VALUE_LEN))); // 10xxxxxx - strOut.push_back(UTF8_2BYTE_FIRST_CODE_VALUE | (ch & UTF8_2BYTE_MASK)); + strOut.push_back(static_cast(UTF8_2BYTE_FIRST_CODE_VALUE | (ch & UTF8_2BYTE_MASK))); } } diff --git a/src/common/syscheck_op/src/syscheck_op.c b/src/common/syscheck_op/src/syscheck_op.c index d0d10c5cd6..5ac68d249a 100644 --- a/src/common/syscheck_op/src/syscheck_op.c +++ b/src/common/syscheck_op/src/syscheck_op.c @@ -131,13 +131,8 @@ char *get_user(int uid) { os_calloc(bufsize, sizeof(char), buf); -#if defined(SUN_MAJOR_VERSION) && defined(SUN_MINOR_VERSION) && \ - (SUN_MAJOR_VERSION < 11) || \ - ((SUN_MAJOR_VERSION == 11) && (SUN_MINOR_VERSION < 4)) - result = getpwuid_r(uid, &pwd, buf, bufsize); -#else errno = getpwuid_r(uid, &pwd, buf, bufsize, &result); -#endif + if (result == NULL) { if (errno == 0) { mdebug2("User with uid '%d' not found.\n", uid); diff --git a/src/common/utils/include/shared.h b/src/common/utils/include/shared.h index d586d82ea3..83a1f87262 100644 --- a/src/common/utils/include/shared.h +++ b/src/common/utils/include/shared.h @@ -53,11 +53,6 @@ #include #endif -/* HPUX does not have select.h */ -#ifndef HPUX -#include -#endif - #include #endif /* WIN32 */ @@ -99,11 +94,6 @@ #ifdef __cplusplus #include #define _Atomic(T) std::atomic -#else -#ifdef hpux -// TODO: remove this line after upgrading GCC on HP-UX -#define _Atomic(T) T -#endif #endif #include @@ -125,7 +115,6 @@ #include "randombytes.h" #include "bzip2_op.h" - #ifndef LARGEFILE64_SOURCE #define LARGEFILE64_SOURCE #endif /* LARGEFILE64_SOURCE */ @@ -136,29 +125,6 @@ /* Global portability code */ -#ifdef SOLARIS -#include -typedef uint32_t u_int32_t; -typedef uint16_t u_int16_t; -typedef uint8_t u_int8_t; - -#ifndef va_copy -#define va_copy __va_copy -#endif - -#endif /* SOLARIS */ - -#if defined(HPUX) || defined(DOpenBSD) -#include -typedef uint64_t u_int64_t; -typedef int int32_t; -typedef uint32_t u_int32_t; -typedef uint16_t u_int16_t; -typedef uint8_t u_int8_t; - -#define MSG_DONTWAIT 0 -#endif - #ifdef Darwin typedef int sock2len_t; #endif @@ -187,10 +153,6 @@ typedef uint8_t u_int8_t; #endif #endif /* WIN32 */ -#ifdef AIX -#define MSG_DONTWAIT MSG_NONBLOCK -#endif - #if defined(__GNUC__) && __GNUC__ >= 7 #define WFALLTHROUGH __attribute__ ((fallthrough)) #else diff --git a/src/common/validate_op/src/validate_op.c b/src/common/validate_op/src/validate_op.c index 415886b2ca..4aee999a04 100644 --- a/src/common/validate_op/src/validate_op.c +++ b/src/common/validate_op/src/validate_op.c @@ -10,6 +10,7 @@ #include "shared.h" #include "validate_op.h" +#include "expression.h" #include "os_net.h" #ifdef WAZUH_UNIT_TESTING diff --git a/src/common/version_op/tests/unit/tests/test_version_op.c b/src/common/version_op/tests/unit/tests/test_version_op.c index 7bf3c31596..79e8d78a18 100644 --- a/src/common/version_op/tests/unit/tests/test_version_op.c +++ b/src/common/version_op/tests/unit/tests/test_version_op.c @@ -18,7 +18,6 @@ #include "../wrappers/common.h" #include "../wrappers/libc/stdio_wrappers.h" #include "../wrappers/wazuh/shared/binaries_op_wrappers.h" -#include "../headers/version_op.h" /* setup/teardowns */ static int setup_group(void **state) { diff --git a/src/modules/CMakeLists.txt b/src/modules/CMakeLists.txt index 7f61dea654..43a3e3815c 100644 --- a/src/modules/CMakeLists.txt +++ b/src/modules/CMakeLists.txt @@ -2,14 +2,17 @@ cmake_minimum_required(VERSION 3.22) project(ModuleManager) -set(CMAKE_CXX_STANDARD 20) -set(CMAKE_CXX_STANDARD_REQUIRED True) +include(../cmake/CommonSettings.cmake) +set_common_settings() add_subdirectory(inventory) add_library(ModuleManager src/moduleManager.cpp) target_include_directories(ModuleManager PUBLIC include) -target_link_libraries(ModuleManager PUBLIC inventory) +target_link_libraries(ModuleManager PUBLIC Inventory) + +include(../cmake/ConfigureTarget.cmake) +configure_target(ModuleManager) if(BUILD_TESTS) enable_testing() diff --git a/src/modules/include/configuration.hpp b/src/modules/include/configuration.hpp deleted file mode 100644 index 4cde7dc309..0000000000 --- a/src/modules/include/configuration.hpp +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once - -#define INVENTORY_DEFAULT_INTERVAL 3600 - -struct InventoryConfig { - bool enabled = true; - unsigned int interval = INVENTORY_DEFAULT_INTERVAL; - bool scanOnStart = true; - bool hardware = true; - bool os = true; - bool network = true; - bool packages = true; - bool ports = true; - bool portsAll = true; - bool processes = true; - bool hotfixes = true; -}; - -class Configuration { - public: - Configuration() = default; - - Configuration(const InventoryConfig& config) : inventoryConfig(config) {} - - void setInventoryConfig(const InventoryConfig& config) { - inventoryConfig = config; - } - - const InventoryConfig& getInventoryConfig() const { return inventoryConfig; } - - private: - InventoryConfig inventoryConfig; -}; diff --git a/src/modules/include/moduleManager.hpp b/src/modules/include/moduleManager.hpp index 7158eeca45..71944f1fe3 100644 --- a/src/modules/include/moduleManager.hpp +++ b/src/modules/include/moduleManager.hpp @@ -4,58 +4,59 @@ #include #include #include -#include #include #include using namespace std; template -concept Module = requires(T t, const Configuration & config, const string & query, +concept Module = requires(T t, const configuration::ConfigurationParser& configurationParser, const string & query, const std::shared_ptr queue) { - { t.start() } -> same_as; - { t.setup(config) } -> same_as; - { t.stop() } -> same_as; - { t.command(query) } -> same_as; - { t.name() } -> same_as; - { t.setMessageQueue(queue) } -> same_as; + { t.Start() } -> same_as; + { t.Setup(configurationParser) } -> same_as; + { t.Stop() } -> same_as; + { t.Command(query) } -> same_as; + { t.Name() } -> same_as; + { t.SetMessageQueue(queue) } -> same_as; }; class ModuleManager { public: - ModuleManager() = default; + ModuleManager(const std::shared_ptr& messageQueue, + const configuration::ConfigurationParser& configurationParser) + : m_multiTypeQueue(messageQueue) + , m_configurationParser(configurationParser) + {} ~ModuleManager() = default; template - void addModule(T& module) { - const std::string& moduleName = module.name(); - if (modules.find(moduleName) != modules.end()) { + void AddModule(T& module) { + const std::string& moduleName = module.Name(); + if (m_modules.find(moduleName) != m_modules.end()) { throw std::runtime_error("Module '" + moduleName + "' already exists."); } - module.setMessageQueue(multiTypeQueue); + module.SetMessageQueue(m_multiTypeQueue); auto wrapper = make_shared(ModuleWrapper{ - .start = [&module]() { module.start(); }, - .setup = [&module](const Configuration & config) { return module.setup(config); }, - .stop = [&module]() { module.stop(); }, - .command = [&module](const string & query) { return module.command(query); }, - .name = [&module]() { return module.name(); } + .Start = [&module]() { module.Start(); }, + .Setup = [&module](const configuration::ConfigurationParser& configurationParser) { module.Setup(configurationParser); }, + .Stop = [&module]() { module.Stop(); }, + .Command = [&module](const string & query) { return module.Command(query); }, + .Name = [&module]() { return module.Name(); } }); - modules[moduleName] = wrapper; + m_modules[moduleName] = wrapper; } - shared_ptr getModule(const string & name); - void start(); - void setup(const Configuration & config); - void stop(); - void setMessageQueue(const std::shared_ptr& messageQueue) { - multiTypeQueue = messageQueue; - } + shared_ptr GetModule(const string & name); + void Start(); + void Setup(); + void Stop(); private: - map> modules; - vector threads; - std::shared_ptr multiTypeQueue; + map> m_modules; + vector m_threads; + std::shared_ptr m_multiTypeQueue; + configuration::ConfigurationParser m_configurationParser; }; diff --git a/src/modules/include/moduleWrapper.hpp b/src/modules/include/moduleWrapper.hpp index b39151628d..ec67f8e0cb 100644 --- a/src/modules/include/moduleWrapper.hpp +++ b/src/modules/include/moduleWrapper.hpp @@ -2,14 +2,14 @@ #include #include -#include "configuration.hpp" +#include using namespace std; struct ModuleWrapper { - function start; - function setup; - function stop; - function command; - function name; + function Start; + function Setup; + function Stop; + function Command; + function Name; }; diff --git a/src/modules/inventory/CMakeLists.txt b/src/modules/inventory/CMakeLists.txt index 70f67a6609..14746de12a 100644 --- a/src/modules/inventory/CMakeLists.txt +++ b/src/modules/inventory/CMakeLists.txt @@ -2,6 +2,9 @@ cmake_minimum_required(VERSION 3.22) project(Inventory) +include(../../cmake/CommonSettings.cmake) +set_common_settings() + get_filename_component(SRC_FOLDER ${CMAKE_CURRENT_SOURCE_DIR}/../../ ABSOLUTE) get_filename_component(COMMON_FOLDER ${SRC_FOLDER}/common/ ABSOLUTE) @@ -9,12 +12,12 @@ find_package(cJSON CONFIG REQUIRED) find_package(nlohmann_json CONFIG REQUIRED) find_package(OpenSSL REQUIRED) -add_library(inventory +add_library(Inventory src/inventory.cpp src/inventoryImp.cpp src/inventoryNormalizer.cpp) -target_include_directories(inventory PUBLIC +target_include_directories(Inventory PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include ${CMAKE_CURRENT_SOURCE_DIR}/../include ${COMMON_FOLDER} @@ -31,14 +34,13 @@ target_include_directories(inventory PUBLIC ${COMMON_FOLDER}/timeHelper/include ${COMMON_FOLDER}/utils) -if(LINUX) - target_link_directories(inventory PUBLIC ${SRC_FOLDER}/external/rpm/builddir/) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_link_directories(Inventory PUBLIC ${SRC_FOLDER}/external/rpm/builddir/) endif() -target_link_directories(inventory PUBLIC ${SRC_FOLDER}/external/libdb/build_unix/) -target_link_directories(inventory PUBLIC ${SRC_FOLDER}/external/procps/) - +target_link_directories(Inventory PUBLIC ${SRC_FOLDER}/external/libdb/build_unix/) +target_link_directories(Inventory PUBLIC ${SRC_FOLDER}/external/procps/) -target_link_libraries(inventory PUBLIC +target_link_libraries(Inventory PUBLIC dbsync sysinfo cjson @@ -48,7 +50,12 @@ target_link_libraries(inventory PUBLIC utils logging_helper pthreads_op - MultiTypeQueue) + ConfigurationParser + MultiTypeQueue + Logger) + +include(../../cmake/ConfigureTarget.cmake) +configure_target(Inventory) add_subdirectory(testtool) diff --git a/src/modules/inventory/include/inventory.hpp b/src/modules/inventory/include/inventory.hpp index 854b6f8b48..1ee04c5d2a 100644 --- a/src/modules/inventory/include/inventory.hpp +++ b/src/modules/inventory/include/inventory.hpp @@ -8,7 +8,7 @@ #include #include #include -#include +#include #include #include #include @@ -17,25 +17,25 @@ class Inventory { public: - static Inventory& instance() + static Inventory& Instance() { static Inventory s_instance; return s_instance; } - void start(); - int setup(const Configuration & config); - void stop(); - std::string command(const std::string & query); - std::string name() const; - void setMessageQueue(const std::shared_ptr queue); + void Start(); + void Setup(const configuration::ConfigurationParser& configurationParser); + void Stop(); + std::string Command(const std::string & query); + const std::string& Name() const { return m_moduleName; }; + void SetMessageQueue(const std::shared_ptr queue); - void init(const std::shared_ptr& spInfo, - const std::function reportDiffFunction, + void Init(const std::shared_ptr& spInfo, + const std::function& reportDiffFunction, const std::string& dbPath, const std::string& normalizerConfigPath, const std::string& normalizerType); - virtual void sendDeltaEvent(const std::string& data); + virtual void SendDeltaEvent(const std::string& data); private: Inventory(); @@ -43,46 +43,45 @@ class Inventory { Inventory(const Inventory&) = delete; Inventory& operator=(const Inventory&) = delete; - void destroy(); + void Destroy(); - std::string getCreateStatement() const; - nlohmann::json getOSData(); - nlohmann::json getHardwareData(); - nlohmann::json getNetworkData(); - nlohmann::json getPortsData(); + std::string GetCreateStatement() const; + nlohmann::json GetOSData(); + nlohmann::json GetHardwareData(); + nlohmann::json GetNetworkData(); + nlohmann::json GetPortsData(); - void updateChanges(const std::string& table, - const nlohmann::json& values); - void notifyChange(ReturnTypeCallback result, - const nlohmann::json& data, - const std::string& table); - void scanHardware(); - void scanOs(); - void scanNetwork(); - void scanPackages(); - void scanHotfixes(); - void scanPorts(); - void scanProcesses(); - void scan(); - void syncLoop(std::unique_lock& lock); - void showConfig(); - cJSON * dump(); - static void log(const modules_log_level_t level, const std::string& log); - static void logError(const std::string& log); + void UpdateChanges(const std::string& table, const nlohmann::json& values); + void NotifyChange(ReturnTypeCallback result, const nlohmann::json& data, const std::string& table); + void TryCatchTask(const std::function& task) const; + void ScanHardware(); + void ScanOs(); + void ScanNetwork(); + void ScanPackages(); + void ScanHotfixes(); + void ScanPorts(); + void ScanProcesses(); + void Scan(); + void SyncLoop(std::unique_lock& lock); + void ShowConfig(); + cJSON * Dump(); + static void Log(const modules_log_level_t level, const std::string& log); + static void LogErrorInventory(const std::string& log); + const std::string m_moduleName {"inventory"}; std::shared_ptr m_spInfo; std::function m_reportDiffFunction; - std::chrono::seconds m_intervalValue; - bool m_enabled; // Main switch - bool m_scanOnStart; // Scan always on start - bool m_hardware; // Hardware inventory - bool m_os; // OS inventory - bool m_network; // Network inventory - bool m_packages; // Installed packages inventory - bool m_ports; // Opened ports inventory - bool m_portsAll; // Scan only listening ports or all - bool m_processes; // Running processes inventory - bool m_hotfixes; // Windows hotfixes installed + bool m_enabled; // Main switch + std::chrono::seconds m_intervalValue; // Scan interval + bool m_scanOnStart; // Scan always on start + bool m_hardware; // Hardware inventory + bool m_os; // OS inventory + bool m_network; // Network inventory + bool m_packages; // Installed packages inventory + bool m_ports; // Opened ports inventory + bool m_portsAll; // Scan only listening ports or all + bool m_processes; // Running processes inventory + bool m_hotfixes; // Windows hotfixes installed bool m_stopping; bool m_notify; std::unique_ptr m_spDBSync; diff --git a/src/modules/inventory/include/inventoryNormalizer.hpp b/src/modules/inventory/include/inventoryNormalizer.hpp index 4bb06abe55..6a848b87f8 100644 --- a/src/modules/inventory/include/inventoryNormalizer.hpp +++ b/src/modules/inventory/include/inventoryNormalizer.hpp @@ -1,13 +1,3 @@ -/* - * Wazuh Inventory - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #pragma once #include #include @@ -19,12 +9,10 @@ class InvNormalizer InvNormalizer(const std::string& configFile, const std::string& target); ~InvNormalizer() = default; - void normalize(const std::string& type, - nlohmann::json& data) const; - void removeExcluded(const std::string& type, - nlohmann::json& data) const; + void Normalize(const std::string& type, nlohmann::json& data) const; + void RemoveExcluded(const std::string& type, nlohmann::json& data) const; private: - static std::map getTypeValues(const std::string& configFile, + static std::map GetTypeValues(const std::string& configFile, const std::string& target, const std::string& type); const std::map m_typeExclusions; diff --git a/src/modules/inventory/src/inventory.cpp b/src/modules/inventory/src/inventory.cpp index 4d6fc7e190..2295e997cf 100644 --- a/src/modules/inventory/src/inventory.cpp +++ b/src/modules/inventory/src/inventory.cpp @@ -1,14 +1,3 @@ -/* - * Wazuh Inventory - * Copyright (C) 2015, Wazuh Inc. - * July 15, 2024. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 3) as published by the FSF - Free Software - * Foundation. - */ - #include #include #include @@ -21,104 +10,94 @@ using namespace std; -#define INV_LOGTAG "modules:inventory" // Tag for log messages +constexpr const char* INV_LOGTAG = "modules:inventory"; // Tag for log messages -void Inventory::start() { +void Inventory::Start() { if (!m_enabled) { - log(LOG_INFO, "Module disabled. Exiting..."); - pthread_exit(NULL); + Log(LOG_INFO, "Module disabled. Exiting..."); + return; } - log(LOG_INFO, "Starting inventory."); + Log(LOG_INFO, "Starting inventory."); - showConfig(); + ShowConfig(); - DBSync::initialize(logError); + DBSync::initialize(LogErrorInventory); try { - Inventory::instance().init(std::make_shared(), - [this](const std::string& diff) { this->sendDeltaEvent(diff); }, + Inventory::Instance().Init(std::make_shared(), + [this](const std::string& diff) { this->SendDeltaEvent(diff); }, INVENTORY_DB_DISK_PATH, INVENTORY_NORM_CONFIG_DISK_PATH, INVENTORY_NORM_TYPE); } catch (const std::exception& ex) { - logError(ex.what()); + LogErrorInventory(ex.what()); } - log(LOG_INFO, "Module finished."); + Log(LOG_INFO, "Module finished."); } -int Inventory::setup(const Configuration & config) { - - const InventoryConfig& inventoryConfig = config.getInventoryConfig(); - - m_enabled = inventoryConfig.enabled; - m_intervalValue = std::chrono::seconds{inventoryConfig.interval}; - m_scanOnStart = inventoryConfig.scanOnStart; - m_hardware = inventoryConfig.hardware; - m_os = inventoryConfig.os; - m_network = inventoryConfig.network; - m_packages = inventoryConfig.packages; - m_ports = inventoryConfig.ports; - m_portsAll = inventoryConfig.portsAll; - m_processes = inventoryConfig.processes; - m_hotfixes = inventoryConfig.hotfixes; - - m_notify = true; - - return 0; +void Inventory::Setup(const configuration::ConfigurationParser& configurationParser) { + + m_enabled = !configurationParser.GetConfig("inventory", "disabled"); + m_intervalValue = std::chrono::seconds{configurationParser.GetConfig("inventory", "interval")}; + m_scanOnStart = configurationParser.GetConfig("inventory", "scan_on_start"); + m_hardware = configurationParser.GetConfig("inventory", "hardware"); + m_os = configurationParser.GetConfig("inventory", "os"); + m_network = configurationParser.GetConfig("inventory", "network"); + m_packages = configurationParser.GetConfig("inventory", "packages"); + m_ports = configurationParser.GetConfig("inventory", "ports"); + m_portsAll = configurationParser.GetConfig("inventory", "ports_all"); + m_processes = configurationParser.GetConfig("inventory", "processes"); + m_hotfixes = configurationParser.GetConfig("inventory", "hotfixes"); } -void Inventory::stop() { - log(LOG_INFO, "Module stopped."); - Inventory::instance().destroy(); +void Inventory::Stop() { + Log(LOG_INFO, "Module stopped."); + Inventory::Instance().Destroy(); } -string Inventory::command(const string & query) { - log(LOG_INFO, "Query: " + query); +string Inventory::Command(const string & query) { + Log(LOG_INFO, "Query: " + query); return "OK"; } -string Inventory::name() const { - return "inventory"; -} - -void Inventory::setMessageQueue(const std::shared_ptr queue) { +void Inventory::SetMessageQueue(const std::shared_ptr queue) { m_messageQueue = queue; } -void Inventory::sendDeltaEvent(const string& data) { +void Inventory::SendDeltaEvent(const string& data) { const auto jsonData = nlohmann::json::parse(data); - const Message message{ MessageType::STATELESS, jsonData, name() }; + const Message message{ MessageType::STATELESS, jsonData, Name() }; if(!m_messageQueue->push(message)) { - log(LOG_WARNING, "Delta event can't be pushed into the message queue: " + data); + Log(LOG_WARNING, "Delta event can't be pushed into the message queue: " + data); } else { - log(LOG_DEBUG_VERBOSE, "Delta sent: " + data); + Log(LOG_DEBUG_VERBOSE, "Delta sent: " + data); } } -void Inventory::showConfig() +void Inventory::ShowConfig() { - cJSON * configJson = dump(); + cJSON * configJson = Dump(); if (configJson) { char * configString = cJSON_PrintUnformatted(configJson); if (configString) { - log(LOG_DEBUG, configString); + Log(LOG_DEBUG, configString); cJSON_free(configString); } cJSON_Delete(configJson); } } -cJSON * Inventory::dump() { +cJSON * Inventory::Dump() { cJSON *rootJson = cJSON_CreateObject(); cJSON *invJson = cJSON_CreateObject(); @@ -126,7 +105,7 @@ cJSON * Inventory::dump() { // System provider values if (m_enabled) cJSON_AddStringToObject(invJson,"disabled","no"); else cJSON_AddStringToObject(invJson,"disabled","yes"); if (m_scanOnStart) cJSON_AddStringToObject(invJson,"scan-on-start","yes"); else cJSON_AddStringToObject(invJson,"scan-on-start","no"); - cJSON_AddNumberToObject(invJson,"interval",m_intervalValue.count()); + cJSON_AddNumberToObject(invJson, "interval", static_cast(m_intervalValue.count())); if (m_network) cJSON_AddStringToObject(invJson,"network","yes"); else cJSON_AddStringToObject(invJson,"network","no"); if (m_os) cJSON_AddStringToObject(invJson,"os","yes"); else cJSON_AddStringToObject(invJson,"os","no"); if (m_hardware) cJSON_AddStringToObject(invJson,"hardware","yes"); else cJSON_AddStringToObject(invJson,"hardware","no"); @@ -143,12 +122,12 @@ cJSON * Inventory::dump() { return rootJson; } -void Inventory::log(const modules_log_level_t level, const std::string& log) +void Inventory::Log(const modules_log_level_t level, const std::string& log) { taggedLogFunction(level, log.c_str(), INV_LOGTAG); } -void Inventory::logError(const std::string& log) +void Inventory::LogErrorInventory(const std::string& log) { taggedLogFunction(LOG_ERROR, log.c_str(), INV_LOGTAG); } diff --git a/src/modules/inventory/src/inventoryImp.cpp b/src/modules/inventory/src/inventoryImp.cpp index 6311e984db..d136a2ed56 100644 --- a/src/modules/inventory/src/inventoryImp.cpp +++ b/src/modules/inventory/src/inventoryImp.cpp @@ -1,13 +1,3 @@ -/* - * Wazuh Inventory - * Copyright (C) 2015, Wazuh Inc. - * October 7, 2020. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #include #include #include @@ -15,26 +5,7 @@ #include #include -constexpr std::chrono::seconds MAX_DELAY_TIME -{ - 300 -}; - -#define TRY_CATCH_TASK(task) \ -do \ -{ \ - try \ - { \ - if(!m_stopping) \ - { \ - task(); \ - } \ - } \ - catch(const std::exception& ex) \ - { \ - logError(std::string{ex.what()}); \ - } \ -}while(0) +constexpr std::chrono::seconds INVENTORY_DEFAULT_INTERVAL { 3600 }; constexpr auto QUEUE_SIZE { @@ -75,78 +46,6 @@ constexpr auto OS_SQL_STATEMENT PRIMARY KEY (os_name)) WITHOUT ROWID;)" }; -constexpr auto OS_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_osinfo", - "component":"inventory_osinfo", - "index":"os_name", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE os_name BETWEEN '?' and '?' ORDER BY os_name", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE os_name BETWEEN '?' and '?' ORDER BY os_name", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE os_name ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE os_name BETWEEN '?' and '?' ORDER BY os_name", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - -constexpr auto OS_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_osinfo", - "first_query": - { - "column_list":["os_name"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"os_name DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["os_name"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"os_name ASC", - "count_opt":1 - }, - "component":"inventory_osinfo", - "index":"os_name", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE os_name BETWEEN '?' and '?' ORDER BY os_name", - "column_list":["os_name, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":100 - } - })" -}; - constexpr auto HW_SQL_STATEMENT { R"(CREATE TABLE dbsync_hwinfo ( @@ -161,79 +60,6 @@ constexpr auto HW_SQL_STATEMENT PRIMARY KEY (board_serial)) WITHOUT ROWID;)" }; -constexpr auto HW_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_hwinfo", - "component":"inventory_hwinfo", - "index":"board_serial", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE board_serial BETWEEN '?' and '?' ORDER BY board_serial", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE board_serial BETWEEN '?' and '?' ORDER BY board_serial", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE board_serial ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE board_serial BETWEEN '?' and '?' ORDER BY board_serial", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - -constexpr auto HW_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_hwinfo", - "first_query": - { - "column_list":["board_serial"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"board_serial DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["board_serial"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"board_serial ASC", - "count_opt":1 - }, - "component":"inventory_hwinfo", - "index":"board_serial", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE board_serial BETWEEN '?' and '?' ORDER BY board_serial", - "column_list":["board_serial, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":100 - } - })" -}; - - constexpr auto HOTFIXES_SQL_STATEMENT { R"(CREATE TABLE dbsync_hotfixes( @@ -242,78 +68,6 @@ constexpr auto HOTFIXES_SQL_STATEMENT PRIMARY KEY (hotfix)) WITHOUT ROWID;)" }; -constexpr auto HOTFIXES_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_hotfixes", - "component":"inventory_hotfixes", - "index":"hotfix", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE hotfix BETWEEN '?' and '?' ORDER BY hotfix", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE hotfix BETWEEN '?' and '?' ORDER BY hotfix", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE hotfix ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE hotfix BETWEEN '?' and '?' ORDER BY hotfix", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - -constexpr auto HOTFIXES_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_hotfixes", - "first_query": - { - "column_list":["hotfix"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"hotfix DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["hotfix"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"hotfix ASC", - "count_opt":1 - }, - "component":"inventory_hotfixes", - "index":"hotfix", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE hotfix BETWEEN '?' and '?' ORDER BY hotfix", - "column_list":["hotfix, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":100 - } - })" -}; - constexpr auto PACKAGES_SQL_STATEMENT { R"(CREATE TABLE dbsync_packages( @@ -336,150 +90,6 @@ constexpr auto PACKAGES_SQL_STATEMENT }; static const std::vector PACKAGES_ITEM_ID_FIELDS{"name", "version", "architecture", "format", "location"}; -constexpr auto PACKAGES_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_packages", - "component":"inventory_packages", - "index":"item_id", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE item_id ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - -constexpr auto PACKAGES_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_packages", - "first_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id ASC", - "count_opt":1 - }, - "component":"inventory_packages", - "index":"item_id", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["item_id, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":100 - } - })" -}; - -constexpr auto PROCESSES_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_processes", - "first_query": - { - "column_list":["pid"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"pid DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["pid"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"pid ASC", - "count_opt":1 - }, - "component":"inventory_processes", - "index":"pid", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE pid BETWEEN '?' and '?' ORDER BY pid", - "column_list":["pid, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":1000 - } - })" -}; - -constexpr auto PROCESSES_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_processes", - "component":"inventory_processes", - "index":"pid", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE pid BETWEEN '?' and '?' ORDER BY pid", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE pid BETWEEN '?' and '?' ORDER BY pid", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE pid ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE pid BETWEEN '?' and '?' ORDER BY pid", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - constexpr auto PROCESSES_SQL_STATEMENT { R"(CREATE TABLE dbsync_processes ( @@ -515,78 +125,6 @@ constexpr auto PROCESSES_SQL_STATEMENT PRIMARY KEY (pid)) WITHOUT ROWID;)" }; -constexpr auto PORTS_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_ports", - "first_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id ASC", - "count_opt":1 - }, - "component":"inventory_ports", - "index":"item_id", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["item_id, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":1000 - } - })" -}; - -constexpr auto PORTS_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_ports", - "component":"inventory_ports", - "index":"item_id", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE item_id ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - constexpr auto PORTS_SQL_STATEMENT { R"(CREATE TABLE dbsync_ports ( @@ -607,78 +145,6 @@ constexpr auto PORTS_SQL_STATEMENT }; static const std::vector PORTS_ITEM_ID_FIELDS{"inode", "protocol", "local_ip", "local_port"}; -constexpr auto NETIFACE_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_network_iface", - "first_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id ASC", - "count_opt":1 - }, - "component":"inventory_network_iface", - "index":"item_id", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["item_id, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":1000 - } - })" -}; - -constexpr auto NETIFACE_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_network_iface", - "component":"inventory_network_iface", - "index":"item_id", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE item_id ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - constexpr auto NETIFACE_SQL_STATEMENT { R"(CREATE TABLE dbsync_network_iface ( @@ -702,78 +168,6 @@ constexpr auto NETIFACE_SQL_STATEMENT }; static const std::vector NETIFACE_ITEM_ID_FIELDS{"name", "adapter", "type"}; -constexpr auto NETPROTO_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_network_protocol", - "first_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id ASC", - "count_opt":1 - }, - "component":"inventory_network_protocol", - "index":"item_id", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["item_id, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":1000 - } - })" -}; - -constexpr auto NETPROTO_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_network_protocol", - "component":"inventory_network_protocol", - "index":"item_id", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE item_id ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - constexpr auto NETPROTO_SQL_STATEMENT { R"(CREATE TABLE dbsync_network_protocol ( @@ -788,78 +182,6 @@ constexpr auto NETPROTO_SQL_STATEMENT }; static const std::vector NETPROTO_ITEM_ID_FIELDS{"iface", "type"}; -constexpr auto NETADDRESS_START_CONFIG_STATEMENT -{ - R"({"table":"dbsync_network_address", - "first_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id DESC", - "count_opt":1 - }, - "last_query": - { - "column_list":["item_id"], - "row_filter":" ", - "distinct_opt":false, - "order_by_opt":"item_id ASC", - "count_opt":1 - }, - "component":"inventory_network_address", - "index":"item_id", - "last_event":"last_event", - "checksum_field":"checksum", - "range_checksum_query_json": - { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["item_id, checksum"], - "distinct_opt":false, - "order_by_opt":"", - "count_opt":1000 - } - })" -}; - -constexpr auto NETADDRESS_SYNC_CONFIG_STATEMENT -{ - R"( - { - "decoder_type":"JSON_RANGE", - "table":"dbsync_network_address", - "component":"inventory_network_address", - "index":"item_id", - "checksum_field":"checksum", - "no_data_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "count_range_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "count_field_name":"count", - "column_list":["count(*) AS count "], - "distinct_opt":false, - "order_by_opt":"" - }, - "row_data_query_json": { - "row_filter":"WHERE item_id ='?'", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - }, - "range_checksum_query_json": { - "row_filter":"WHERE item_id BETWEEN '?' and '?' ORDER BY item_id", - "column_list":["*"], - "distinct_opt":false, - "order_by_opt":"" - } - } - )" -}; - constexpr auto NETADDR_SQL_STATEMENT { R"(CREATE TABLE dbsync_network_address ( @@ -885,7 +207,7 @@ constexpr auto OS_TABLE { "dbsync_osinfo" }; constexpr auto HW_TABLE { "dbsync_hwinfo" }; -static std::string getItemId(const nlohmann::json& item, const std::vector& idFields) +static std::string GetItemId(const nlohmann::json& item, const std::vector& idFields) { Utils::HashData hash; @@ -909,7 +231,7 @@ static std::string getItemId(const nlohmann::json& item, const std::vector& keyValue) +static bool IsElementDuplicated(const nlohmann::json& input, const std::pair& keyValue) { const auto it { @@ -948,11 +270,11 @@ static bool isElementDuplicated(const nlohmann::json& input, const std::pair& task) const +{ + try + { + if (!m_stopping) + { + task(); // Ejecuta la tarea + } + } + catch (const std::exception& ex) + { + LogErrorInventory(std::string{ex.what()}); + } +} + Inventory::Inventory() - : m_intervalValue { 0 } - , m_scanOnStart { false } - , m_hardware { false } - , m_os { false } - , m_network { false } - , m_packages { false } - , m_ports { false } - , m_portsAll { false } - , m_processes { false } - , m_hotfixes { false } + : m_enabled { true } + , m_intervalValue { INVENTORY_DEFAULT_INTERVAL } + , m_scanOnStart { true } + , m_hardware { true } + , m_os { true } + , m_network { true } + , m_packages { true } + , m_ports { true } + , m_portsAll { true } + , m_processes { true } + , m_hotfixes { true } , m_stopping { true } - , m_notify { false } + , m_notify { true } {} -std::string Inventory::getCreateStatement() const +std::string Inventory::GetCreateStatement() const { std::string ret; @@ -1042,8 +380,8 @@ std::string Inventory::getCreateStatement() const return ret; } -void Inventory::init(const std::shared_ptr& spInfo, - const std::function reportDiffFunction, +void Inventory::Init(const std::shared_ptr& spInfo, + const std::function& reportDiffFunction, const std::string& dbPath, const std::string& normalizerConfigPath, const std::string& normalizerType) @@ -1056,13 +394,13 @@ void Inventory::init(const std::shared_ptr& spInfo, m_spDBSync = std::make_unique(HostType::AGENT, DbEngineType::SQLITE3, dbPath, - getCreateStatement(), + GetCreateStatement(), DbManagement::PERSISTENT); m_spNormalizer = std::make_unique(normalizerConfigPath, normalizerType); - syncLoop(lock); + SyncLoop(lock); } -void Inventory::destroy() +void Inventory::Destroy() { std::unique_lock lock{m_mutex}; m_stopping = true; @@ -1070,26 +408,26 @@ void Inventory::destroy() lock.unlock(); } -nlohmann::json Inventory::getHardwareData() +nlohmann::json Inventory::GetHardwareData() { nlohmann::json ret; ret[0] = m_spInfo->hardware(); - ret[0]["checksum"] = getItemChecksum(ret[0]); + ret[0]["checksum"] = GetItemChecksum(ret[0]); return ret; } -void Inventory::scanHardware() +void Inventory::ScanHardware() { if (m_hardware) { - log(LOG_DEBUG_VERBOSE, "Starting hardware scan"); - const auto& hwData{getHardwareData()}; - updateChanges(HW_TABLE, hwData); - log(LOG_DEBUG_VERBOSE, "Ending hardware scan"); + Log(LOG_DEBUG_VERBOSE, "Starting hardware scan"); + const auto& hwData{GetHardwareData()}; + UpdateChanges(HW_TABLE, hwData); + Log(LOG_DEBUG_VERBOSE, "Ending hardware scan"); } } -nlohmann::json Inventory::getOSData() +nlohmann::json Inventory::GetOSData() { nlohmann::json ret; ret[0] = m_spInfo->os(); @@ -1097,18 +435,18 @@ nlohmann::json Inventory::getOSData() return ret; } -void Inventory::scanOs() +void Inventory::ScanOs() { if (m_os) { - log(LOG_DEBUG_VERBOSE, "Starting os scan"); - const auto& osData{getOSData()}; - updateChanges(OS_TABLE, osData); - log(LOG_DEBUG_VERBOSE, "Ending os scan"); + Log(LOG_DEBUG_VERBOSE, "Starting os scan"); + const auto& osData{GetOSData()}; + UpdateChanges(OS_TABLE, osData); + Log(LOG_DEBUG_VERBOSE, "Ending os scan"); } } -nlohmann::json Inventory::getNetworkData() +nlohmann::json Inventory::GetNetworkData() { nlohmann::json ret; const auto& networks { m_spInfo->networks() }; @@ -1148,8 +486,8 @@ nlohmann::json Inventory::getNetworkData() ifaceTableData["rx_bytes"] = item.at("rx_bytes"); ifaceTableData["tx_dropped"] = item.at("tx_dropped"); ifaceTableData["rx_dropped"] = item.at("rx_dropped"); - ifaceTableData["checksum"] = getItemChecksum(ifaceTableData); - ifaceTableData["item_id"] = getItemId(ifaceTableData, NETIFACE_ITEM_ID_FIELDS); + ifaceTableData["checksum"] = GetItemChecksum(ifaceTableData); + ifaceTableData["item_id"] = GetItemId(ifaceTableData, NETIFACE_ITEM_ID_FIELDS); ifaceTableDataList.push_back(std::move(ifaceTableData)); if (item.find("IPv4") != item.end()) @@ -1161,8 +499,8 @@ nlohmann::json Inventory::getNetworkData() protoTableData["type"] = IP_TYPE.at(IPV4); protoTableData["dhcp"] = item.at("IPv4").begin()->at("dhcp"); protoTableData["metric"] = item.at("IPv4").begin()->at("metric"); - protoTableData["checksum"] = getItemChecksum(protoTableData); - protoTableData["item_id"] = getItemId(protoTableData, NETPROTO_ITEM_ID_FIELDS); + protoTableData["checksum"] = GetItemChecksum(protoTableData); + protoTableData["item_id"] = GetItemId(protoTableData, NETPROTO_ITEM_ID_FIELDS); protoTableDataList.push_back(std::move(protoTableData)); for (auto addressTableData : item.at("IPv4")) @@ -1170,8 +508,8 @@ nlohmann::json Inventory::getNetworkData() // "dbsync_network_address" table data to update and notify addressTableData["iface"] = item.at("name"); addressTableData["proto"] = IPV4; - addressTableData["checksum"] = getItemChecksum(addressTableData); - addressTableData["item_id"] = getItemId(addressTableData, NETADDRESS_ITEM_ID_FIELDS); + addressTableData["checksum"] = GetItemChecksum(addressTableData); + addressTableData["item_id"] = GetItemId(addressTableData, NETADDRESS_ITEM_ID_FIELDS); // Remove unwanted fields for dbsync_network_address table addressTableData.erase("dhcp"); addressTableData.erase("metric"); @@ -1189,8 +527,8 @@ nlohmann::json Inventory::getNetworkData() protoTableData["type"] = IP_TYPE.at(IPV6); protoTableData["dhcp"] = item.at("IPv6").begin()->at("dhcp"); protoTableData["metric"] = item.at("IPv6").begin()->at("metric"); - protoTableData["checksum"] = getItemChecksum(protoTableData); - protoTableData["item_id"] = getItemId(protoTableData, NETPROTO_ITEM_ID_FIELDS); + protoTableData["checksum"] = GetItemChecksum(protoTableData); + protoTableData["item_id"] = GetItemId(protoTableData, NETPROTO_ITEM_ID_FIELDS); protoTableDataList.push_back(std::move(protoTableData)); for (auto addressTableData : item.at("IPv6")) @@ -1198,8 +536,8 @@ nlohmann::json Inventory::getNetworkData() // "dbsync_network_address" table data to update and notify addressTableData["iface"] = item.at("name"); addressTableData["proto"] = IPV6; - addressTableData["checksum"] = getItemChecksum(addressTableData); - addressTableData["item_id"] = getItemId(addressTableData, NETADDRESS_ITEM_ID_FIELDS); + addressTableData["checksum"] = GetItemChecksum(addressTableData); + addressTableData["item_id"] = GetItemId(addressTableData, NETADDRESS_ITEM_ID_FIELDS); // Remove unwanted fields for dbsync_network_address table addressTableData.erase("dhcp"); addressTableData.erase("metric"); @@ -1218,12 +556,12 @@ nlohmann::json Inventory::getNetworkData() return ret; } -void Inventory::scanNetwork() +void Inventory::ScanNetwork() { if (m_network) { - log(LOG_DEBUG_VERBOSE, "Starting network scan"); - const auto networkData(getNetworkData()); + Log(LOG_DEBUG_VERBOSE, "Starting network scan"); + const auto networkData(GetNetworkData()); if (!networkData.is_null()) { @@ -1231,38 +569,38 @@ void Inventory::scanNetwork() if (itIface != networkData.end()) { - updateChanges(NET_IFACE_TABLE, itIface.value()); + UpdateChanges(NET_IFACE_TABLE, itIface.value()); } const auto itProtocol { networkData.find(NET_PROTOCOL_TABLE) }; if (itProtocol != networkData.end()) { - updateChanges(NET_PROTOCOL_TABLE, itProtocol.value()); + UpdateChanges(NET_PROTOCOL_TABLE, itProtocol.value()); } const auto itAddress { networkData.find(NET_ADDRESS_TABLE) }; if (itAddress != networkData.end()) { - updateChanges(NET_ADDRESS_TABLE, itAddress.value()); + UpdateChanges(NET_ADDRESS_TABLE, itAddress.value()); } } - log(LOG_DEBUG_VERBOSE, "Ending network scan"); + Log(LOG_DEBUG_VERBOSE, "Ending network scan"); } } -void Inventory::scanPackages() +void Inventory::ScanPackages() { if (m_packages) { - log(LOG_DEBUG_VERBOSE, "Starting packages scan"); + Log(LOG_DEBUG_VERBOSE, "Starting packages scan"); const auto callback { [this](ReturnTypeCallback result, const nlohmann::json & data) { - notifyChange(result, data, PACKAGES_TABLE); + NotifyChange(result, data, PACKAGES_TABLE); } }; DBSyncTxn txn @@ -1277,12 +615,12 @@ void Inventory::scanPackages() { nlohmann::json input; - rawData["checksum"] = getItemChecksum(rawData); - rawData["item_id"] = getItemId(rawData, PACKAGES_ITEM_ID_FIELDS); + rawData["checksum"] = GetItemChecksum(rawData); + rawData["item_id"] = GetItemId(rawData, PACKAGES_ITEM_ID_FIELDS); input["table"] = PACKAGES_TABLE; - m_spNormalizer->normalize("packages", rawData); - m_spNormalizer->removeExcluded("packages", rawData); + m_spNormalizer->Normalize("packages", rawData); + m_spNormalizer->RemoveExcluded("packages", rawData); if (!rawData.empty()) { @@ -1292,32 +630,32 @@ void Inventory::scanPackages() }); txn.getDeletedRows(callback); - log(LOG_DEBUG_VERBOSE, "Ending packages scan"); + Log(LOG_DEBUG_VERBOSE, "Ending packages scan"); } } -void Inventory::scanHotfixes() +void Inventory::ScanHotfixes() { if (m_hotfixes) { - log(LOG_DEBUG_VERBOSE, "Starting hotfixes scan"); + Log(LOG_DEBUG_VERBOSE, "Starting hotfixes scan"); auto hotfixes = m_spInfo->hotfixes(); if (!hotfixes.is_null()) { for (auto& hotfix : hotfixes) { - hotfix["checksum"] = getItemChecksum(hotfix); + hotfix["checksum"] = GetItemChecksum(hotfix); } - updateChanges(HOTFIXES_TABLE, hotfixes); + UpdateChanges(HOTFIXES_TABLE, hotfixes); } - log(LOG_DEBUG_VERBOSE, "Ending hotfixes scan"); + Log(LOG_DEBUG_VERBOSE, "Ending hotfixes scan"); } } -nlohmann::json Inventory::getPortsData() +nlohmann::json Inventory::GetPortsData() { nlohmann::json ret; constexpr auto PORT_LISTENING_STATE { "listening" }; @@ -1336,11 +674,11 @@ nlohmann::json Inventory::getPortsData() // All ports. if (m_portsAll) { - const auto& itemId { getItemId(item, PORTS_ITEM_ID_FIELDS) }; + const auto& itemId { GetItemId(item, PORTS_ITEM_ID_FIELDS) }; - if (!isElementDuplicated(ret, std::make_pair("item_id", itemId))) + if (!IsElementDuplicated(ret, std::make_pair("item_id", itemId))) { - item["checksum"] = getItemChecksum(item); + item["checksum"] = GetItemChecksum(item); item["item_id"] = itemId; ret.push_back(item); } @@ -1352,11 +690,11 @@ nlohmann::json Inventory::getPortsData() if (isListeningState) { - const auto& itemId { getItemId(item, PORTS_ITEM_ID_FIELDS) }; + const auto& itemId { GetItemId(item, PORTS_ITEM_ID_FIELDS) }; - if (!isElementDuplicated(ret, std::make_pair("item_id", itemId))) + if (!IsElementDuplicated(ret, std::make_pair("item_id", itemId))) { - item["checksum"] = getItemChecksum(item); + item["checksum"] = GetItemChecksum(item); item["item_id"] = itemId; ret.push_back(item); } @@ -1365,11 +703,11 @@ nlohmann::json Inventory::getPortsData() } else if (Utils::startsWith(protocol, UDP_PROTOCOL)) { - const auto& itemId { getItemId(item, PORTS_ITEM_ID_FIELDS) }; + const auto& itemId { GetItemId(item, PORTS_ITEM_ID_FIELDS) }; - if (!isElementDuplicated(ret, std::make_pair("item_id", itemId))) + if (!IsElementDuplicated(ret, std::make_pair("item_id", itemId))) { - item["checksum"] = getItemChecksum(item); + item["checksum"] = GetItemChecksum(item); item["item_id"] = itemId; ret.push_back(item); } @@ -1380,27 +718,27 @@ nlohmann::json Inventory::getPortsData() return ret; } -void Inventory::scanPorts() +void Inventory::ScanPorts() { if (m_ports) { - log(LOG_DEBUG_VERBOSE, "Starting ports scan"); - const auto& portsData { getPortsData() }; - updateChanges(PORTS_TABLE, portsData); - log(LOG_DEBUG_VERBOSE, "Ending ports scan"); + Log(LOG_DEBUG_VERBOSE, "Starting ports scan"); + const auto& portsData { GetPortsData() }; + UpdateChanges(PORTS_TABLE, portsData); + Log(LOG_DEBUG_VERBOSE, "Ending ports scan"); } } -void Inventory::scanProcesses() +void Inventory::ScanProcesses() { if (m_processes) { - log(LOG_DEBUG_VERBOSE, "Starting processes scan"); + Log(LOG_DEBUG_VERBOSE, "Starting processes scan"); const auto callback { [this](ReturnTypeCallback result, const nlohmann::json & data) { - notifyChange(result, data, PROCESSES_TABLE); + NotifyChange(result, data, PROCESSES_TABLE); } }; DBSyncTxn txn @@ -1415,7 +753,7 @@ void Inventory::scanProcesses() { nlohmann::json input; - rawData["checksum"] = getItemChecksum(rawData); + rawData["checksum"] = GetItemChecksum(rawData); input["table"] = PROCESSES_TABLE; input["data"] = nlohmann::json::array( { rawData } ); @@ -1424,33 +762,33 @@ void Inventory::scanProcesses() }); txn.getDeletedRows(callback); - log(LOG_DEBUG_VERBOSE, "Ending processes scan"); + Log(LOG_DEBUG_VERBOSE, "Ending processes scan"); } } -void Inventory::scan() +void Inventory::Scan() { - log(LOG_INFO, "Starting evaluation."); + Log(LOG_INFO, "Starting evaluation."); m_scanTime = Utils::getCurrentTimestamp(); - TRY_CATCH_TASK(scanHardware); - TRY_CATCH_TASK(scanOs); - TRY_CATCH_TASK(scanNetwork); - TRY_CATCH_TASK(scanPackages); - TRY_CATCH_TASK(scanHotfixes); - TRY_CATCH_TASK(scanPorts); - TRY_CATCH_TASK(scanProcesses); + TryCatchTask([&]() { ScanHardware(); }); + TryCatchTask([&]() { ScanOs(); }); + TryCatchTask([&]() { ScanNetwork(); }); + TryCatchTask([&]() { ScanPackages(); }); + TryCatchTask([&]() { ScanHotfixes(); }); + TryCatchTask([&]() { ScanPorts(); }); + TryCatchTask([&]() { ScanProcesses(); }); m_notify = true; - log(LOG_INFO, "Evaluation finished."); + Log(LOG_INFO, "Evaluation finished."); } -void Inventory::syncLoop(std::unique_lock& lock) +void Inventory::SyncLoop(std::unique_lock& lock) { - log(LOG_INFO, "Module started."); + Log(LOG_INFO, "Module started."); if (m_scanOnStart) { - scan(); + Scan(); } while (!m_cv.wait_for(lock, std::chrono::seconds{m_intervalValue}, [&]() @@ -1458,7 +796,7 @@ void Inventory::syncLoop(std::unique_lock& lock) return m_stopping; })) { - scan(); + Scan(); } m_spDBSync.reset(nullptr); } diff --git a/src/modules/inventory/src/inventoryNormalizer.cpp b/src/modules/inventory/src/inventoryNormalizer.cpp index 24bab994cd..4ba1640d27 100644 --- a/src/modules/inventory/src/inventoryNormalizer.cpp +++ b/src/modules/inventory/src/inventoryNormalizer.cpp @@ -1,13 +1,3 @@ -/* - * Wazuh Inventory - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #include #include #include @@ -15,12 +5,12 @@ InvNormalizer::InvNormalizer(const std::string& configFile, const std::string& target) - : m_typeExclusions{getTypeValues(configFile, target, "exclusions")} - , m_typeDictionary{getTypeValues(configFile, target, "dictionary")} + : m_typeExclusions{GetTypeValues(configFile, target, "exclusions")} + , m_typeDictionary{GetTypeValues(configFile, target, "dictionary")} { } -void InvNormalizer::removeExcluded(const std::string& type, +void InvNormalizer::RemoveExcluded(const std::string& type, nlohmann::json& data) const { const auto exclusionsIt{m_typeExclusions.find(type)}; @@ -57,16 +47,21 @@ void InvNormalizer::removeExcluded(const std::string& type, } } // LCOV_EXCL_START + catch (const std::exception& ex) + { + std::cout << "Exception caught in RemoveExcluded: " << ex.what() << '\n'; + } catch (...) - {} - + { + std::cout << "Unknown exception caught in RemoveExcluded." << '\n'; + } // LCOV_EXCL_STOP } } } -static void normalizeItem(const nlohmann::json& dictionary, +static void NormalizeItem(const nlohmann::json& dictionary, nlohmann::json& item) { for (const auto& dictItem : dictionary) @@ -117,7 +112,7 @@ static void normalizeItem(const nlohmann::json& dictionary, } } -void InvNormalizer::normalize(const std::string& type, +void InvNormalizer::Normalize(const std::string& type, nlohmann::json& data) const { const auto dictionaryIt{m_typeDictionary.find(type)}; @@ -128,17 +123,17 @@ void InvNormalizer::normalize(const std::string& type, { for (auto& item : data) { - normalizeItem(dictionaryIt->second, item); + NormalizeItem(dictionaryIt->second, item); } } else { - normalizeItem(dictionaryIt->second, data); + NormalizeItem(dictionaryIt->second, data); } } } -std::map InvNormalizer::getTypeValues(const std::string& configFile, +std::map InvNormalizer::GetTypeValues(const std::string& configFile, const std::string& target, const std::string& type) { @@ -166,8 +161,13 @@ std::map InvNormalizer::getTypeValues(const std::st } } } + catch (const std::exception& ex) + { + std::cout << "Exception caught in GetTypeValues: " << ex.what() << '\n'; + } catch (...) { + std::cout << "Unknown exception caught in GetTypeValues." << '\n'; } return ret; diff --git a/src/modules/inventory/tests/invNormalizer/CMakeLists.txt b/src/modules/inventory/tests/invNormalizer/CMakeLists.txt index c801aec34b..17c1a29a14 100644 --- a/src/modules/inventory/tests/invNormalizer/CMakeLists.txt +++ b/src/modules/inventory/tests/invNormalizer/CMakeLists.txt @@ -1,9 +1,10 @@ find_package(GTest CONFIG REQUIRED) add_executable(inv_normalizer_unit_test invNormalizer_test.cpp) -target_include_directories(inv_normalizer_unit_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../include) +configure_target(inv_normalizer_unit_test) +target_include_directories(inv_normalizer_unit_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../include) target_link_libraries(inv_normalizer_unit_test PRIVATE - inventory + Inventory GTest::gtest GTest::gtest_main GTest::gmock diff --git a/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp b/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp index 89223f4362..db32eabe74 100644 --- a/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp +++ b/src/modules/inventory/tests/invNormalizer/invNormalizer_test.cpp @@ -1,13 +1,3 @@ -/* - * Wazuh InventoryNormalizer - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #include "invNormalizer_test.h" #include "test_config.h" #include "test_input.h" @@ -63,7 +53,7 @@ TEST_F(InvNormalizerTest, excludeSiriAndiTunes) auto inputJson(nlohmann::json::parse(TEST_INPUT_DATA)); const auto size{inputJson.size()}; InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.removeExcluded("packages", inputJson); + normalizer.RemoveExcluded("packages", inputJson); EXPECT_EQ(size, inputJson.size() + 2); } @@ -78,7 +68,7 @@ TEST_F(InvNormalizerTest, excludeSingleItemNoMatch) })")}; nlohmann::json normalized(origJson); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.removeExcluded("packages", normalized); + normalizer.RemoveExcluded("packages", normalized); EXPECT_EQ(normalized, origJson); } @@ -92,7 +82,7 @@ TEST_F(InvNormalizerTest, excludeSingleItemMatch) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.removeExcluded("packages", inputJson); + normalizer.RemoveExcluded("packages", inputJson); EXPECT_TRUE(inputJson.empty()); } @@ -106,7 +96,7 @@ TEST_F(InvNormalizerTest, normalizeSingleMicosoft) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "Microsoft"); } @@ -121,7 +111,7 @@ TEST_F(InvNormalizerTest, normalizeSingleMcAfee1) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "McAfee"); EXPECT_EQ(inputJson["name"], "Antivirus"); @@ -137,7 +127,7 @@ TEST_F(InvNormalizerTest, normalizeSingleMcAfee2) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "McAfee"); EXPECT_EQ(inputJson["name"], "Endpoint Protection"); @@ -153,7 +143,7 @@ TEST_F(InvNormalizerTest, normalizeSingleTotalDefense1) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "TotalDefense"); EXPECT_EQ(inputJson["name"], "Anti-Virus"); @@ -169,7 +159,7 @@ TEST_F(InvNormalizerTest, normalizeSingleTotalDefense2) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "TotalDefense"); EXPECT_EQ(inputJson["name"], "OtherProduct"); @@ -185,7 +175,7 @@ TEST_F(InvNormalizerTest, normalizeSingleAVG1) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "AVG"); EXPECT_EQ(inputJson["name"], "Anti-Virus"); @@ -201,7 +191,7 @@ TEST_F(InvNormalizerTest, normalizeSingleAVG2) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["vendor"], "AVG"); EXPECT_EQ(inputJson["name"], "OtherProduct"); @@ -217,7 +207,7 @@ TEST_F(InvNormalizerTest, normalizeSingleKaspersky1) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["name"], "Kaspersky Antivirus"); } @@ -232,7 +222,7 @@ TEST_F(InvNormalizerTest, normalizeSingleKaspersky2) "version": "1.0" })")); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_FALSE(inputJson.empty()); EXPECT_EQ(inputJson["name"], "Kaspersky Internet Security"); } @@ -242,7 +232,7 @@ TEST_F(InvNormalizerTest, normalizeItemMatch) auto inputJson(nlohmann::json::parse(TEST_INPUT_DATA)); const auto origJson(inputJson); InvNormalizer normalizer{TEST_CONFIG_FILE_NAME, "macos"}; - normalizer.normalize("packages", inputJson); + normalizer.Normalize("packages", inputJson); EXPECT_EQ(inputJson.size(), origJson.size()); EXPECT_NE(inputJson, origJson); } diff --git a/src/modules/inventory/tests/invNormalizer/invNormalizer_test.h b/src/modules/inventory/tests/invNormalizer/invNormalizer_test.h index c9afab7f07..af41d20e4c 100644 --- a/src/modules/inventory/tests/invNormalizer/invNormalizer_test.h +++ b/src/modules/inventory/tests/invNormalizer/invNormalizer_test.h @@ -1,13 +1,3 @@ -/* - * Wazuh InventoryNormalizer - * Copyright (C) 2015, Wazuh Inc. - * January 12, 2021. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #pragma once #include "gtest/gtest.h" #include "gmock/gmock.h" diff --git a/src/modules/inventory/tests/inventoryImp/CMakeLists.txt b/src/modules/inventory/tests/inventoryImp/CMakeLists.txt index e9fdffdfaa..1f9fd6e84e 100644 --- a/src/modules/inventory/tests/inventoryImp/CMakeLists.txt +++ b/src/modules/inventory/tests/inventoryImp/CMakeLists.txt @@ -1,9 +1,10 @@ find_package(GTest CONFIG REQUIRED) add_executable(inventoryimp_unit_test inventoryImp_test.cpp) +configure_target(inventoryimp_unit_test) target_include_directories(inventoryimp_unit_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../include) target_link_libraries(inventoryimp_unit_test PRIVATE - inventory + Inventory GTest::gtest GTest::gtest_main GTest::gmock diff --git a/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp b/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp index d015bfff4d..52a29491ce 100644 --- a/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp +++ b/src/modules/inventory/tests/inventoryImp/inventoryImp_test.cpp @@ -1,19 +1,12 @@ -/* - * Wazuh InventoryImp - * Copyright (C) 2015, Wazuh Inc. - * November 9, 2020. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #include #include #include "inventoryImp_test.hpp" #include "inventory.hpp" constexpr auto INVENTORY_DB_PATH {"TEMP.db"}; +constexpr int SLEEP_DURATION_SECONDS = 10; + +void ReportFunction(const std::string& payload); void InventoryImpTest::SetUp() {}; @@ -22,14 +15,19 @@ void InventoryImpTest::TearDown() std::remove(INVENTORY_DB_PATH); }; -using ::testing::_; using ::testing::Return; class SysInfoWrapper: public ISysInfo { public: SysInfoWrapper() = default; - ~SysInfoWrapper() = default; + ~SysInfoWrapper() override = default; + + SysInfoWrapper(const SysInfoWrapper&) = delete; + SysInfoWrapper& operator=(const SysInfoWrapper&) = delete; + SysInfoWrapper(SysInfoWrapper&&) = default; + SysInfoWrapper& operator=(SysInfoWrapper&&) = default; + MOCK_METHOD(nlohmann::json, hardware, (), (override)); MOCK_METHOD(nlohmann::json, packages, (), (override)); MOCK_METHOD(void, packages, (std::function), (override)); @@ -46,26 +44,20 @@ class CallbackMock public: CallbackMock() = default; ~CallbackMock() = default; + + CallbackMock(const CallbackMock&) = delete; + CallbackMock& operator=(const CallbackMock&) = delete; + CallbackMock(CallbackMock&&) = default; + CallbackMock& operator=(CallbackMock&&) = default; + MOCK_METHOD(void, callbackMock, (const std::string&), ()); }; -void reportFunction(const std::string& /*payload*/) +void ReportFunction(const std::string& /*payload*/) { // std::cout << payload << std::endl; } -void logFunction(const modules_log_level_t /*level*/, const std::string& /*log*/) -{ - // static const std::map s_logStringMap - // { - // {LOG_ERROR, "ERROR"}, - // {LOG_INFO, "INFO"}, - // {LOG_DEBUG, "DEBUG"}, - // {LOG_DEBUG_VERBOSE, "DEBUG2"} - // }; - // std::cout << s_logStringMap.at(level) << ": " << log << std::endl; -} - TEST_F(InventoryImpTest, defaultCtor) { const auto spInfoWrapper{std::make_shared()}; @@ -77,14 +69,14 @@ TEST_F(InventoryImpTest, defaultCtor) R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -166,13 +158,13 @@ TEST_F(InventoryImpTest, defaultCtor) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult10)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult11)).Times(1); - Configuration config; - Inventory::instance().setup(config); + const configuration::ConfigurationParser configurationParser; + Inventory::Instance().Setup(configurationParser); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -181,7 +173,7 @@ TEST_F(InventoryImpTest, defaultCtor) }; std::this_thread::sleep_for(std::chrono::seconds(1)); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -201,27 +193,38 @@ TEST_F(InventoryImpTest, intervalSeconds) EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"},{"hotfix":"KB87654321"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(::testing::AtLeast(2)) .WillRepeatedly(testing::InvokeArgument<0>(nlohmann::json::parse( R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":431625,"ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(2)) .WillRepeatedly(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); - InventoryConfig invConfig; - invConfig.interval = 1; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 1 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper]() { - Inventory::instance().init(spInfoWrapper, - reportFunction, + Inventory::Instance().Init(spInfoWrapper, + ReportFunction, INVENTORY_DB_PATH, "", ""); @@ -229,8 +232,8 @@ TEST_F(InventoryImpTest, intervalSeconds) } }; - std::this_thread::sleep_for(std::chrono::seconds{10}); - Inventory::instance().stop(); + std::this_thread::sleep_for(std::chrono::seconds{SLEEP_DURATION_SECONDS}); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -243,23 +246,34 @@ TEST_F(InventoryImpTest, noScanOnStart) const auto spInfoWrapper{std::make_shared()}; EXPECT_CALL(*spInfoWrapper, hardware()).Times(0); EXPECT_CALL(*spInfoWrapper, os()).Times(0); - EXPECT_CALL(*spInfoWrapper, packages(_)).Times(0); + EXPECT_CALL(*spInfoWrapper, packages(testing::_)).Times(0); EXPECT_CALL(*spInfoWrapper, networks()).Times(0); - EXPECT_CALL(*spInfoWrapper, processes(_)).Times(0); + EXPECT_CALL(*spInfoWrapper, processes(testing::_)).Times(0); EXPECT_CALL(*spInfoWrapper, ports()).Times(0); EXPECT_CALL(*spInfoWrapper, hotfixes()).Times(0); - InventoryConfig invConfig; - invConfig.scanOnStart = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = false + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper]() { - Inventory::instance().init(spInfoWrapper, - reportFunction, + Inventory::Instance().Init(spInfoWrapper, + ReportFunction, INVENTORY_DB_PATH, "", ""); @@ -267,7 +281,7 @@ TEST_F(InventoryImpTest, noScanOnStart) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -285,14 +299,14 @@ TEST_F(InventoryImpTest, noHardware) R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -366,16 +380,27 @@ TEST_F(InventoryImpTest, noHardware) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult10)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult11)).Times(1); - InventoryConfig invConfig; - invConfig.hardware = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = false + os = true + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -384,7 +409,7 @@ TEST_F(InventoryImpTest, noHardware) }; std::this_thread::sleep_for(std::chrono::seconds(1)); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -403,14 +428,14 @@ TEST_F(InventoryImpTest, noOs) EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); EXPECT_CALL(*spInfoWrapper, os()).Times(0); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -484,16 +509,27 @@ TEST_F(InventoryImpTest, noOs) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult10)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult11)).Times(1); - InventoryConfig invConfig; - invConfig.os = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = false + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -502,7 +538,7 @@ TEST_F(InventoryImpTest, noOs) }; std::this_thread::sleep_for(std::chrono::seconds(2)); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -520,14 +556,14 @@ TEST_F(InventoryImpTest, noNetwork) EXPECT_CALL(*spInfoWrapper, networks()).Times(0); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -581,16 +617,27 @@ TEST_F(InventoryImpTest, noNetwork) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult9)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult10)).Times(1); - InventoryConfig invConfig; - invConfig.network = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = true + network = false + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -599,7 +646,7 @@ TEST_F(InventoryImpTest, noNetwork) }; std::this_thread::sleep_for(std::chrono::seconds(1)); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -618,11 +665,11 @@ TEST_F(InventoryImpTest, noPackages) R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)).Times(0); + EXPECT_CALL(*spInfoWrapper, packages(testing::_)).Times(0); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -696,16 +743,27 @@ TEST_F(InventoryImpTest, noPackages) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult10)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult11)).Times(1); - InventoryConfig invConfig; - invConfig.packages = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = true + network = true + packages = false + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -714,7 +772,7 @@ TEST_F(InventoryImpTest, noPackages) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -732,14 +790,14 @@ TEST_F(InventoryImpTest, noPorts) EXPECT_CALL(*spInfoWrapper, networks()).WillRepeatedly(Return(nlohmann::json::parse( R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).Times(0); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -813,17 +871,27 @@ TEST_F(InventoryImpTest, noPorts) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult18)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult20)).Times(1); - InventoryConfig invConfig; - invConfig.ports = false; - invConfig.interval = 5; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 5 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = false + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -832,7 +900,7 @@ TEST_F(InventoryImpTest, noPorts) }; std::this_thread::sleep_for(std::chrono::seconds(1)); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -851,14 +919,14 @@ TEST_F(InventoryImpTest, noPortsAll) R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"udp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"","tx_queue":0},{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -942,16 +1010,27 @@ TEST_F(InventoryImpTest, noPortsAll) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult11)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult12)).Times(1); - InventoryConfig invConfig; - invConfig.portsAll = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = false + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -960,7 +1039,7 @@ TEST_F(InventoryImpTest, noPortsAll) }; std::this_thread::sleep_for(std::chrono::seconds(1)); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -979,14 +1058,14 @@ TEST_F(InventoryImpTest, noProcesses) R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"}])"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)).Times(0); + EXPECT_CALL(*spInfoWrapper, processes(testing::_)).Times(0); CallbackMock wrapperDelta; std::function callbackDataDelta @@ -1057,16 +1136,27 @@ TEST_F(InventoryImpTest, noProcesses) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult10)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult11)).Times(1); - InventoryConfig invConfig; - invConfig.processes = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = true + processes = false + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -1075,7 +1165,7 @@ TEST_F(InventoryImpTest, noProcesses) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -1094,14 +1184,14 @@ TEST_F(InventoryImpTest, noHotfixes) R"({"iface":[{"address":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "mac":"d4:5d:64:51:07:5d", "gateway":"192.168.0.1|600","broadcast":"127.255.255.255", "name":"ens1", "mtu":1500, "name":"enp4s0", "adapter":" ", "type":"ethernet", "state":"up", "dhcp":"disabled","iface":"Loopback Pseudo-Interface 1","metric":"75","netmask":"255.0.0.0","proto":"IPv4","rx_bytes":0,"rx_dropped":0,"rx_errors":0,"rx_packets":0,"tx_bytes":0,"tx_dropped":0,"tx_errors":0,"tx_packets":0, "IPv4":[{"address":"192.168.153.1","broadcast":"192.168.153.255","dhcp":"unknown","metric":" ","netmask":"255.255.255.0"}], "IPv6":[{"address":"fe80::250:56ff:fec0:8","dhcp":"unknown","metric":" ","netmask":"ffff:ffff:ffff:ffff::"}]}]})"))); EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"architecture":"amd64","scan_time":"2020/12/28 21:49:50", "group":"x11","name":"xserver-xorg","priority":"optional","size":411,"source":"xorg","version":"1:7.7+19ubuntu14","format":"deb","location":" "})"_json)); EXPECT_CALL(*spInfoWrapper, hotfixes()).Times(0); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":"431625","ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); @@ -1175,16 +1265,27 @@ TEST_F(InventoryImpTest, noHotfixes) EXPECT_CALL(wrapperDelta, callbackMock(expectedResult9)).Times(1); EXPECT_CALL(wrapperDelta, callbackMock(expectedResult18)).Times(1); - InventoryConfig invConfig; - invConfig.hotfixes = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = false + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackDataDelta]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackDataDelta, INVENTORY_DB_PATH, "", @@ -1193,7 +1294,7 @@ TEST_F(InventoryImpTest, noHotfixes) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -1213,33 +1314,44 @@ TEST_F(InventoryImpTest, scanInvalidData) EXPECT_CALL(*spInfoWrapper, ports()).WillRepeatedly(Return(nlohmann::json::parse( R"([{"inode":0,"local_ip":"127.0.0.1","scan_time":"2020/12/28 21:49:50", "local_port":631,"pid":0,"process_name":"System Idle Process","protocol":"tcp","remote_ip":"0.0.0.0","remote_port":0,"rx_queue":0,"state":"listening","tx_queue":0}])"))); EXPECT_CALL(*spInfoWrapper, hotfixes()).WillRepeatedly(Return(R"([{"hotfix":"KB12345678"},{"hotfix":"KB87654321"}])"_json)); - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"name":"TEXT", "scan_time":"2020/12/28 21:49:50", "version":"TEXT", "vendor":"TEXT", "install_time":"TEXT", "location":"TEXT", "architecture":"TEXT", "groups":"TEXT", "description":"TEXT", "size":"TEXT", "priority":"TEXT", "multiarch":"TEXT", "source":"TEXT", "os_patch":"TEXT"})"_json)); - EXPECT_CALL(*spInfoWrapper, processes(_)) + EXPECT_CALL(*spInfoWrapper, processes(testing::_)) .Times(testing::AtLeast(1)) .WillOnce(::testing::InvokeArgument<0> (R"({"egroup":"root","euser":"root","fgroup":"root","name":"kworker/u256:2-","scan_time":"2020/12/28 21:49:50", "nice":0,"nlwp":1,"pgrp":0,"pid":431625,"ppid":2,"priority":20,"processor":1,"resident":0,"rgroup":"root","ruser":"root","session":0,"sgroup":"root","share":0,"size":0,"start_time":9302261,"state":"I","stime":3,"suser":"root","tgid":431625,"tty":0,"utime":0,"vm_size":0})"_json)); - InventoryConfig invConfig; - invConfig.interval = 60; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 60 + scan_on_start = true + hardware = true + os = true + network = true + packages = true + ports = true + ports_all = true + processes = true + hotfixes = true + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper]() { - Inventory::instance().init(spInfoWrapper, - reportFunction, + Inventory::Instance().Init(spInfoWrapper, + ReportFunction, INVENTORY_DB_PATH, "", ""); } }; std::this_thread::sleep_for(std::chrono::seconds{1}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -1355,21 +1467,27 @@ TEST_F(InventoryImpTest, portAllEnable) EXPECT_CALL(wrapper, callbackMock(expectedResult3)).Times(1); EXPECT_CALL(wrapper, callbackMock(expectedResult4)).Times(1); - InventoryConfig invConfig; - invConfig.hardware = false; - invConfig.os = false; - invConfig.network = false; - invConfig.packages = false; - invConfig.processes = false; - invConfig.hotfixes = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = false + os = false + network = false + packages = false + ports = true + ports_all = true + processes = false + hotfixes = false + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackData]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackData, INVENTORY_DB_PATH, "", @@ -1378,7 +1496,7 @@ TEST_F(InventoryImpTest, portAllEnable) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -1488,22 +1606,27 @@ TEST_F(InventoryImpTest, portAllDisable) EXPECT_CALL(wrapper, callbackMock(expectedResult2)).Times(1); EXPECT_CALL(wrapper, callbackMock(expectedResult3)).Times(1); - InventoryConfig invConfig; - invConfig.hardware = false; - invConfig.os = false; - invConfig.network = false; - invConfig.packages = false; - invConfig.portsAll = false; - invConfig.processes = false; - invConfig.hotfixes = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = false + os = false + network = false + packages = false + ports = true + ports_all = false + processes = false + hotfixes = false + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackData]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackData, INVENTORY_DB_PATH, "", @@ -1512,7 +1635,7 @@ TEST_F(InventoryImpTest, portAllDisable) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { @@ -1524,7 +1647,7 @@ TEST_F(InventoryImpTest, PackagesDuplicated) { const auto spInfoWrapper{std::make_shared()}; - EXPECT_CALL(*spInfoWrapper, packages(_)) + EXPECT_CALL(*spInfoWrapper, packages(testing::_)) .Times(::testing::AtLeast(1)) .WillOnce(::testing::DoAll( ::testing::InvokeArgument<0> @@ -1553,22 +1676,27 @@ TEST_F(InventoryImpTest, PackagesDuplicated) EXPECT_CALL(wrapper, callbackMock(expectedResult1)).Times(1); - InventoryConfig invConfig; - invConfig.hardware = false; - invConfig.os = false; - invConfig.network = false; - invConfig.ports = false; - invConfig.portsAll = false; - invConfig.processes = false; - invConfig.hotfixes = false; - Configuration config(invConfig); - Inventory::instance().setup(config); + std::string inventoryConfig = R"( + [inventory] + disabled = false + interval = 3600 + scan_on_start = true + hardware = false + os = false + network = false + packages = true + ports = false + ports_all = false + processes = false + hotfixes = false + )"; + Inventory::Instance().Setup(configuration::ConfigurationParser(inventoryConfig)); std::thread t { [&spInfoWrapper, &callbackData]() { - Inventory::instance().init(spInfoWrapper, + Inventory::Instance().Init(spInfoWrapper, callbackData, INVENTORY_DB_PATH, "", @@ -1577,7 +1705,7 @@ TEST_F(InventoryImpTest, PackagesDuplicated) }; std::this_thread::sleep_for(std::chrono::seconds{2}); - Inventory::instance().stop(); + Inventory::Instance().Stop(); if (t.joinable()) { diff --git a/src/modules/inventory/tests/inventoryImp/inventoryImp_test.hpp b/src/modules/inventory/tests/inventoryImp/inventoryImp_test.hpp index be64bcb6e8..fa54d782c6 100644 --- a/src/modules/inventory/tests/inventoryImp/inventoryImp_test.hpp +++ b/src/modules/inventory/tests/inventoryImp/inventoryImp_test.hpp @@ -1,13 +1,3 @@ -/* - * Wazuh InventoryImp - * Copyright (C) 2015, Wazuh Inc. - * November 9, 2020. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ #pragma once #include "gtest/gtest.h" #include "gmock/gmock.h" diff --git a/src/modules/inventory/testtool/CMakeLists.txt b/src/modules/inventory/testtool/CMakeLists.txt index f0d28c8dd2..2e61eabc55 100644 --- a/src/modules/inventory/testtool/CMakeLists.txt +++ b/src/modules/inventory/testtool/CMakeLists.txt @@ -28,7 +28,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") target_link_libraries(inventory_test_tool dbsync sysinfo - inventory + Inventory psapi iphlpapi crypto @@ -37,31 +37,12 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows") crypt32 -static-libstdc++ ) -elseif (CMAKE_SYSTEM_NAME STREQUAL "OpenBSD") - target_link_libraries(inventory_test_tool - dbsync - sysinfo - inventory - pthread) -elseif (CMAKE_SYSTEM_NAME STREQUAL "AIX") - target_link_libraries(inventory_test_tool - dbsync - sysinfo - inventory - dl) else() target_link_libraries(inventory_test_tool dbsync sysinfo - inventory + Inventory dl proc ) - - if(SOLARIS) - target_link_libraries(inventory_test_tool - nsl - socket - ) - endif(SOLARIS) endif(CMAKE_SYSTEM_NAME STREQUAL "Windows") diff --git a/src/modules/inventory/testtool/main.cpp b/src/modules/inventory/testtool/main.cpp index ce5f72719b..90aa098908 100644 --- a/src/modules/inventory/testtool/main.cpp +++ b/src/modules/inventory/testtool/main.cpp @@ -1,22 +1,10 @@ -/* - * Wazuh Inventory Test tool - * Copyright (C) 2015, Wazuh Inc. - * October 7, 2020. - * - * This program is free software; you can redistribute it - * and/or modify it under the terms of the GNU General Public - * License (version 2) as published by the FSF - Free Software - * Foundation. - */ - #include #include #include #include #include -#include "defs.h" -#include "configuration.hpp" -#include "inventory.hpp" +#include +#include constexpr int DEFAULT_SLEEP_TIME { 60 }; @@ -24,7 +12,7 @@ int main(int argc, const char* argv[]) { auto timedMainLoop { false }; auto sleepTime { DEFAULT_SLEEP_TIME }; - Configuration config{}; + const configuration::ConfigurationParser configurationParser; if (2 == argc) { @@ -39,7 +27,7 @@ int main(int argc, const char* argv[]) return -1; } - Inventory::instance().setup(config); + Inventory::Instance().Setup(configurationParser); try { @@ -56,11 +44,11 @@ int main(int argc, const char* argv[]) std::this_thread::sleep_for(std::chrono::seconds(sleepTime)); } - Inventory::instance().stop(); + Inventory::Instance().Stop(); } }; - Inventory::instance().start(); + Inventory::Instance().Start(); if (thread.joinable()) { diff --git a/src/modules/moduleWrapper.hpp b/src/modules/moduleWrapper.hpp new file mode 100644 index 0000000000..b39151628d --- /dev/null +++ b/src/modules/moduleWrapper.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include +#include +#include "configuration.hpp" + +using namespace std; + +struct ModuleWrapper { + function start; + function setup; + function stop; + function command; + function name; +}; diff --git a/src/modules/src/moduleManager.cpp b/src/modules/src/moduleManager.cpp index 251df01ad7..5699ff3caa 100644 --- a/src/modules/src/moduleManager.cpp +++ b/src/modules/src/moduleManager.cpp @@ -2,32 +2,32 @@ #include #include -shared_ptr ModuleManager::getModule(const string & name) { - auto it = modules.find(name); - if (it != modules.end()) { +shared_ptr ModuleManager::GetModule(const string & name) { + auto it = m_modules.find(name); + if (it != m_modules.end()) { return it->second; } return nullptr; } -void ModuleManager::start() { - for (const auto &[_, module] : modules) { - threads.emplace_back([module]() { module->start(); }); +void ModuleManager::Start() { + for (const auto &[_, module] : m_modules) { + m_threads.emplace_back([module]() { module->Start(); }); } } -void ModuleManager::setup(const Configuration & config) { - for (const auto &[_, module] : modules) { - module->setup(config); +void ModuleManager::Setup() { + for (const auto &[_, module] : m_modules) { + module->Setup(m_configurationParser); } } -void ModuleManager::stop() { - for (const auto &[_, module] : modules) { - module->stop(); +void ModuleManager::Stop() { + for (const auto &[_, module] : m_modules) { + module->Stop(); } - for (auto &thread : threads) { + for (auto &thread : m_threads) { if (thread.joinable()) { thread.join(); } diff --git a/src/modules/tests/CMakeLists.txt b/src/modules/tests/CMakeLists.txt index ac81648c33..2872043c3f 100644 --- a/src/modules/tests/CMakeLists.txt +++ b/src/modules/tests/CMakeLists.txt @@ -1,6 +1,7 @@ find_package(GTest CONFIG REQUIRED) add_executable(module_manager_test moduleManager_test.cpp) +configure_target(module_manager_test) target_include_directories(module_manager_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../include) target_link_libraries(module_manager_test PRIVATE ModuleManager diff --git a/src/modules/tests/moduleManager_test.cpp b/src/modules/tests/moduleManager_test.cpp index 51114e4f4a..1d2ef2fe4d 100644 --- a/src/modules/tests/moduleManager_test.cpp +++ b/src/modules/tests/moduleManager_test.cpp @@ -7,45 +7,53 @@ using namespace testing; // Mock classes to simulate modules class MockModule { public: - MOCK_METHOD(void, start, (), ()); - MOCK_METHOD(int, setup, (const Configuration&), ()); - MOCK_METHOD(void, stop, (), ()); - MOCK_METHOD(std::string, command, (const std::string&), ()); - MOCK_METHOD(std::string, name, (), (const)); - MOCK_METHOD(void, setMessageQueue, (const std::shared_ptr)); + MOCK_METHOD(void, Start, (), ()); + MOCK_METHOD(int, Setup, (const configuration::ConfigurationParser&), ()); + MOCK_METHOD(void, Stop, (), ()); + MOCK_METHOD(std::string, Command, (const std::string&), ()); + MOCK_METHOD(std::string, Name, (), (const)); + MOCK_METHOD(void, SetMessageQueue, (const std::shared_ptr)); }; class ModuleManagerTest : public ::testing::Test { protected: + std::shared_ptr messageQueue; + configuration::ConfigurationParser configurationParser; ModuleManager manager; MockModule mockModule; + ModuleManagerTest() + : messageQueue(std::make_shared()), + configurationParser(), + manager(messageQueue, configurationParser) + {} + void SetUp() override { // Set up default expectations for mock methods - ON_CALL(mockModule, name()).WillByDefault(Return("MockModule")); + ON_CALL(mockModule, Name()).WillByDefault(Return("MockModule")); } }; TEST_F(ModuleManagerTest, AddModule) { - EXPECT_CALL(mockModule, name()).Times(1); + EXPECT_CALL(mockModule, Name()).Times(1); - manager.addModule(mockModule); + manager.AddModule(mockModule); - auto moduleWrapper = manager.getModule("MockModule"); + auto moduleWrapper = manager.GetModule("MockModule"); EXPECT_NE(moduleWrapper, nullptr); } TEST_F(ModuleManagerTest, AddMultipleModules) { MockModule mockModule1, mockModule2; - EXPECT_CALL(mockModule1, name()).WillOnce(Return("MockModule1")); - EXPECT_CALL(mockModule2, name()).WillOnce(Return("MockModule2")); + EXPECT_CALL(mockModule1, Name()).WillOnce(Return("MockModule1")); + EXPECT_CALL(mockModule2, Name()).WillOnce(Return("MockModule2")); - manager.addModule(mockModule1); - manager.addModule(mockModule2); + manager.AddModule(mockModule1); + manager.AddModule(mockModule2); - auto moduleWrapper1 = manager.getModule("MockModule1"); - auto moduleWrapper2 = manager.getModule("MockModule2"); + auto moduleWrapper1 = manager.GetModule("MockModule1"); + auto moduleWrapper2 = manager.GetModule("MockModule2"); EXPECT_NE(moduleWrapper1, nullptr); EXPECT_NE(moduleWrapper2, nullptr); @@ -54,116 +62,113 @@ TEST_F(ModuleManagerTest, AddMultipleModules) { TEST_F(ModuleManagerTest, AddModuleDuplicateName) { MockModule mockModule1, mockModule2; - EXPECT_CALL(mockModule1, name()).WillOnce(Return("MockModule")); - EXPECT_CALL(mockModule2, name()).WillOnce(Return("MockModule")); + EXPECT_CALL(mockModule1, Name()).WillOnce(Return("MockModule")); + EXPECT_CALL(mockModule2, Name()).WillOnce(Return("MockModule")); - manager.addModule(mockModule1); + manager.AddModule(mockModule1); - EXPECT_THROW(manager.addModule(mockModule2), std::runtime_error); + EXPECT_THROW(manager.AddModule(mockModule2), std::runtime_error); } TEST_F(ModuleManagerTest, GetModuleNotFound) { - auto moduleWrapper = manager.getModule("NonExistentModule"); + auto moduleWrapper = manager.GetModule("NonExistentModule"); EXPECT_EQ(moduleWrapper, nullptr); } TEST_F(ModuleManagerTest, SetupModules) { - Configuration config; - EXPECT_CALL(mockModule, name()).Times(1); - EXPECT_CALL(mockModule, setup(_)).Times(1); + EXPECT_CALL(mockModule, Name()).Times(1); + EXPECT_CALL(mockModule, Setup(_)).Times(1); - manager.addModule(mockModule); - manager.setup(config); + manager.AddModule(mockModule); + manager.Setup(); } TEST_F(ModuleManagerTest, SetupMultipleModules) { MockModule mockModule1, mockModule2; - Configuration config; - EXPECT_CALL(mockModule1, name()).WillOnce(Return("MockModule1")); - EXPECT_CALL(mockModule2, name()).WillOnce(Return("MockModule2")); + EXPECT_CALL(mockModule1, Name()).WillOnce(Return("MockModule1")); + EXPECT_CALL(mockModule2, Name()).WillOnce(Return("MockModule2")); - EXPECT_CALL(mockModule1, setup(_)).Times(1); - EXPECT_CALL(mockModule2, setup(_)).Times(1); + EXPECT_CALL(mockModule1, Setup(_)).Times(1); + EXPECT_CALL(mockModule2, Setup(_)).Times(1); - manager.addModule(mockModule1); - manager.addModule(mockModule2); - manager.setup(config); + manager.AddModule(mockModule1); + manager.AddModule(mockModule2); + manager.Setup(); } TEST_F(ModuleManagerTest, SetupModuleThrowsException) { - Configuration config; - EXPECT_CALL(mockModule, name()).WillOnce(Return("MockModule")); - EXPECT_CALL(mockModule, setup(_)).WillOnce(Throw(std::runtime_error("Setup failed"))); + EXPECT_CALL(mockModule, Name()).WillOnce(Return("MockModule")); + EXPECT_CALL(mockModule, Setup(_)).WillOnce(Throw(std::runtime_error("Setup failed"))); - manager.addModule(mockModule); + manager.AddModule(mockModule); - EXPECT_THROW(manager.setup(config), std::runtime_error); + EXPECT_THROW(manager.Setup(), std::runtime_error); } TEST_F(ModuleManagerTest, StartModules) { - EXPECT_CALL(mockModule, name()).Times(2); - EXPECT_CALL(mockModule, start()).Times(1); - EXPECT_CALL(mockModule, stop()).Times(1); + EXPECT_CALL(mockModule, Name()).Times(2); + EXPECT_CALL(mockModule, Start()).Times(1); + EXPECT_CALL(mockModule, Stop()).Times(1); - manager.addModule(mockModule); - manager.start(); + manager.AddModule(mockModule); + manager.Start(); - auto moduleWrapper = manager.getModule("MockModule"); - EXPECT_EQ(moduleWrapper->name(), "MockModule"); + auto moduleWrapper = manager.GetModule("MockModule"); + EXPECT_EQ(moduleWrapper->Name(), "MockModule"); - manager.stop(); + manager.Stop(); } TEST_F(ModuleManagerTest, StartMultipleModules) { MockModule mockModule1, mockModule2; - EXPECT_CALL(mockModule1, name()).Times(2).WillRepeatedly(Return("MockModule1")); - EXPECT_CALL(mockModule2, name()).Times(2).WillRepeatedly(Return("MockModule2")); + EXPECT_CALL(mockModule1, Name()).Times(2).WillRepeatedly(Return("MockModule1")); + EXPECT_CALL(mockModule2, Name()).Times(2).WillRepeatedly(Return("MockModule2")); - EXPECT_CALL(mockModule1, start()).Times(1); - EXPECT_CALL(mockModule2, start()).Times(1); - EXPECT_CALL(mockModule1, stop()).Times(1); - EXPECT_CALL(mockModule2, stop()).Times(1); + EXPECT_CALL(mockModule1, Start()).Times(1); + EXPECT_CALL(mockModule2, Start()).Times(1); + EXPECT_CALL(mockModule1, Stop()).Times(1); + EXPECT_CALL(mockModule2, Stop()).Times(1); - manager.addModule(mockModule1); - manager.addModule(mockModule2); + manager.AddModule(mockModule1); + manager.AddModule(mockModule2); - manager.start(); + manager.Start(); - auto moduleWrapper1 = manager.getModule("MockModule1"); - auto moduleWrapper2 = manager.getModule("MockModule2"); + auto moduleWrapper1 = manager.GetModule("MockModule1"); + auto moduleWrapper2 = manager.GetModule("MockModule2"); EXPECT_NE(moduleWrapper1, nullptr); EXPECT_NE(moduleWrapper2, nullptr); - EXPECT_EQ(moduleWrapper1->name(), "MockModule1"); - EXPECT_EQ(moduleWrapper2->name(), "MockModule2"); + EXPECT_EQ(moduleWrapper1->Name(), "MockModule1"); + EXPECT_EQ(moduleWrapper2->Name(), "MockModule2"); - manager.stop(); + manager.Stop(); } TEST_F(ModuleManagerTest, StopModules) { - EXPECT_CALL(mockModule, name()).Times(1); - EXPECT_CALL(mockModule, stop()).Times(1); + EXPECT_CALL(mockModule, Name()).Times(1); + EXPECT_CALL(mockModule, Stop()).Times(1); - manager.addModule(mockModule); - manager.stop(); + manager.AddModule(mockModule); + manager.Stop(); } TEST_F(ModuleManagerTest, StopMultipleModules) { MockModule mockModule1, mockModule2; - EXPECT_CALL(mockModule1, name()).WillOnce(Return("MockModule1")); - EXPECT_CALL(mockModule2, name()).WillOnce(Return("MockModule2")); + EXPECT_CALL(mockModule1, Name()).WillOnce(Return("MockModule1")); + EXPECT_CALL(mockModule2, Name()).WillOnce(Return("MockModule2")); - EXPECT_CALL(mockModule1, stop()).Times(1); - EXPECT_CALL(mockModule2, stop()).Times(1); + EXPECT_CALL(mockModule1, Stop()).Times(1); + EXPECT_CALL(mockModule2, Stop()).Times(1); - manager.addModule(mockModule1); - manager.addModule(mockModule2); - manager.stop(); + manager.AddModule(mockModule1); + manager.AddModule(mockModule2); + manager.Stop(); } int main(int argc, char** argv) diff --git a/src/vcpkg b/src/vcpkg index 91f002cae2..f7423ee180 160000 --- a/src/vcpkg +++ b/src/vcpkg @@ -1 +1 @@ -Subproject commit 91f002cae2281636da5155efc5a11d67efa72415 +Subproject commit f7423ee180c4b7f40d43402c2feb3859161ef625 diff --git a/src/vcpkg.json b/src/vcpkg.json index 7cf9b86139..8665ac48f8 100644 --- a/src/vcpkg.json +++ b/src/vcpkg.json @@ -63,7 +63,7 @@ "packages": [ "toml11"] } ], - "overlay-ports": [ + "overlay-ports": [ "./ports-overlay/procps", "./ports-overlay/libdb", "./ports-overlay/librpm"