From 1c529746ff07312e30e76fd933c628c658e3c77d Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Tue, 23 Aug 2022 14:21:12 +0300 Subject: [PATCH 01/16] Add subscriptions (to replace notifiers). --- include/stg/subscriptions.h | 84 +++++++++++++ tests/CMakeLists.txt | 4 + tests/test_subscriptions.cpp | 223 +++++++++++++++++++++++++++++++++++ 3 files changed, 311 insertions(+) create mode 100644 include/stg/subscriptions.h create mode 100644 tests/test_subscriptions.cpp diff --git a/include/stg/subscriptions.h b/include/stg/subscriptions.h new file mode 100644 index 00000000..1486e62d --- /dev/null +++ b/include/stg/subscriptions.h @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include + +namespace STG +{ + +template +class Subscriptions +{ + public: + using Callback = std::function; + using Callbacks = std::list; + + class Connection + { + public: + Connection(Subscriptions& s, typename Callbacks::iterator i) noexcept + : m_subscriptions(s), m_iterator(i), m_connected(true) + {} + ~Connection() + { + disconnect(); + } + + void disconnect() noexcept + { + if (!m_connected) + return; + m_subscriptions.remove(m_iterator); + m_connected = false; + } + private: + Subscriptions& m_subscriptions; + typename Callbacks::iterator m_iterator; + bool m_connected; + }; + + template + Connection add(F&& f) + { + std::lock_guard lock(m_mutex); + return Connection(*this, m_callbacks.insert(m_callbacks.end(), Callback(std::forward(f)))); + } + + template + Connection add(C& c, void (C::*m)(T2s...)) + { + return add([&c, m](Ts&&... values){ (c.*m)(std::forward(values)...); }); + } + + void remove(typename Callbacks::iterator i) + { + std::lock_guard lock(m_mutex); + m_callbacks.erase(i); + } + + void notify(Ts&&... values) + { + std::lock_guard lock(m_mutex); + for (auto& cb : m_callbacks) + cb(values...); + } + + bool empty() const noexcept + { + std::lock_guard lock(m_mutex); + return m_callbacks.empty(); + } + + size_t size() const noexcept + { + std::lock_guard lock(m_mutex); + return m_callbacks.size(); + } + + private: + mutable std::mutex m_mutex; + Callbacks m_callbacks; +}; + +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 250f5e06..a552cfbe 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -49,3 +49,7 @@ add_executable ( test_filter_params_log test_filter_params_log.cpp ../projects/s target_link_libraries ( test_filter_params_log logger scriptexecuter common Boost::unit_test_framework Threads::Threads ) target_include_directories ( test_filter_params_log PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) add_test ( filter_params_log test_filter_params_log ) + +add_executable ( test_subscriptions test_subscriptions.cpp ) +target_link_libraries ( test_subscriptions Boost::unit_test_framework ) +add_test ( subscriptions test_subscriptions ) diff --git a/tests/test_subscriptions.cpp b/tests/test_subscriptions.cpp new file mode 100644 index 00000000..ebc3c920 --- /dev/null +++ b/tests/test_subscriptions.cpp @@ -0,0 +1,223 @@ +#define BOOST_TEST_MODULE STGSubscriptions + +#include "stg/subscriptions.h" + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop + +namespace +{ + +struct Receiver +{ + Receiver() noexcept + : countR0(0), + countR1(0), + valueR1(0), + countR2(0), + value1R2(0) + {} + + void r0() { ++countR0; } + void r1(uint8_t v) { ++countR1; valueR1 = v; } + void r2(uint8_t v1, const std::string& v2) { ++countR2; value1R2 = v1; value2R2 = v2; } + + size_t countR0; + size_t countR1; + uint8_t valueR1; + size_t countR2; + uint8_t value1R2; + std::string value2R2; +}; + +} + +BOOST_AUTO_TEST_SUITE(Subscriptions) + +BOOST_AUTO_TEST_CASE(Construction) +{ + STG::Subscriptions<> nullary; + BOOST_CHECK(nullary.empty()); + BOOST_CHECK_EQUAL(nullary.size(), 0); + + STG::Subscriptions unary; + BOOST_CHECK(unary.empty()); + BOOST_CHECK_EQUAL(unary.size(), 0); + + STG::Subscriptions binary; + BOOST_CHECK(binary.empty()); + BOOST_CHECK_EQUAL(binary.size(), 0); +} + +BOOST_AUTO_TEST_CASE(AddingAndRemoving) +{ + Receiver r; + STG::Subscriptions<> nullary; + { + auto c1 = nullary.add(r, &Receiver::r0); + auto c2 = nullary.add([&r](){ r.r0(); }); + + BOOST_CHECK(!nullary.empty()); + BOOST_CHECK_EQUAL(nullary.size(), 2); + + c1.disconnect(); + + BOOST_CHECK(!nullary.empty()); + BOOST_CHECK_EQUAL(nullary.size(), 1); + } + BOOST_CHECK(nullary.empty()); + BOOST_CHECK_EQUAL(nullary.size(), 0); + + STG::Subscriptions unary; + { + auto c1 = unary.add(r, &Receiver::r1); + auto c2 = unary.add([&r](const auto& v){ r.r1(v); }); + + BOOST_CHECK(!unary.empty()); + BOOST_CHECK_EQUAL(unary.size(), 2); + + c1.disconnect(); + + BOOST_CHECK(!unary.empty()); + BOOST_CHECK_EQUAL(unary.size(), 1); + } + BOOST_CHECK(unary.empty()); + BOOST_CHECK_EQUAL(unary.size(), 0); + + STG::Subscriptions binary; + { + auto c1 = binary.add(r, &Receiver::r2); + auto c2 = binary.add([&r](const auto& v1, const auto& v2){ r.r2(v1, v2); }); + + BOOST_CHECK(!binary.empty()); + BOOST_CHECK_EQUAL(binary.size(), 2); + + c1.disconnect(); + + BOOST_CHECK(!binary.empty()); + BOOST_CHECK_EQUAL(binary.size(), 1); + } + BOOST_CHECK(binary.empty()); + BOOST_CHECK_EQUAL(binary.size(), 0); +} + +BOOST_AUTO_TEST_CASE(Notification) +{ + Receiver r; + + BOOST_CHECK_EQUAL(r.countR0, 0); + BOOST_CHECK_EQUAL(r.countR1, 0); + BOOST_CHECK_EQUAL(r.valueR1, 0); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + + STG::Subscriptions<> nullary; + { + auto c1 = nullary.add(r, &Receiver::r0); + auto c2 = nullary.add([&r](){ r.r0(); }); + + nullary.notify(); + + BOOST_CHECK_EQUAL(r.countR0, 2); + BOOST_CHECK_EQUAL(r.countR1, 0); + BOOST_CHECK_EQUAL(r.valueR1, 0); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + + c1.disconnect(); + nullary.notify(); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 0); + BOOST_CHECK_EQUAL(r.valueR1, 0); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + } + + nullary.notify(); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 0); + BOOST_CHECK_EQUAL(r.valueR1, 0); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + + STG::Subscriptions unary; + { + auto c1 = unary.add(r, &Receiver::r1); + auto c2 = unary.add([&r](const auto& v){ r.r1(v); }); + + unary.notify(42); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 2); + BOOST_CHECK_EQUAL(r.valueR1, 42); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + + c1.disconnect(); + unary.notify(13); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 3); + BOOST_CHECK_EQUAL(r.valueR1, 13); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + } + + unary.notify(7); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 3); + BOOST_CHECK_EQUAL(r.valueR1, 13); + BOOST_CHECK_EQUAL(r.countR2, 0); + BOOST_CHECK_EQUAL(r.value1R2, 0); + BOOST_CHECK_EQUAL(r.value2R2, ""); + + STG::Subscriptions binary; + { + auto c1 = binary.add(r, &Receiver::r2); + auto c2 = binary.add([&r](const auto& v1, const auto& v2){ r.r2(v1, v2); }); + + binary.notify(42, "Douglas"); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 3); + BOOST_CHECK_EQUAL(r.valueR1, 13); + BOOST_CHECK_EQUAL(r.countR2, 2); + BOOST_CHECK_EQUAL(r.value1R2, 42); + BOOST_CHECK_EQUAL(r.value2R2, "Douglas"); + + c1.disconnect(); + binary.notify(21, "Adams"); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 3); + BOOST_CHECK_EQUAL(r.valueR1, 13); + BOOST_CHECK_EQUAL(r.countR2, 3); + BOOST_CHECK_EQUAL(r.value1R2, 21); + BOOST_CHECK_EQUAL(r.value2R2, "Adams"); + } + + binary.notify(13, "Devil's Dozen"); + + BOOST_CHECK_EQUAL(r.countR0, 3); + BOOST_CHECK_EQUAL(r.countR1, 3); + BOOST_CHECK_EQUAL(r.valueR1, 13); + BOOST_CHECK_EQUAL(r.countR2, 3); + BOOST_CHECK_EQUAL(r.value1R2, 21); + BOOST_CHECK_EQUAL(r.value2R2, "Adams"); +} + +BOOST_AUTO_TEST_SUITE_END() -- 2.44.2 From 646c8fd6c0112573ba2aae7f165f5d48e849831e Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Tue, 23 Aug 2022 16:55:28 +0300 Subject: [PATCH 02/16] Add async pool (to replace EVENT_LOOP). --- projects/stargazer/CMakeLists.txt | 1 + projects/stargazer/async_pool.cpp | 42 +++++++++++++++++++++ projects/stargazer/async_pool.h | 62 +++++++++++++++++++++++++++++++ projects/stargazer/main.cpp | 3 ++ tests/CMakeLists.txt | 5 +++ tests/test_async_pool.cpp | 54 +++++++++++++++++++++++++++ 6 files changed, 167 insertions(+) create mode 100644 projects/stargazer/async_pool.cpp create mode 100644 projects/stargazer/async_pool.h create mode 100644 tests/test_async_pool.cpp diff --git a/projects/stargazer/CMakeLists.txt b/projects/stargazer/CMakeLists.txt index 005e72df..6fbfbbc4 100644 --- a/projects/stargazer/CMakeLists.txt +++ b/projects/stargazer/CMakeLists.txt @@ -7,6 +7,7 @@ set ( CPP_FILES main.cpp user_impl.cpp tariff_impl.cpp eventloop.cpp + async_pool.cpp pidfile.cpp plugin_runner.cpp plugin_mgr.cpp diff --git a/projects/stargazer/async_pool.cpp b/projects/stargazer/async_pool.cpp new file mode 100644 index 00000000..1d8fec0c --- /dev/null +++ b/projects/stargazer/async_pool.cpp @@ -0,0 +1,42 @@ +#include "async_pool.h" + +using STG::AsyncPool; + +AsyncPool& STG::AsyncPoolST::instance() +{ + static AsyncPool pool; + return pool; +} + +void AsyncPool::start() +{ + if (m_thread.joinable()) + return; + m_thread = std::jthread([this](auto token){ run(std::move(token)); }); +} + +void AsyncPool::stop() +{ + if (!m_thread.joinable()) + return; + m_thread.request_stop(); + m_cond.notify_all(); +} + +void AsyncPool::run(std::stop_token token) noexcept +{ + while (true) + { + Queue tasks; + { + std::unique_lock lock(m_mutex); + m_cond.wait(lock, [this, &token](){ return !m_tasks.empty() || token.stop_requested(); }); + if (token.stop_requested()) + return; + if (!m_tasks.empty()) + tasks.swap(m_tasks); + } + for (const auto& t : tasks) + t(); + } +} diff --git a/projects/stargazer/async_pool.h b/projects/stargazer/async_pool.h new file mode 100644 index 00000000..cf82db0d --- /dev/null +++ b/projects/stargazer/async_pool.h @@ -0,0 +1,62 @@ +#pragma once + +#include +#include +#include +#include +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wshadow" +#include +#pragma GCC diagnostic pop +#include + +namespace STG +{ + +class AsyncPool +{ + public: + AsyncPool() = default; + + void start(); + void stop(); + + template + void enqueue(F&& f) + { + { + std::lock_guard lock(m_mutex); + m_tasks.emplace_back(std::forward(f)); + } + m_cond.notify_all(); + } + + private: + using Task = std::function; + using Queue = std::deque; + + std::mutex m_mutex; + std::condition_variable m_cond; + Queue m_tasks; + std::jthread m_thread; + + void run(std::stop_token token) noexcept; +}; + +namespace AsyncPoolST +{ + +AsyncPool& instance(); + +inline +void start() { instance().start(); } +inline +void stop() { instance().stop(); } + +template +inline +void enqueue(F&& f) { instance().enqueue(std::forward(f)); } + +}; + +} diff --git a/projects/stargazer/main.cpp b/projects/stargazer/main.cpp index bcf7af77..3ee229c2 100644 --- a/projects/stargazer/main.cpp +++ b/projects/stargazer/main.cpp @@ -29,6 +29,7 @@ #include "traffcounter_impl.h" #include "settings_impl.h" #include "pidfile.h" +#include "async_pool.h" #include "eventloop.h" #include "stg_timer.h" @@ -283,6 +284,7 @@ int main(int argc, char* argv[]) } auto& loop = EVENT_LOOP::instance(); + STG::AsyncPoolST::start(); StoreLoader storeLoader(settings); if (storeLoader.load()) @@ -377,6 +379,7 @@ int main(int argc, char* argv[]) manager.stop(); + STG::AsyncPoolST::stop(); if (loop.Stop()) WriteServLog("Event loop not stopped."); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a552cfbe..8fc662c6 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -53,3 +53,8 @@ add_test ( filter_params_log test_filter_params_log ) add_executable ( test_subscriptions test_subscriptions.cpp ) target_link_libraries ( test_subscriptions Boost::unit_test_framework ) add_test ( subscriptions test_subscriptions ) + +add_executable ( test_async_pool test_async_pool.cpp ../projects/stargazer/async_pool.cpp ) +target_include_directories ( test_async_pool PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer ) +target_link_libraries ( test_async_pool Boost::unit_test_framework Threads::Threads ) +add_test ( async_pool test_async_pool ) diff --git a/tests/test_async_pool.cpp b/tests/test_async_pool.cpp new file mode 100644 index 00000000..7e2e0cfe --- /dev/null +++ b/tests/test_async_pool.cpp @@ -0,0 +1,54 @@ +#define BOOST_TEST_MODULE STGSubscriptions + +#include "async_pool.h" + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wparentheses" +#include +#pragma GCC diagnostic pop + +namespace AsyncPoolST = STG::AsyncPoolST; + +namespace +{ + +size_t counter = 0; + +} + +BOOST_AUTO_TEST_SUITE() + +BOOST_AUTO_TEST_CASE(BeforeStart) +{ + BOOST_CHECK_EQUAL(counter, 0); + AsyncPoolST::enqueue([](){ ++counter; }); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + BOOST_CHECK_EQUAL(counter, 0); +} + +BOOST_AUTO_TEST_CASE(AfterStart) +{ + BOOST_CHECK_EQUAL(counter, 0); + AsyncPoolST::start(); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + BOOST_CHECK_EQUAL(counter, 1); + AsyncPoolST::enqueue([](){ ++counter; }); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + BOOST_CHECK_EQUAL(counter, 2); +} + +BOOST_AUTO_TEST_CASE(AfterStop) +{ + BOOST_CHECK_EQUAL(counter, 2); + AsyncPoolST::stop(); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + BOOST_CHECK_EQUAL(counter, 2); + AsyncPoolST::enqueue([](){ ++counter; }); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + BOOST_CHECK_EQUAL(counter, 2); +} + +BOOST_AUTO_TEST_SUITE_END() -- 2.44.2 From c59911ca3cd38cf4ab36d2cc62686f97395899f9 Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Tue, 23 Aug 2022 17:11:56 +0300 Subject: [PATCH 03/16] Use async pool instead of EVENT_LOOP. --- projects/stargazer/CMakeLists.txt | 1 - projects/stargazer/actions.h | 96 ------------------- projects/stargazer/eventloop.cpp | 59 ------------ projects/stargazer/eventloop.h | 45 --------- projects/stargazer/main.cpp | 11 --- .../stargazer/plugins/authorization/ao/ao.cpp | 2 - projects/stargazer/traffcounter_impl.cpp | 36 +++++++ projects/stargazer/traffcounter_impl.h | 34 ------- projects/stargazer/users_impl.h | 2 - 9 files changed, 36 insertions(+), 250 deletions(-) delete mode 100644 projects/stargazer/actions.h delete mode 100644 projects/stargazer/eventloop.cpp delete mode 100644 projects/stargazer/eventloop.h diff --git a/projects/stargazer/CMakeLists.txt b/projects/stargazer/CMakeLists.txt index 6fbfbbc4..751bfc03 100644 --- a/projects/stargazer/CMakeLists.txt +++ b/projects/stargazer/CMakeLists.txt @@ -6,7 +6,6 @@ set ( CPP_FILES main.cpp services_impl.cpp user_impl.cpp tariff_impl.cpp - eventloop.cpp async_pool.cpp pidfile.cpp plugin_runner.cpp diff --git a/projects/stargazer/actions.h b/projects/stargazer/actions.h deleted file mode 100644 index 360a56e1..00000000 --- a/projects/stargazer/actions.h +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -// Usage: -// -// ACTIONS_LIST actionsList; -// CLASS myClass; -// DATA1 myData1; -// DATA2 myData2; -// -// actionsList.Enqueue(myClass, &CLASS::myMethod1, myData1); -// actionsList.Enqueue(myClass, &CLASS::myMethod2, myData2); -// -// actionsList.InvokeAll(); - -#include -#include -#include - -// Generalized actor type - a method of some class with one argument -template -struct ACTOR -{ - using TYPE = void (ACTIVE_CLASS::*)(DATA_TYPE); -}; - -// Abstract base action class for polymorphic action invocation -class BASE_ACTION -{ -public: - virtual ~BASE_ACTION() {} - virtual void Invoke() = 0; -}; - -// Concrete generalized action type - an actor with it's data and owner -template -class ACTION : public BASE_ACTION -{ -public: - ACTION(ACTIVE_CLASS & ac, - typename ACTOR::TYPE a, - DATA_TYPE d) - : activeClass(ac), actor(a), data(d) {} - void Invoke() override - { - (activeClass.*actor)(data); - } -private: - ACTION(const ACTION & rvalue); - ACTION & operator=(const ACTION & rvalue); - - ACTIVE_CLASS & activeClass; - typename ACTOR::TYPE actor; - DATA_TYPE data; -}; - -// A list of an actions -// All methods are thread-safe -class ACTIONS_LIST -{ -public: - ~ACTIONS_LIST() - { - std::lock_guard lock(m_mutex); - for (auto action : m_list) - delete action; - } - - auto begin() { std::lock_guard lock(m_mutex); return m_list.begin(); } - auto end() { std::lock_guard lock(m_mutex); return m_list.end(); } - auto begin() const { std::lock_guard lock(m_mutex); return m_list.begin(); } - auto end() const { std::lock_guard lock(m_mutex); return m_list.end(); } - - bool empty() const { std::lock_guard lock(m_mutex); return m_list.empty(); } - size_t size() const { std::lock_guard lock(m_mutex); return m_list.size(); } - void swap(ACTIONS_LIST & rhs) { std::lock_guard lock(m_mutex); m_list.swap(rhs.m_list); } - - // Add an action to list - template - void Enqueue(ACTIVE_CLASS & ac, - typename ACTOR::TYPE a, - DATA_TYPE d) - { - std::lock_guard lock(m_mutex); - m_list.push_back(new ACTION(ac, a, d)); - } - // Invoke all actions in the list - void InvokeAll() - { - std::lock_guard lock(m_mutex); - for (auto action : m_list) - action->Invoke(); - } -private: - mutable std::mutex m_mutex; - std::vector m_list; -}; diff --git a/projects/stargazer/eventloop.cpp b/projects/stargazer/eventloop.cpp deleted file mode 100644 index ea175c41..00000000 --- a/projects/stargazer/eventloop.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "stg/common.h" -#include "eventloop.h" - -#include -#include -#include - -EVENT_LOOP& EVENT_LOOP::instance() -{ - static EVENT_LOOP el; - return el; -} - -bool EVENT_LOOP::Start() -{ -m_thread = std::jthread([this](auto token){ Run(std::move(token)); }); -return false; -} - -bool EVENT_LOOP::Stop() -{ -m_thread.request_stop(); -// Wake up thread -m_cond.notify_all(); -m_thread.join(); -return false; -} - -void EVENT_LOOP::Run(std::stop_token token) -{ -sigset_t signalSet; -sigfillset(&signalSet); -pthread_sigmask(SIG_BLOCK, &signalSet, NULL); - -printfd(__FILE__, "EVENT_LOOP::Runner - Before start\n"); -while (!token.stop_requested()) - { - // Create new empty actions list - ACTIONS_LIST local; - { - std::unique_lock lock(m_mutex); - // Check for any actions... - // ... and sleep until new actions added - printfd(__FILE__, "EVENT_LOOP::Runner - Sleeping until new actions arrived\n"); - m_cond.wait(lock); - // Check for running after wake up - if (token.stop_requested()) - break; // Don't process any actions if stopping - if (!m_list.empty()) - local.swap(m_list); - } - // Fast swap with current - m_list.swap(local); - // Invoke all current actions - printfd(__FILE__, "EVENT_LOOP::Runner - Invoke %d actions\n", local.size()); - local.InvokeAll(); - } -printfd(__FILE__, "EVENT_LOOP::Runner - Before stop\n"); -} diff --git a/projects/stargazer/eventloop.h b/projects/stargazer/eventloop.h deleted file mode 100644 index 0b2b8397..00000000 --- a/projects/stargazer/eventloop.h +++ /dev/null @@ -1,45 +0,0 @@ -#ifndef __EVENT_LOOP_H__ -#define __EVENT_LOOP_H__ - -#include "actions.h" - -#include -#include -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wshadow" -#include -#pragma GCC diagnostic pop - -class EVENT_LOOP -{ - public: - static EVENT_LOOP& instance(); - - bool Start(); - bool Stop(); - - template - void Enqueue(ACTIVE_CLASS & ac, - typename ACTOR::TYPE a, - DATA_TYPE d) - { - std::lock_guard lock(m_mutex); - // Add new action - m_list.Enqueue(ac, a, d); - // Signal about new action - m_cond.notify_all(); - } - - private: - std::jthread m_thread; - std::mutex m_mutex; - std::condition_variable m_cond; - - ACTIONS_LIST m_list; - - EVENT_LOOP() = default; - - void Run(std::stop_token token); -}; - -#endif diff --git a/projects/stargazer/main.cpp b/projects/stargazer/main.cpp index 3ee229c2..ee14c3a8 100644 --- a/projects/stargazer/main.cpp +++ b/projects/stargazer/main.cpp @@ -30,7 +30,6 @@ #include "settings_impl.h" #include "pidfile.h" #include "async_pool.h" -#include "eventloop.h" #include "stg_timer.h" #include "stg/user.h" @@ -283,7 +282,6 @@ int main(int argc, char* argv[]) return -1; } - auto& loop = EVENT_LOOP::instance(); STG::AsyncPoolST::start(); StoreLoader storeLoader(settings); @@ -294,13 +292,6 @@ int main(int argc, char* argv[]) return -1; } - if (loop.Start()) - { - printfd(__FILE__, "Event loop not started.\n"); - WriteServLog("Event loop not started."); - return -1; - } - auto& store = storeLoader.get(); WriteServLog("Storage plugin: %s. Loading successfull.", store.GetVersion().c_str()); @@ -380,8 +371,6 @@ int main(int argc, char* argv[]) manager.stop(); STG::AsyncPoolST::stop(); - if (loop.Stop()) - WriteServLog("Event loop not stopped."); if (!traffCnt.Stop()) WriteServLog("Traffcounter: Stop successfull."); diff --git a/projects/stargazer/plugins/authorization/ao/ao.cpp b/projects/stargazer/plugins/authorization/ao/ao.cpp index 78e1c955..1145d679 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.cpp +++ b/projects/stargazer/plugins/authorization/ao/ao.cpp @@ -213,7 +213,6 @@ return -1; template void CHG_BEFORE_NOTIFIER::notify(const varParamType &, const varParamType &) { -//EVENT_LOOP_SINGLETON::GetInstance().Enqueue(auth, &AUTH_AO::Unauthorize, user); if (user->IsAuthorizedBy(&auth)) auth.users->Unauthorize(user->GetLogin(), &auth); } @@ -221,7 +220,6 @@ if (user->IsAuthorizedBy(&auth)) template void CHG_AFTER_NOTIFIER::notify(const varParamType &, const varParamType &) { -//EVENT_LOOP_SINGLETON::GetInstance().Enqueue(auth, &AUTH_AO::UpdateUserAuthorization, user); auth.UpdateUserAuthorization(user); } //----------------------------------------------------------------------------- diff --git a/projects/stargazer/traffcounter_impl.cpp b/projects/stargazer/traffcounter_impl.cpp index 377e3889..ed0f93d5 100644 --- a/projects/stargazer/traffcounter_impl.cpp +++ b/projects/stargazer/traffcounter_impl.cpp @@ -45,11 +45,18 @@ #include "traffcounter_impl.h" #include "stg_timer.h" #include "users_impl.h" +#include "async_pool.h" #define FLUSH_TIME (10) #define REMOVE_TIME (31) using STG::TraffCounterImpl; +using STG::TRF_IP_BEFORE; +using STG::TRF_IP_AFTER; +using STG::ADD_USER_NONIFIER; +using STG::DEL_USER_NONIFIER; + +namespace AsyncPoolST = STG::AsyncPoolST; const char protoName[PROTOMAX][8] = {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"}; @@ -843,3 +850,32 @@ monitorDir = dir; monitoring = !monitorDir.empty(); } //----------------------------------------------------------------------------- +void TRF_IP_BEFORE::notify(const uint32_t & oldValue, const uint32_t &) +{ +// User changes his address. Remove old IP +if (!oldValue) + return; + +AsyncPoolST::enqueue([this, oldValue](){ traffCnt.DelUser(oldValue); }); +} +//----------------------------------------------------------------------------- +void TRF_IP_AFTER::notify(const uint32_t &, const uint32_t & newValue) +{ +// User changes his address. Add new IP +if (!newValue) + return; + +AsyncPoolST::enqueue([this](){ traffCnt.AddUser(user); }); +} +//----------------------------------------------------------------------------- +void ADD_USER_NONIFIER::notify(const UserImplPtr & user) +{ +AsyncPoolST::enqueue([this, user](){ traffCnt.SetUserNotifiers(user); }); +} +//----------------------------------------------------------------------------- +void DEL_USER_NONIFIER::notify(const UserImplPtr & user) +{ +AsyncPoolST::enqueue([this, user](){ traffCnt.UnSetUserNotifiers(user); }); +AsyncPoolST::enqueue([this, user](){ traffCnt.DelUser(user->GetCurrIP()); }); +} +//----------------------------------------------------------------------------- diff --git a/projects/stargazer/traffcounter_impl.h b/projects/stargazer/traffcounter_impl.h index d23f6306..7fd06309 100644 --- a/projects/stargazer/traffcounter_impl.h +++ b/projects/stargazer/traffcounter_impl.h @@ -25,8 +25,6 @@ #include "stg/raw_ip_packet.h" #include "stg/noncopyable.h" #include "stg/notifer.h" -#include "actions.h" -#include "eventloop.h" #include "user_impl.h" #include @@ -236,38 +234,6 @@ class TraffCounterImpl : public TraffCounter { ADD_USER_NONIFIER addUserNotifier; DEL_USER_NONIFIER delUserNotifier; }; -//----------------------------------------------------------------------------- -inline -void TRF_IP_BEFORE::notify(const uint32_t & oldValue, const uint32_t &) -{ -// User changes his address. Remove old IP -if (!oldValue) - return; -EVENT_LOOP::instance().Enqueue(traffCnt, &TraffCounterImpl::DelUser, oldValue); } //----------------------------------------------------------------------------- -inline -void TRF_IP_AFTER::notify(const uint32_t &, const uint32_t & newValue) -{ -// User changes his address. Add new IP -if (!newValue) - return; - -EVENT_LOOP::instance().Enqueue(traffCnt, &TraffCounterImpl::AddUser, user); -} -//----------------------------------------------------------------------------- -inline -void ADD_USER_NONIFIER::notify(const UserImplPtr & user) -{ -EVENT_LOOP::instance().Enqueue(traffCnt, &TraffCounterImpl::SetUserNotifiers, user); -} -//----------------------------------------------------------------------------- -inline -void DEL_USER_NONIFIER::notify(const UserImplPtr & user) -{ -EVENT_LOOP::instance().Enqueue(traffCnt, &TraffCounterImpl::UnSetUserNotifiers, user); -EVENT_LOOP::instance().Enqueue(traffCnt, &TraffCounterImpl::DelUser, user->GetCurrIP()); -} -//----------------------------------------------------------------------------- -} diff --git a/projects/stargazer/users_impl.h b/projects/stargazer/users_impl.h index bfb52fa1..cd7d2932 100644 --- a/projects/stargazer/users_impl.h +++ b/projects/stargazer/users_impl.h @@ -41,8 +41,6 @@ #include "stg/logger.h" #include "stg/notifer.h" #include "stg/noncopyable.h" -#include "actions.h" -#include "eventloop.h" #include "settings_impl.h" #include "user_impl.h" -- 2.44.2 From ee1709cd231588fe672d0bd2546ef69ee87ff88c Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Tue, 23 Aug 2022 18:35:03 +0300 Subject: [PATCH 04/16] Start replacing notifiers with subscriptions. --- include/stg/subscriptions.h | 69 ++++++--- include/stg/users.h | 65 ++++---- .../stargazer/plugins/authorization/ao/ao.cpp | 10 +- .../stargazer/plugins/authorization/ao/ao.h | 28 +--- .../authorization/inetaccess/inetaccess.cpp | 7 +- .../authorization/inetaccess/inetaccess.h | 22 +-- .../stargazer/plugins/other/ping/ping.cpp | 21 +-- projects/stargazer/plugins/other/ping/ping.h | 29 +--- .../plugins/other/rscript/rscript.cpp | 9 +- .../stargazer/plugins/other/rscript/rscript.h | 41 +---- .../stargazer/plugins/other/smux/smux.cpp | 16 +- projects/stargazer/plugins/other/smux/smux.h | 67 +++----- projects/stargazer/traffcounter_impl.cpp | 26 +--- projects/stargazer/traffcounter_impl.h | 42 +---- projects/stargazer/users_impl.cpp | 89 +---------- projects/stargazer/users_impl.h | 144 +++++++++--------- tests/test_subscriptions.cpp | 47 +++--- tests/testusers.h | 6 - 18 files changed, 239 insertions(+), 499 deletions(-) diff --git a/include/stg/subscriptions.h b/include/stg/subscriptions.h index 1486e62d..853cebe1 100644 --- a/include/stg/subscriptions.h +++ b/include/stg/subscriptions.h @@ -7,6 +7,48 @@ namespace STG { +class Connection +{ + public: + Connection() noexcept : m_connected(false) {} + + Connection(const Connection&) = delete; + Connection& operator=(const Connection&) = delete; + Connection(Connection&&) = default; + Connection& operator=(Connection&&) = default; + + Connection(const std::function& f) noexcept : m_disconnect(f), m_connected(true) {} + void disconnect() noexcept + { + if (!m_connected) + return; + m_disconnect(); + m_connected = false; + } + private: + std::function m_disconnect; + bool m_connected; +}; + +class ScopedConnection +{ + public: + ScopedConnection() = default; + + ScopedConnection(const ScopedConnection&) = delete; + ScopedConnection& operator=(const ScopedConnection&) = delete; + ScopedConnection(ScopedConnection&&) = default; + ScopedConnection& operator=(ScopedConnection&&) = default; + + ScopedConnection(Connection c) noexcept : m_conn(std::move(c)) {} + ~ScopedConnection() { disconnect(); } + + void disconnect() noexcept { m_conn.disconnect(); } + + private: + Connection m_conn; +}; + template class Subscriptions { @@ -14,35 +56,16 @@ class Subscriptions using Callback = std::function; using Callbacks = std::list; - class Connection + Connection makeConn(typename Callbacks::iterator i) noexcept { - public: - Connection(Subscriptions& s, typename Callbacks::iterator i) noexcept - : m_subscriptions(s), m_iterator(i), m_connected(true) - {} - ~Connection() - { - disconnect(); - } - - void disconnect() noexcept - { - if (!m_connected) - return; - m_subscriptions.remove(m_iterator); - m_connected = false; - } - private: - Subscriptions& m_subscriptions; - typename Callbacks::iterator m_iterator; - bool m_connected; - }; + return Connection([this, i](){ remove(i); }); + } template Connection add(F&& f) { std::lock_guard lock(m_mutex); - return Connection(*this, m_callbacks.insert(m_callbacks.end(), Callback(std::forward(f)))); + return makeConn(m_callbacks.insert(m_callbacks.end(), Callback(std::forward(f)))); } template diff --git a/include/stg/users.h b/include/stg/users.h index dfc60b64..a8d4eb60 100644 --- a/include/stg/users.h +++ b/include/stg/users.h @@ -20,7 +20,7 @@ #pragma once -#include "notifer.h" +#include "subscriptions.h" #include @@ -31,46 +31,51 @@ struct Admin; struct User; struct Auth; -struct Users { - virtual ~Users() = default; +class Users +{ + public: + virtual ~Users() = default; - using UserPtr = User*; - using ConstUserPtr = const User*; + using UserPtr = User*; + using ConstUserPtr = const User*; - virtual int FindByName(const std::string& login, UserPtr* user) = 0; - virtual int FindByName(const std::string& login, ConstUserPtr* user) const = 0; - virtual bool Exists(const std::string& login) const = 0; + virtual int FindByName(const std::string& login, UserPtr* user) = 0; + virtual int FindByName(const std::string& login, ConstUserPtr* user) const = 0; + virtual bool Exists(const std::string& login) const = 0; - virtual bool TariffInUse(const std::string& tariffName) const = 0; + virtual bool TariffInUse(const std::string& tariffName) const = 0; - virtual void AddNotifierUserAdd(NotifierBase* notifier) = 0; - virtual void DelNotifierUserAdd(NotifierBase* notifier) = 0; + template + auto onUserAdd(F&& f) { return m_onAddCallbacks.add(std::forward(f)); } + template + auto onUserDel(F&& f) { return m_onDelCallbacks.add(std::forward(f)); } - virtual void AddNotifierUserDel(NotifierBase* notifier) = 0; - virtual void DelNotifierUserDel(NotifierBase* notifier) = 0; + virtual int Add(const std::string& login, const Admin* admin) = 0; + virtual void Del(const std::string& login, const Admin* admin) = 0; - virtual int Add(const std::string& login, const Admin* admin) = 0; - virtual void Del(const std::string& login, const Admin* admin) = 0; + virtual bool Authorize(const std::string& login, uint32_t ip, + uint32_t enabledDirs, const Auth* auth) = 0; + virtual bool Unauthorize(const std::string& login, + const Auth* auth, + const std::string& reason = {}) = 0; - virtual bool Authorize(const std::string& login, uint32_t ip, - uint32_t enabledDirs, const Auth* auth) = 0; - virtual bool Unauthorize(const std::string& login, - const Auth* auth, - const std::string& reason = {}) = 0; + virtual int ReadUsers() = 0; + virtual size_t Count() const = 0; - virtual int ReadUsers() = 0; - virtual size_t Count() const = 0; + virtual int FindByIPIdx(uint32_t ip, User** user) const = 0; + virtual bool IsIPInIndex(uint32_t ip) const = 0; + virtual bool IsIPInUse(uint32_t ip, const std::string & login, const User** user) const = 0; - virtual int FindByIPIdx(uint32_t ip, User** user) const = 0; - virtual bool IsIPInIndex(uint32_t ip) const = 0; - virtual bool IsIPInUse(uint32_t ip, const std::string & login, const User** user) const = 0; + virtual unsigned int OpenSearch() = 0; + virtual int SearchNext(int handle, User** u) = 0; + virtual int CloseSearch(int handle) = 0; - virtual unsigned int OpenSearch() = 0; - virtual int SearchNext(int handle, User** u) = 0; - virtual int CloseSearch(int handle) = 0; + virtual int Start() = 0; + virtual int Stop() = 0; - virtual int Start() = 0; - virtual int Stop() = 0; + protected: + Subscriptions m_onAddCallbacks; + Subscriptions m_onDelCallbacks; }; } diff --git a/projects/stargazer/plugins/authorization/ao/ao.cpp b/projects/stargazer/plugins/authorization/ao/ao.cpp index 1145d679..d0be8dd5 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.cpp +++ b/projects/stargazer/plugins/authorization/ao/ao.cpp @@ -48,8 +48,6 @@ return "Always Online authorizator v.1.0"; AUTH_AO::AUTH_AO() : users(NULL), isRunning(false), - onAddUserNotifier(*this), - onDelUserNotifier(*this), logger(STG::PluginLogger::get("auth_ao")) { } @@ -59,8 +57,8 @@ int AUTH_AO::Start() printfd(__FILE__, "AUTH_AO::Start()\n"); GetUsers(); -users->AddNotifierUserAdd(&onAddUserNotifier); -users->AddNotifierUserDel(&onDelUserNotifier); +m_onAddUserConn = users->onUserAdd([this](auto user){ AddUser(user); }); +m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); std::for_each(userList.begin(), userList.end(), [this](auto user){ UpdateUserAuthorization(user); }); @@ -75,8 +73,8 @@ printfd(__FILE__, "AUTH_AO::Stop()\n"); if (!isRunning) return 0; -users->DelNotifierUserAdd(&onAddUserNotifier); -users->DelNotifierUserDel(&onDelUserNotifier); +m_onAddUserConn.disconnect(); +m_onDelUserConn.disconnect(); auto it = userList.begin(); while (it != userList.end()) diff --git a/projects/stargazer/plugins/authorization/ao/ao.h b/projects/stargazer/plugins/authorization/ao/ao.h index a97a0918..18b41429 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.h +++ b/projects/stargazer/plugins/authorization/ao/ao.h @@ -24,6 +24,7 @@ #include "stg/module_settings.h" #include "stg/store.h" #include "stg/notifer.h" +#include "stg/subscriptions.h" #include "stg/user_ips.h" #include "stg/user.h" #include "stg/logger.h" @@ -121,31 +122,8 @@ private: std::list > BeforeChgIPNotifierList; std::list > AfterChgIPNotifierList; - class ADD_USER_NONIFIER: public STG::NotifierBase { - public: - explicit ADD_USER_NONIFIER(AUTH_AO & a) : auth(a) {} - virtual ~ADD_USER_NONIFIER() {} - void notify(const UserPtr & user) override { auth.AddUser(user); } - - private: - ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rvalue); - ADD_USER_NONIFIER & operator=(const ADD_USER_NONIFIER & rvalue); - - AUTH_AO & auth; - } onAddUserNotifier; - - class DEL_USER_NONIFIER: public STG::NotifierBase { - public: - explicit DEL_USER_NONIFIER(AUTH_AO & a) : auth(a) {} - virtual ~DEL_USER_NONIFIER() {} - void notify(const UserPtr & user) override { auth.DelUser(user); } - - private: - DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rvalue); - DEL_USER_NONIFIER & operator=(const DEL_USER_NONIFIER & rvalue); - - AUTH_AO & auth; - } onDelUserNotifier; + STG::ScopedConnection m_onAddUserConn; + STG::ScopedConnection m_onDelUserConn; STG::PluginLogger logger; diff --git a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp index 01162875..3c6a687c 100644 --- a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp +++ b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp @@ -290,7 +290,6 @@ AUTH_IA::AUTH_IA() stgSettings(NULL), listenSocket(-1), enabledDirs(0xFFffFFff), - onDelUserNotifier(*this), logger(STG::PluginLogger::get("auth_ia")) { InitContext("pr7Hhen", 7, &ctxS); @@ -341,12 +340,10 @@ AUTH_IA::~AUTH_IA() //----------------------------------------------------------------------------- int AUTH_IA::Start() { -users->AddNotifierUserDel(&onDelUserNotifier); +m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); if (PrepareNet()) - { return -1; - } if (!m_thread.joinable()) m_thread = std::jthread([this](auto token){ Run(std::move(token)); }); @@ -394,7 +391,7 @@ if (isRunningRunTimeouter) } } -users->DelNotifierUserDel(&onDelUserNotifier); +m_onDelUserConn.disconnect(); if (isRunningRun) m_thread.detach(); diff --git a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h index f9137c20..d620f392 100644 --- a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h +++ b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h @@ -213,21 +213,7 @@ private: class AUTH_IA; using UserPtr = STG::User*; //----------------------------------------------------------------------------- -class DEL_USER_NOTIFIER: public STG::NotifierBase { -public: - explicit DEL_USER_NOTIFIER(AUTH_IA & a) : auth(a) {} - virtual ~DEL_USER_NOTIFIER() {} - - void notify(const UserPtr & user) override; -private: - DEL_USER_NOTIFIER(const DEL_USER_NOTIFIER & rvalue); - DEL_USER_NOTIFIER & operator=(const DEL_USER_NOTIFIER & rvalue); - - AUTH_IA & auth; -}; -//----------------------------------------------------------------------------- class AUTH_IA : public STG::Auth { -friend class DEL_USER_NOTIFIER; public: AUTH_IA(); ~AUTH_IA() override; @@ -350,7 +336,7 @@ private: uint32_t enabledDirs; - DEL_USER_NOTIFIER onDelUserNotifier; + STG::ScopedConnection m_onDelUserConn; STG::PluginLogger logger; @@ -370,9 +356,3 @@ class UnauthorizeUser : std::unary_function & AUTH_IA * auth; }; -//----------------------------------------------------------------------------- -inline -void DEL_USER_NOTIFIER::notify(const UserPtr & user) -{ - auth.DelUser(user); -} diff --git a/projects/stargazer/plugins/other/ping/ping.cpp b/projects/stargazer/plugins/other/ping/ping.cpp index 35237120..65dd3454 100644 --- a/projects/stargazer/plugins/other/ping/ping.cpp +++ b/projects/stargazer/plugins/other/ping/ping.cpp @@ -63,8 +63,6 @@ return 0; PING::PING() : users(nullptr), isRunning(false), - onAddUserNotifier(*this), - onDelUserNotifier(*this), logger(STG::PluginLogger::get("ping")) { } @@ -81,8 +79,8 @@ int PING::Start() { GetUsers(); -users->AddNotifierUserAdd(&onAddUserNotifier); -users->AddNotifierUserDel(&onDelUserNotifier); +m_onAddUserConn = users->onUserAdd([this](auto user){ AddUser(user); }); +m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); pinger.SetDelayTime(pingSettings.GetPingDelay()); pinger.Start(); @@ -111,8 +109,8 @@ for (int i = 0; i < 25; i++) nanosleep(&ts, nullptr); } -users->DelNotifierUserAdd(&onAddUserNotifier); -users->DelNotifierUserDel(&onDelUserNotifier); +m_onAddUserConn.disconnect(); +m_onDelUserConn.disconnect(); std::list::iterator users_iter; users_iter = usersList.begin(); @@ -306,14 +304,3 @@ if (oldIPS.onlyOneIP()) if (newIPS.onlyOneIP()) ping.pinger.AddIP(newIPS[0].ip); } -//----------------------------------------------------------------------------- -void ADD_USER_NONIFIER_PING::notify(const UserPtr & user) -{ -ping.AddUser(user); -} -//----------------------------------------------------------------------------- -void DEL_USER_NONIFIER_PING::notify(const UserPtr & user) -{ -ping.DelUser(user); -} -//----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/other/ping/ping.h b/projects/stargazer/plugins/other/ping/ping.h index ff66a1c2..68d79794 100644 --- a/projects/stargazer/plugins/other/ping/ping.h +++ b/projects/stargazer/plugins/other/ping/ping.h @@ -3,6 +3,7 @@ #include "stg/plugin.h" #include "stg/module_settings.h" #include "stg/notifer.h" +#include "stg/subscriptions.h" #include "stg/user_ips.h" #include "stg/pinger.h" #include "stg/users.h" @@ -55,30 +56,6 @@ private: const PING & ping; }; //----------------------------------------------------------------------------- -class ADD_USER_NONIFIER_PING: public STG::NotifierBase { -public: - explicit ADD_USER_NONIFIER_PING(PING & p) : ping(p) {} - void notify(const UserPtr & user) override; - -private: - ADD_USER_NONIFIER_PING(const ADD_USER_NONIFIER_PING &); - ADD_USER_NONIFIER_PING & operator=(const ADD_USER_NONIFIER_PING &); - - PING & ping; -}; -//----------------------------------------------------------------------------- -class DEL_USER_NONIFIER_PING: public STG::NotifierBase { -public: - explicit DEL_USER_NONIFIER_PING(PING & p) : ping(p) {} - void notify(const UserPtr & user) override; - -private: - DEL_USER_NONIFIER_PING(const DEL_USER_NONIFIER_PING &); - DEL_USER_NONIFIER_PING & operator=(const DEL_USER_NONIFIER_PING &); - - PING & ping; -}; -//----------------------------------------------------------------------------- class PING_SETTINGS { public: PING_SETTINGS() : pingDelay(0) {} @@ -136,8 +113,8 @@ private: std::list ChgCurrIPNotifierList; std::list ChgIPNotifierList; - ADD_USER_NONIFIER_PING onAddUserNotifier; - DEL_USER_NONIFIER_PING onDelUserNotifier; + STG::ScopedConnection m_onAddUserConn; + STG::ScopedConnection m_onDelUserConn; STG::PluginLogger logger; }; diff --git a/projects/stargazer/plugins/other/rscript/rscript.cpp b/projects/stargazer/plugins/other/rscript/rscript.cpp index 7f0f4bc4..d54c800e 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.cpp +++ b/projects/stargazer/plugins/other/rscript/rscript.cpp @@ -160,8 +160,6 @@ REMOTE_SCRIPT::REMOTE_SCRIPT() isRunning(false), users(nullptr), sock(0), - onAddUserNotifier(*this), - onDelUserNotifier(*this), logger(STG::PluginLogger::get("rscript")) { } @@ -201,8 +199,8 @@ netRouters = rsSettings.GetSubnetsMap(); InitEncrypt(rsSettings.GetPassword()); -users->AddNotifierUserAdd(&onAddUserNotifier); -users->AddNotifierUserDel(&onDelUserNotifier); +m_onAddUserConn = users->onUserAdd([this](auto user){ AddUser(user); }); +m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); if (GetUsers()) return -1; @@ -242,9 +240,6 @@ if (isRunning) } } -users->DelNotifierUserDel(&onDelUserNotifier); -users->DelNotifierUserAdd(&onAddUserNotifier); - if (isRunning) { logger("Cannot stop thread."); diff --git a/projects/stargazer/plugins/other/rscript/rscript.h b/projects/stargazer/plugins/other/rscript/rscript.h index fc957108..d0bf1e7e 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.h +++ b/projects/stargazer/plugins/other/rscript/rscript.h @@ -23,6 +23,7 @@ #include "stg/plugin.h" #include "stg/module_settings.h" +#include "stg/subscriptions.h" #include "stg/notifer.h" #include "stg/user.h" #include "stg/blowfish.h" @@ -58,32 +59,6 @@ class DisconnectUser; using UserPtr = STG::User*; -//----------------------------------------------------------------------------- -class ADD_USER_NONIFIER: public STG::NotifierBase { -public: - explicit ADD_USER_NONIFIER(REMOTE_SCRIPT & r) - : rs(r) {} - void notify(const UserPtr & user) override; - -private: - ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rhs); - ADD_USER_NONIFIER & operator=(const ADD_USER_NONIFIER); - - REMOTE_SCRIPT & rs; -}; -//----------------------------------------------------------------------------- -class DEL_USER_NONIFIER: public STG::NotifierBase { -public: - explicit DEL_USER_NONIFIER(REMOTE_SCRIPT & r) - : rs(r) {} - void notify(const UserPtr & user) override; - -private: - DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rhs); - DEL_USER_NONIFIER & operator=(const DEL_USER_NONIFIER); - - REMOTE_SCRIPT & rs; -}; //----------------------------------------------------------------------------- class IP_NOTIFIER: public STG::PropertyNotifierBase { public: @@ -243,8 +218,8 @@ private: int sock; - ADD_USER_NONIFIER onAddUserNotifier; - DEL_USER_NONIFIER onDelUserNotifier; + STG::ScopedConnection m_onAddUserConn; + STG::ScopedConnection m_onDelUserConn; STG::PluginLogger logger; @@ -264,15 +239,5 @@ class DisconnectUser : public std::unary_functionSearchNext(h, &u) == 0) users->CloseSearch(h); -users->AddNotifierUserAdd(&addUserNotifier); -users->AddNotifierUserDel(&delUserNotifier); +m_onAddUserConn = users->onUserAdd([this](auto user){ + SetNotifier(user); + UpdateTables(); +}); +m_onDelUserConn = users->onUserDel([this](auto user){ + UnsetNotifier(user); + UpdateTables(); +}); tariffs->AddNotifierAdd(&addDelTariffNotifier); tariffs->AddNotifierDel(&addDelTariffNotifier); @@ -456,8 +460,8 @@ void SMUX::ResetNotifiers() tariffs->DelNotifierDel(&addDelTariffNotifier); tariffs->DelNotifierAdd(&addDelTariffNotifier); -users->DelNotifierUserDel(&delUserNotifier); -users->DelNotifierUserAdd(&addUserNotifier); +m_onAddUserConn.disconnect(); +m_onDelUserConn.disconnect(); auto it = notifiers.begin(); while (it != notifiers.end()) diff --git a/projects/stargazer/plugins/other/smux/smux.h b/projects/stargazer/plugins/other/smux/smux.h index f45beffc..1986d28b 100644 --- a/projects/stargazer/plugins/other/smux/smux.h +++ b/projects/stargazer/plugins/other/smux/smux.h @@ -1,28 +1,28 @@ -#ifndef __SMUX_H__ -#define __SMUX_H__ +#pragma once -#include -#include -#include -#include -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wshadow" -#include -#pragma GCC diagnostic pop -#include +#include "sensors.h" +#include "tables.h" +#include "types.h" #include "stg/SMUX-PDUs.h" #include "stg/ObjectSyntax.h" #include "stg/plugin.h" #include "stg/module_settings.h" +#include "stg/subscriptions.h" #include "stg/notifer.h" #include "stg/noncopyable.h" #include "stg/logger.h" -#include "sensors.h" -#include "tables.h" -#include "types.h" +#include +#include +#include +#include +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wshadow" +#include +#pragma GCC diagnostic pop +#include namespace STG { @@ -87,24 +87,6 @@ public: : STG::NotifierBase(), smux(s) {} void notify(const STG::TariffData &) override; -private: - SMUX & smux; -}; -//----------------------------------------------------------------------------- -class ADD_USER_NOTIFIER : public STG::NotifierBase { -public: - explicit ADD_USER_NOTIFIER(SMUX & s) : STG::NotifierBase(), smux(s) {} - void notify(const UserPtr &) override; - -private: - SMUX & smux; -}; -//----------------------------------------------------------------------------- -class DEL_USER_NOTIFIER : public STG::NotifierBase { -public: - explicit DEL_USER_NOTIFIER(SMUX & s) : STG::NotifierBase(), smux(s) {} - void notify(const UserPtr &) override; - private: SMUX & smux; }; @@ -186,9 +168,10 @@ private: Sensors sensors; Tables tables; + STG::ScopedConnection m_onAddUserConn; + STG::ScopedConnection m_onDelUserConn; + std::list notifiers; - ADD_USER_NOTIFIER addUserNotifier; - DEL_USER_NOTIFIER delUserNotifier; ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier; STG::PluginLogger logger; @@ -206,19 +189,3 @@ void ADD_DEL_TARIFF_NOTIFIER::notify(const STG::TariffData &) { smux.UpdateTables(); } - -inline -void ADD_USER_NOTIFIER::notify(const UserPtr & userPtr) -{ -smux.SetNotifier(userPtr); -smux.UpdateTables(); -} - -inline -void DEL_USER_NOTIFIER::notify(const UserPtr & userPtr) -{ -smux.UnsetNotifier(userPtr); -smux.UpdateTables(); -} - -#endif diff --git a/projects/stargazer/traffcounter_impl.cpp b/projects/stargazer/traffcounter_impl.cpp index ed0f93d5..aa156c9d 100644 --- a/projects/stargazer/traffcounter_impl.cpp +++ b/projects/stargazer/traffcounter_impl.cpp @@ -53,8 +53,6 @@ using STG::TraffCounterImpl; using STG::TRF_IP_BEFORE; using STG::TRF_IP_AFTER; -using STG::ADD_USER_NONIFIER; -using STG::DEL_USER_NONIFIER; namespace AsyncPoolST = STG::AsyncPoolST; @@ -73,17 +71,20 @@ TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn) monitoring(false), touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC), users(u), - stopped(true), - addUserNotifier(*this), - delUserNotifier(*this) + stopped(true) { for (int i = 0; i < DIR_NUM; i++) strprintf(&dirName[i], "DIR%d", i); dirName[DIR_NUM] = "NULL"; -users->AddNotifierUserAdd(&addUserNotifier); -users->AddNotifierUserDel(&delUserNotifier); +m_onAddUserConn = users->onUserImplAdd([this](auto user){ + AsyncPoolST::enqueue([this, user](){ SetUserNotifiers(user); }); +}); +m_onDelUserConn = users->onUserImplDel([this](auto user){ + AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); }); + AsyncPoolST::enqueue([this, user](){ DelUser(user->GetCurrIP()); }); +}); } //----------------------------------------------------------------------------- TraffCounterImpl::~TraffCounterImpl() @@ -868,14 +869,3 @@ if (!newValue) AsyncPoolST::enqueue([this](){ traffCnt.AddUser(user); }); } //----------------------------------------------------------------------------- -void ADD_USER_NONIFIER::notify(const UserImplPtr & user) -{ -AsyncPoolST::enqueue([this, user](){ traffCnt.SetUserNotifiers(user); }); -} -//----------------------------------------------------------------------------- -void DEL_USER_NONIFIER::notify(const UserImplPtr & user) -{ -AsyncPoolST::enqueue([this, user](){ traffCnt.UnSetUserNotifiers(user); }); -AsyncPoolST::enqueue([this, user](){ traffCnt.DelUser(user->GetCurrIP()); }); -} -//----------------------------------------------------------------------------- diff --git a/projects/stargazer/traffcounter_impl.h b/projects/stargazer/traffcounter_impl.h index 7fd06309..474b6694 100644 --- a/projects/stargazer/traffcounter_impl.h +++ b/projects/stargazer/traffcounter_impl.h @@ -23,7 +23,7 @@ #include "stg/traffcounter.h" #include "stg/logger.h" #include "stg/raw_ip_packet.h" -#include "stg/noncopyable.h" +#include "stg/subscriptions.h" #include "stg/notifer.h" #include "user_impl.h" @@ -130,41 +130,7 @@ private: using UserImplPtr = UserImpl*; //----------------------------------------------------------------------------- -class ADD_USER_NONIFIER: public NotifierBase { -public: - explicit ADD_USER_NONIFIER(TraffCounterImpl & t) : - NotifierBase(), - traffCnt(t) - {} - virtual ~ADD_USER_NONIFIER() {} - void notify(const UserImplPtr & user) override; - -private: - ADD_USER_NONIFIER(const ADD_USER_NONIFIER & rvalue); - ADD_USER_NONIFIER & operator=(const ADD_USER_NONIFIER & rvalue); - - TraffCounterImpl & traffCnt; -}; -//----------------------------------------------------------------------------- -class DEL_USER_NONIFIER: public NotifierBase { -public: - explicit DEL_USER_NONIFIER(TraffCounterImpl & t) : - NotifierBase(), - traffCnt(t) - {} - virtual ~DEL_USER_NONIFIER() {} - void notify(const UserImplPtr & user) override; - -private: - DEL_USER_NONIFIER(const DEL_USER_NONIFIER & rvalue); - DEL_USER_NONIFIER & operator=(const DEL_USER_NONIFIER & rvalue); - - TraffCounterImpl & traffCnt; -}; -//----------------------------------------------------------------------------- class TraffCounterImpl : public TraffCounter { - friend class ADD_USER_NONIFIER; - friend class DEL_USER_NONIFIER; friend class TRF_IP_BEFORE; friend class TRF_IP_AFTER; public: @@ -228,11 +194,11 @@ class TraffCounterImpl : public TraffCounter { std::mutex m_mutex; std::jthread m_thread; + ScopedConnection m_onAddUserConn; + ScopedConnection m_onDelUserConn; + std::list ipBeforeNotifiers; std::list ipAfterNotifiers; - - ADD_USER_NONIFIER addUserNotifier; - DEL_USER_NONIFIER delUserNotifier; }; } diff --git a/projects/stargazer/users_impl.cpp b/projects/stargazer/users_impl.cpp index cfd692c5..5bf082ec 100644 --- a/projects/stargazer/users_impl.cpp +++ b/projects/stargazer/users_impl.cpp @@ -148,26 +148,8 @@ u.OnAdd(); users.push_front(u); AddUserIntoIndexes(users.begin()); - - { - // Fire all "on add" notifiers - auto ni = onAddNotifiers.begin(); - while (ni != onAddNotifiers.end()) - { - (*ni)->notify(&users.front()); - ++ni; - } - } - - { - // Fire all "on add" implementation notifiers - auto ni = onAddNotifiersImpl.begin(); - while (ni != onAddNotifiersImpl.end()) - { - (*ni)->notify(&users.front()); - ++ni; - } - } +m_onAddCallbacks.notify(&users.front()); +m_onAddImplCallbacks.notify(&users.front()); return 0; } @@ -199,23 +181,8 @@ if (priv.userAddDel == 0) u->SetDeleted(); } - { - auto ni = onDelNotifiers.begin(); - while (ni != onDelNotifiers.end()) - { - (*ni)->notify(&(*u)); - ++ni; - } - } - - { - auto ni = onDelNotifiersImpl.begin(); - while (ni != onDelNotifiersImpl.end()) - { - (*ni)->notify(&(*u)); - ++ni; - } - } + m_onDelCallbacks.notify(&(*u)); + m_onDelImplCallbacks.notify(&(*u)); { std::lock_guard lock(m_mutex); @@ -664,54 +631,6 @@ while (iter != users.end()) return false; } //----------------------------------------------------------------------------- -void UsersImpl::AddNotifierUserAdd(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onAddNotifiers.insert(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::DelNotifierUserAdd(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onAddNotifiers.erase(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::AddNotifierUserDel(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onDelNotifiers.insert(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::DelNotifierUserDel(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onDelNotifiers.erase(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::AddNotifierUserAdd(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onAddNotifiersImpl.insert(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::DelNotifierUserAdd(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onAddNotifiersImpl.erase(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::AddNotifierUserDel(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onDelNotifiersImpl.insert(n); -} -//----------------------------------------------------------------------------- -void UsersImpl::DelNotifierUserDel(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onDelNotifiersImpl.erase(n); -} -//----------------------------------------------------------------------------- unsigned int UsersImpl::OpenSearch() { std::lock_guard lock(m_mutex); diff --git a/projects/stargazer/users_impl.h b/projects/stargazer/users_impl.h index cd7d2932..b5a37063 100644 --- a/projects/stargazer/users_impl.h +++ b/projects/stargazer/users_impl.h @@ -64,109 +64,101 @@ std::list::iterator iter; time_t delTime; }; //----------------------------------------------------------------------------- -class UsersImpl : public Users { +class UsersImpl : public Users +{ friend class PROPERTY_NOTIFER_IP_BEFORE; friend class PROPERTY_NOTIFER_IP_AFTER; -public: - using UserImplPtr = UserImpl*; - - UsersImpl(SettingsImpl * s, Store * store, - Tariffs * tariffs, Services & svcs, - const Admin& sysAdmin); - - int FindByName(const std::string & login, UserPtr * user) override; - int FindByName(const std::string & login, ConstUserPtr * user) const override; - bool Exists(const std::string & login) const override; - - bool TariffInUse(const std::string & tariffName) const override; + public: + using UserImplPtr = UserImpl*; - void AddNotifierUserAdd(NotifierBase *) override; - void DelNotifierUserAdd(NotifierBase *) override; + UsersImpl(SettingsImpl * s, Store * store, + Tariffs * tariffs, Services & svcs, + const Admin& sysAdmin); - void AddNotifierUserDel(NotifierBase *) override; - void DelNotifierUserDel(NotifierBase *) override; + int FindByName(const std::string & login, UserPtr * user) override; + int FindByName(const std::string & login, ConstUserPtr * user) const override; + bool Exists(const std::string & login) const override; - void AddNotifierUserAdd(NotifierBase *); - void DelNotifierUserAdd(NotifierBase *); + bool TariffInUse(const std::string & tariffName) const override; - void AddNotifierUserDel(NotifierBase *); - void DelNotifierUserDel(NotifierBase *); + template + auto onUserImplAdd(F&& f) { return m_onAddImplCallbacks.add(std::forward(f)); } + template + auto onUserImplDel(F&& f) { return m_onDelImplCallbacks.add(std::forward(f)); } - int Add(const std::string & login, const Admin * admin) override; - void Del(const std::string & login, const Admin * admin) override; + int Add(const std::string & login, const Admin * admin) override; + void Del(const std::string & login, const Admin * admin) override; - bool Authorize(const std::string & login, uint32_t ip, - uint32_t enabledDirs, const Auth * auth) override; - bool Unauthorize(const std::string & login, - const Auth * auth, - const std::string & reason) override; + bool Authorize(const std::string & login, uint32_t ip, + uint32_t enabledDirs, const Auth * auth) override; + bool Unauthorize(const std::string & login, + const Auth * auth, + const std::string & reason) override; - int ReadUsers() override; - size_t Count() const override { return users.size(); } + int ReadUsers() override; + size_t Count() const override { return users.size(); } - int FindByIPIdx(uint32_t ip, UserPtr * user) const override; - int FindByIPIdx(uint32_t ip, UserImpl ** user) const; - bool IsIPInIndex(uint32_t ip) const override; - bool IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const override; + int FindByIPIdx(uint32_t ip, UserPtr * user) const override; + int FindByIPIdx(uint32_t ip, UserImpl ** user) const; + bool IsIPInIndex(uint32_t ip) const override; + bool IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const override; - unsigned int OpenSearch() override; - int SearchNext(int handler, UserPtr * user) override; - int SearchNext(int handler, UserImpl ** user); - int CloseSearch(int handler) override; + unsigned int OpenSearch() override; + int SearchNext(int handler, UserPtr * user) override; + int SearchNext(int handler, UserImpl ** user); + int CloseSearch(int handler) override; - int Start() override; - int Stop() override; + int Start() override; + int Stop() override; -private: - UsersImpl(const UsersImpl & rvalue); - UsersImpl & operator=(const UsersImpl & rvalue); + private: + UsersImpl(const UsersImpl & rvalue); + UsersImpl & operator=(const UsersImpl & rvalue); - void AddToIPIdx(user_iter user); - void DelFromIPIdx(uint32_t ip); - bool FindByIPIdx(uint32_t ip, user_iter & iter) const; + void AddToIPIdx(user_iter user); + void DelFromIPIdx(uint32_t ip); + bool FindByIPIdx(uint32_t ip, user_iter & iter) const; - bool FindByNameNonLock(const std::string & login, user_iter * user); - bool FindByNameNonLock(const std::string & login, const_user_iter * user) const; + bool FindByNameNonLock(const std::string & login, user_iter * user); + bool FindByNameNonLock(const std::string & login, const_user_iter * user) const; - void RealDelUser(); - void ProcessActions(); + void RealDelUser(); + void ProcessActions(); - void AddUserIntoIndexes(user_iter user); - void DelUserFromIndexes(user_iter user); + void AddUserIntoIndexes(user_iter user); + void DelUserFromIndexes(user_iter user); - void Run(std::stop_token token); - void NewMinute(const struct tm & t); - void NewDay(const struct tm & t); - void DayResetTraff(const struct tm & t); + void Run(std::stop_token token); + void NewMinute(const struct tm & t); + void NewDay(const struct tm & t); + void DayResetTraff(const struct tm & t); - bool TimeToWriteDetailStat(const struct tm & t); + bool TimeToWriteDetailStat(const struct tm & t); - std::list users; - std::list usersToDelete; + std::list users; + std::list usersToDelete; - std::map ipIndex; - std::map loginIndex; + std::map ipIndex; + std::map loginIndex; - SettingsImpl * settings; - Tariffs * m_tariffs; - Services & m_services; - Store * m_store; - const Admin& m_sysAdmin; - Logger & WriteServLog; + SettingsImpl * settings; + Tariffs * m_tariffs; + Services & m_services; + Store * m_store; + const Admin& m_sysAdmin; + Logger & WriteServLog; - bool isRunning; + bool isRunning; - mutable std::mutex m_mutex; - std::jthread m_thread; - mutable unsigned int handle; + mutable std::mutex m_mutex; + std::jthread m_thread; + mutable unsigned int handle; - mutable std::map searchDescriptors; + mutable std::map searchDescriptors; - std::set*> onAddNotifiers; - std::set*> onDelNotifiers; - std::set*> onAddNotifiersImpl; - std::set*> onDelNotifiersImpl; + Subscriptions m_onAddImplCallbacks; + Subscriptions m_onDelImplCallbacks; }; } diff --git a/tests/test_subscriptions.cpp b/tests/test_subscriptions.cpp index ebc3c920..50780927 100644 --- a/tests/test_subscriptions.cpp +++ b/tests/test_subscriptions.cpp @@ -10,6 +10,9 @@ #include #pragma GCC diagnostic pop +using STG::Subscriptions; +using STG::ScopedConnection; + namespace { @@ -37,19 +40,19 @@ struct Receiver } -BOOST_AUTO_TEST_SUITE(Subscriptions) +BOOST_AUTO_TEST_SUITE(TestSubscriptions) BOOST_AUTO_TEST_CASE(Construction) { - STG::Subscriptions<> nullary; + Subscriptions<> nullary; BOOST_CHECK(nullary.empty()); BOOST_CHECK_EQUAL(nullary.size(), 0); - STG::Subscriptions unary; + Subscriptions unary; BOOST_CHECK(unary.empty()); BOOST_CHECK_EQUAL(unary.size(), 0); - STG::Subscriptions binary; + Subscriptions binary; BOOST_CHECK(binary.empty()); BOOST_CHECK_EQUAL(binary.size(), 0); } @@ -57,10 +60,10 @@ BOOST_AUTO_TEST_CASE(Construction) BOOST_AUTO_TEST_CASE(AddingAndRemoving) { Receiver r; - STG::Subscriptions<> nullary; + Subscriptions<> nullary; { - auto c1 = nullary.add(r, &Receiver::r0); - auto c2 = nullary.add([&r](){ r.r0(); }); + ScopedConnection c1 = nullary.add(r, &Receiver::r0); + ScopedConnection c2 = nullary.add([&r](){ r.r0(); }); BOOST_CHECK(!nullary.empty()); BOOST_CHECK_EQUAL(nullary.size(), 2); @@ -73,10 +76,10 @@ BOOST_AUTO_TEST_CASE(AddingAndRemoving) BOOST_CHECK(nullary.empty()); BOOST_CHECK_EQUAL(nullary.size(), 0); - STG::Subscriptions unary; + Subscriptions unary; { - auto c1 = unary.add(r, &Receiver::r1); - auto c2 = unary.add([&r](const auto& v){ r.r1(v); }); + ScopedConnection c1 = unary.add(r, &Receiver::r1); + ScopedConnection c2 = unary.add([&r](const auto& v){ r.r1(v); }); BOOST_CHECK(!unary.empty()); BOOST_CHECK_EQUAL(unary.size(), 2); @@ -89,10 +92,10 @@ BOOST_AUTO_TEST_CASE(AddingAndRemoving) BOOST_CHECK(unary.empty()); BOOST_CHECK_EQUAL(unary.size(), 0); - STG::Subscriptions binary; + Subscriptions binary; { - auto c1 = binary.add(r, &Receiver::r2); - auto c2 = binary.add([&r](const auto& v1, const auto& v2){ r.r2(v1, v2); }); + ScopedConnection c1 = binary.add(r, &Receiver::r2); + ScopedConnection c2 = binary.add([&r](const auto& v1, const auto& v2){ r.r2(v1, v2); }); BOOST_CHECK(!binary.empty()); BOOST_CHECK_EQUAL(binary.size(), 2); @@ -117,10 +120,10 @@ BOOST_AUTO_TEST_CASE(Notification) BOOST_CHECK_EQUAL(r.value1R2, 0); BOOST_CHECK_EQUAL(r.value2R2, ""); - STG::Subscriptions<> nullary; + Subscriptions<> nullary; { - auto c1 = nullary.add(r, &Receiver::r0); - auto c2 = nullary.add([&r](){ r.r0(); }); + ScopedConnection c1 = nullary.add(r, &Receiver::r0); + ScopedConnection c2 = nullary.add([&r](){ r.r0(); }); nullary.notify(); @@ -151,10 +154,10 @@ BOOST_AUTO_TEST_CASE(Notification) BOOST_CHECK_EQUAL(r.value1R2, 0); BOOST_CHECK_EQUAL(r.value2R2, ""); - STG::Subscriptions unary; + Subscriptions unary; { - auto c1 = unary.add(r, &Receiver::r1); - auto c2 = unary.add([&r](const auto& v){ r.r1(v); }); + ScopedConnection c1 = unary.add(r, &Receiver::r1); + ScopedConnection c2 = unary.add([&r](const auto& v){ r.r1(v); }); unary.notify(42); @@ -185,10 +188,10 @@ BOOST_AUTO_TEST_CASE(Notification) BOOST_CHECK_EQUAL(r.value1R2, 0); BOOST_CHECK_EQUAL(r.value2R2, ""); - STG::Subscriptions binary; + Subscriptions binary; { - auto c1 = binary.add(r, &Receiver::r2); - auto c2 = binary.add([&r](const auto& v1, const auto& v2){ r.r2(v1, v2); }); + ScopedConnection c1 = binary.add(r, &Receiver::r2); + ScopedConnection c2 = binary.add([&r](const auto& v1, const auto& v2){ r.r2(v1, v2); }); binary.notify(42, "Douglas"); diff --git a/tests/testusers.h b/tests/testusers.h index adc0507e..c2f5da34 100644 --- a/tests/testusers.h +++ b/tests/testusers.h @@ -17,12 +17,6 @@ struct TestUsers : public STG::Users bool TariffInUse(const std::string& /*tariffName*/) const override { return -1; } - void AddNotifierUserAdd(STG::NotifierBase* /*notifier*/) override {} - void DelNotifierUserAdd(STG::NotifierBase* /*notifier*/) override {} - - void AddNotifierUserDel(STG::NotifierBase* /*notifier*/) override {} - void DelNotifierUserDel(STG::NotifierBase* /*notifier*/) override {} - int Add(const std::string& /*login*/, const STG::Admin* /*admin*/) override { return 0; } void Del(const std::string& /*login*/, const STG::Admin* /*admin*/) override {} -- 2.44.2 From 1cd2b12bd4e4d86f6cd099240795f3ebeb3852b3 Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Thu, 25 Aug 2022 16:16:56 +0300 Subject: [PATCH 05/16] More subscriptions, less notifiers. --- include/stg/subscriptions.h | 6 +-- include/stg/tariffs.h | 39 +++++++++++-------- include/stg/users.h | 6 ++- .../stargazer/plugins/authorization/ao/ao.cpp | 4 +- .../authorization/inetaccess/inetaccess.cpp | 2 +- .../stargazer/plugins/other/ping/ping.cpp | 4 +- .../plugins/other/rscript/rscript.cpp | 4 +- .../stargazer/plugins/other/smux/smux.cpp | 14 +++---- projects/stargazer/plugins/other/smux/smux.h | 19 +-------- projects/stargazer/tariffs_impl.cpp | 39 +------------------ projects/stargazer/tariffs_impl.h | 9 ----- projects/stargazer/traffcounter_impl.cpp | 4 +- projects/stargazer/users_impl.h | 4 +- tests/testtariffs.h | 6 --- 14 files changed, 51 insertions(+), 109 deletions(-) diff --git a/include/stg/subscriptions.h b/include/stg/subscriptions.h index 853cebe1..a50cbba3 100644 --- a/include/stg/subscriptions.h +++ b/include/stg/subscriptions.h @@ -53,7 +53,7 @@ template class Subscriptions { public: - using Callback = std::function; + using Callback = std::function; using Callbacks = std::list; Connection makeConn(typename Callbacks::iterator i) noexcept @@ -71,7 +71,7 @@ class Subscriptions template Connection add(C& c, void (C::*m)(T2s...)) { - return add([&c, m](Ts&&... values){ (c.*m)(std::forward(values)...); }); + return add([&c, m](const Ts&... values){ (c.*m)(values...); }); } void remove(typename Callbacks::iterator i) @@ -80,7 +80,7 @@ class Subscriptions m_callbacks.erase(i); } - void notify(Ts&&... values) + void notify(const Ts&... values) { std::lock_guard lock(m_mutex); for (auto& cb : m_callbacks) diff --git a/include/stg/tariffs.h b/include/stg/tariffs.h index 66db5f31..c47b857f 100644 --- a/include/stg/tariffs.h +++ b/include/stg/tariffs.h @@ -20,11 +20,11 @@ #pragma once +#include "subscriptions.h" + #include #include -#include "notifer.h" - namespace STG { @@ -32,27 +32,32 @@ struct Admin; struct Tariff; struct TariffData; -struct Tariffs { - virtual ~Tariffs() = default; +class Tariffs +{ + public: + virtual ~Tariffs() = default; - virtual int ReadTariffs() = 0; - virtual const Tariff* FindByName(const std::string& name) const = 0; - virtual const Tariff* GetNoTariff() const = 0; - virtual int Del(const std::string& name, const Admin* admin) = 0; - virtual int Add(const std::string& name, const Admin* admin) = 0; - virtual int Chg(const TariffData& td, const Admin* admin) = 0; + virtual int ReadTariffs() = 0; + virtual const Tariff* FindByName(const std::string& name) const = 0; + virtual const Tariff* GetNoTariff() const = 0; + virtual int Del(const std::string& name, const Admin* admin) = 0; + virtual int Add(const std::string& name, const Admin* admin) = 0; + virtual int Chg(const TariffData& td, const Admin* admin) = 0; - virtual void AddNotifierAdd(NotifierBase* notifier) = 0; - virtual void DelNotifierAdd(NotifierBase* notifier) = 0; + template + auto onAdd(F&& f) { return m_onAddCallbacks.add(std::forward(f)); } + template + auto onDel(F&& f) { return m_onDelCallbacks.add(std::forward(f)); } - virtual void AddNotifierDel(NotifierBase* notifier) = 0; - virtual void DelNotifierDel(NotifierBase* notifier) = 0; + virtual void GetTariffsData(std::vector* tdl) const = 0; - virtual void GetTariffsData(std::vector* tdl) const = 0; + virtual size_t Count() const = 0; - virtual size_t Count() const = 0; + virtual const std::string& GetStrError() const = 0; - virtual const std::string& GetStrError() const = 0; + protected: + Subscriptions m_onAddCallbacks; + Subscriptions m_onDelCallbacks; }; } diff --git a/include/stg/users.h b/include/stg/users.h index a8d4eb60..1587f350 100644 --- a/include/stg/users.h +++ b/include/stg/users.h @@ -24,6 +24,8 @@ #include +#include + namespace STG { @@ -46,9 +48,9 @@ class Users virtual bool TariffInUse(const std::string& tariffName) const = 0; template - auto onUserAdd(F&& f) { return m_onAddCallbacks.add(std::forward(f)); } + auto onAdd(F&& f) { return m_onAddCallbacks.add(std::forward(f)); } template - auto onUserDel(F&& f) { return m_onDelCallbacks.add(std::forward(f)); } + auto onDel(F&& f) { return m_onDelCallbacks.add(std::forward(f)); } virtual int Add(const std::string& login, const Admin* admin) = 0; virtual void Del(const std::string& login, const Admin* admin) = 0; diff --git a/projects/stargazer/plugins/authorization/ao/ao.cpp b/projects/stargazer/plugins/authorization/ao/ao.cpp index d0be8dd5..355c7061 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.cpp +++ b/projects/stargazer/plugins/authorization/ao/ao.cpp @@ -57,8 +57,8 @@ int AUTH_AO::Start() printfd(__FILE__, "AUTH_AO::Start()\n"); GetUsers(); -m_onAddUserConn = users->onUserAdd([this](auto user){ AddUser(user); }); -m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); +m_onAddUserConn = users->onAdd([this](auto user){ AddUser(user); }); +m_onDelUserConn = users->onDel([this](auto user){ DelUser(user); }); std::for_each(userList.begin(), userList.end(), [this](auto user){ UpdateUserAuthorization(user); }); diff --git a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp index 3c6a687c..c607b2ac 100644 --- a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp +++ b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.cpp @@ -340,7 +340,7 @@ AUTH_IA::~AUTH_IA() //----------------------------------------------------------------------------- int AUTH_IA::Start() { -m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); +m_onDelUserConn = users->onDel([this](auto user){ DelUser(user); }); if (PrepareNet()) return -1; diff --git a/projects/stargazer/plugins/other/ping/ping.cpp b/projects/stargazer/plugins/other/ping/ping.cpp index 65dd3454..71752de6 100644 --- a/projects/stargazer/plugins/other/ping/ping.cpp +++ b/projects/stargazer/plugins/other/ping/ping.cpp @@ -79,8 +79,8 @@ int PING::Start() { GetUsers(); -m_onAddUserConn = users->onUserAdd([this](auto user){ AddUser(user); }); -m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); +m_onAddUserConn = users->onAdd([this](auto user){ AddUser(user); }); +m_onDelUserConn = users->onDel([this](auto user){ DelUser(user); }); pinger.SetDelayTime(pingSettings.GetPingDelay()); pinger.Start(); diff --git a/projects/stargazer/plugins/other/rscript/rscript.cpp b/projects/stargazer/plugins/other/rscript/rscript.cpp index d54c800e..f8dc9d99 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.cpp +++ b/projects/stargazer/plugins/other/rscript/rscript.cpp @@ -199,8 +199,8 @@ netRouters = rsSettings.GetSubnetsMap(); InitEncrypt(rsSettings.GetPassword()); -m_onAddUserConn = users->onUserAdd([this](auto user){ AddUser(user); }); -m_onDelUserConn = users->onUserDel([this](auto user){ DelUser(user); }); +m_onAddUserConn = users->onAdd([this](auto user){ AddUser(user); }); +m_onDelUserConn = users->onDel([this](auto user){ DelUser(user); }); if (GetUsers()) return -1; diff --git a/projects/stargazer/plugins/other/smux/smux.cpp b/projects/stargazer/plugins/other/smux/smux.cpp index 8d5079bd..07f9d200 100644 --- a/projects/stargazer/plugins/other/smux/smux.cpp +++ b/projects/stargazer/plugins/other/smux/smux.cpp @@ -100,7 +100,6 @@ SMUX::SMUX() lastReconnectTry(0), reconnectTimeout(1), sock(-1), - addDelTariffNotifier(*this), logger(STG::PluginLogger::get("smux")) { smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler; @@ -442,23 +441,24 @@ while (users->SearchNext(h, &u) == 0) users->CloseSearch(h); -m_onAddUserConn = users->onUserAdd([this](auto user){ +m_onAddUserConn = users->onAdd([this](auto user){ SetNotifier(user); UpdateTables(); }); -m_onDelUserConn = users->onUserDel([this](auto user){ +m_onDelUserConn = users->onDel([this](auto user){ UnsetNotifier(user); UpdateTables(); }); -tariffs->AddNotifierAdd(&addDelTariffNotifier); -tariffs->AddNotifierDel(&addDelTariffNotifier); +auto updateTables = [this](const STG::TariffData&){ UpdateTables(); }; +m_onAddTariffConn = tariffs->onAdd(updateTables); +m_onDelTariffConn = tariffs->onDel(updateTables); } void SMUX::ResetNotifiers() { -tariffs->DelNotifierDel(&addDelTariffNotifier); -tariffs->DelNotifierAdd(&addDelTariffNotifier); +m_onAddTariffConn.disconnect(); +m_onDelTariffConn.disconnect(); m_onAddUserConn.disconnect(); m_onDelUserConn.disconnect(); diff --git a/projects/stargazer/plugins/other/smux/smux.h b/projects/stargazer/plugins/other/smux/smux.h index 1986d28b..3e708e2b 100644 --- a/projects/stargazer/plugins/other/smux/smux.h +++ b/projects/stargazer/plugins/other/smux/smux.h @@ -81,16 +81,6 @@ private: UserPtr userPtr; }; //----------------------------------------------------------------------------- -class ADD_DEL_TARIFF_NOTIFIER : public STG::NotifierBase { -public: - explicit ADD_DEL_TARIFF_NOTIFIER(SMUX & s) - : STG::NotifierBase(), smux(s) {} - void notify(const STG::TariffData &) override; - -private: - SMUX & smux; -}; -//----------------------------------------------------------------------------- class SMUX : public STG::Plugin { public: SMUX(); @@ -170,9 +160,10 @@ private: STG::ScopedConnection m_onAddUserConn; STG::ScopedConnection m_onDelUserConn; + STG::ScopedConnection m_onAddTariffConn; + STG::ScopedConnection m_onDelTariffConn; std::list notifiers; - ADD_DEL_TARIFF_NOTIFIER addDelTariffNotifier; STG::PluginLogger logger; }; @@ -183,9 +174,3 @@ void CHG_AFTER_NOTIFIER::notify(const std::string &, const std::string &) { smux.UpdateTables(); } - -inline -void ADD_DEL_TARIFF_NOTIFIER::notify(const STG::TariffData &) -{ -smux.UpdateTables(); -} diff --git a/projects/stargazer/tariffs_impl.cpp b/projects/stargazer/tariffs_impl.cpp index 492f403f..116570d3 100644 --- a/projects/stargazer/tariffs_impl.cpp +++ b/projects/stargazer/tariffs_impl.cpp @@ -175,12 +175,7 @@ TariffData td; tariffs.erase(ti); } -auto ni = onDelNotifiers.begin(); -while (ni != onDelNotifiers.end()) - { - (*ni)->notify(td); - ++ni; - } +m_onDelCallbacks.notify(td); WriteServLog("%s Tariff \'%s\' deleted.", admin->logStr().c_str(), @@ -223,13 +218,7 @@ if (store->AddTariff(name) < 0) return -1; } -// Fire all "on add" notifiers -auto ni = onAddNotifiers.begin(); -while (ni != onAddNotifiers.end()) - { - (*ni)->notify(tariffs.back().GetTariffData()); - ++ni; - } +m_onAddCallbacks.notify(tariffs.back().GetTariffData()); WriteServLog("%s Tariff \'%s\' added.", admin->logStr().c_str(), name.c_str()); @@ -249,27 +238,3 @@ for (; it != tariffs.end(); ++it) } } //----------------------------------------------------------------------------- -void TariffsImpl::AddNotifierAdd(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onAddNotifiers.insert(n); -} -//----------------------------------------------------------------------------- -void TariffsImpl::DelNotifierAdd(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onAddNotifiers.erase(n); -} -//----------------------------------------------------------------------------- -void TariffsImpl::AddNotifierDel(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onDelNotifiers.insert(n); -} -//----------------------------------------------------------------------------- -void TariffsImpl::DelNotifierDel(NotifierBase * n) -{ -std::lock_guard lock(m_mutex); -onDelNotifiers.erase(n); -} -//----------------------------------------------------------------------------- diff --git a/projects/stargazer/tariffs_impl.h b/projects/stargazer/tariffs_impl.h index 4b554b4d..31d22b59 100644 --- a/projects/stargazer/tariffs_impl.h +++ b/projects/stargazer/tariffs_impl.h @@ -55,12 +55,6 @@ class TariffsImpl : public Tariffs { int Add(const std::string & name, const Admin * admin) override; int Chg(const TariffData & td, const Admin * admin) override; - void AddNotifierAdd(NotifierBase * notifier) override; - void DelNotifierAdd(NotifierBase * notifier) override; - - void AddNotifierDel(NotifierBase * notifier) override; - void DelNotifierDel(NotifierBase * notifier) override; - void GetTariffsData(std::vector * tdl) const override; const std::string & GetStrError() const override { return strError; } @@ -72,9 +66,6 @@ class TariffsImpl : public Tariffs { mutable std::mutex m_mutex; std::string strError; TariffImpl noTariff; - - std::set*> onAddNotifiers; - std::set*> onDelNotifiers; }; } diff --git a/projects/stargazer/traffcounter_impl.cpp b/projects/stargazer/traffcounter_impl.cpp index aa156c9d..44f2e558 100644 --- a/projects/stargazer/traffcounter_impl.cpp +++ b/projects/stargazer/traffcounter_impl.cpp @@ -78,10 +78,10 @@ for (int i = 0; i < DIR_NUM; i++) dirName[DIR_NUM] = "NULL"; -m_onAddUserConn = users->onUserImplAdd([this](auto user){ +m_onAddUserConn = users->onImplAdd([this](auto user){ AsyncPoolST::enqueue([this, user](){ SetUserNotifiers(user); }); }); -m_onDelUserConn = users->onUserImplDel([this](auto user){ +m_onDelUserConn = users->onImplDel([this](auto user){ AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); }); AsyncPoolST::enqueue([this, user](){ DelUser(user->GetCurrIP()); }); }); diff --git a/projects/stargazer/users_impl.h b/projects/stargazer/users_impl.h index b5a37063..7b6f900a 100644 --- a/projects/stargazer/users_impl.h +++ b/projects/stargazer/users_impl.h @@ -83,9 +83,9 @@ class UsersImpl : public Users bool TariffInUse(const std::string & tariffName) const override; template - auto onUserImplAdd(F&& f) { return m_onAddImplCallbacks.add(std::forward(f)); } + auto onImplAdd(F&& f) { return m_onAddImplCallbacks.add(std::forward(f)); } template - auto onUserImplDel(F&& f) { return m_onDelImplCallbacks.add(std::forward(f)); } + auto onImplDel(F&& f) { return m_onDelImplCallbacks.add(std::forward(f)); } int Add(const std::string & login, const Admin * admin) override; void Del(const std::string & login, const Admin * admin) override; diff --git a/tests/testtariffs.h b/tests/testtariffs.h index 30f26a5d..ca8ab0ce 100644 --- a/tests/testtariffs.h +++ b/tests/testtariffs.h @@ -16,12 +16,6 @@ class TestTariffs : public STG::Tariffs int Add(const std::string& /*name*/, const STG::Admin* /*admin*/) override { return 0; } int Chg(const STG::TariffData& /*td*/, const STG::Admin* /*admin*/) override { return 0; } - void AddNotifierAdd(STG::NotifierBase*) override {} - void DelNotifierAdd(STG::NotifierBase*) override {} - - void AddNotifierDel(STG::NotifierBase*) override {} - void DelNotifierDel(STG::NotifierBase*) override {} - void GetTariffsData(std::vector* /*tdl*/) const override {} size_t Count() const override { return 0; } -- 2.44.2 From 43ac308ea20014761481bc40525496a0bb1d9740 Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Fri, 26 Aug 2022 14:57:38 +0300 Subject: [PATCH 06/16] Complete replacement notifiers with subscriptions. --- include/stg/notifer.h | 17 -- include/stg/rs_packets.h | 7 +- include/stg/subscriptions.h | 9 +- include/stg/user.h | 110 ++++---- include/stg/user_property.h | 75 ++---- projects/rscriptd/listener.cpp | 6 +- projects/rscriptd/listener.h | 2 +- .../stargazer/plugins/authorization/ao/ao.cpp | 104 ++------ .../stargazer/plugins/authorization/ao/ao.h | 139 ++++------- .../authorization/inetaccess/inetaccess.h | 1 - .../stargazer/plugins/other/ping/ping.cpp | 102 +++----- projects/stargazer/plugins/other/ping/ping.h | 159 +++++------- .../plugins/other/rscript/rscript.cpp | 68 ++--- .../stargazer/plugins/other/rscript/rscript.h | 226 ++++++----------- .../plugins/other/rscript/ur_functor.h | 83 +++---- .../stargazer/plugins/other/smux/handlers.cpp | 2 + .../stargazer/plugins/other/smux/smux.cpp | 41 ++- projects/stargazer/plugins/other/smux/smux.h | 234 ++++++++---------- projects/stargazer/traffcounter_impl.cpp | 77 ++---- projects/stargazer/traffcounter_impl.h | 66 +---- projects/stargazer/user_impl.cpp | 217 ++++++---------- projects/stargazer/user_impl.h | 94 ++----- projects/stargazer/users_impl.h | 19 +- tests/test_reconnect_on_tariff_change.cpp | 44 ++-- 24 files changed, 675 insertions(+), 1227 deletions(-) delete mode 100644 include/stg/notifer.h diff --git a/include/stg/notifer.h b/include/stg/notifer.h deleted file mode 100644 index 339b6170..00000000 --- a/include/stg/notifer.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -namespace STG -{ - -template -struct NotifierBase -{ - virtual ~NotifierBase() = default; - - virtual void notify(const Ts&... values) = 0; -}; - -template -using PropertyNotifierBase = NotifierBase; - -} diff --git a/include/stg/rs_packets.h b/include/stg/rs_packets.h index 0c31e228..6faea525 100644 --- a/include/stg/rs_packets.h +++ b/include/stg/rs_packets.h @@ -19,8 +19,7 @@ * Author : Maxim Mamontov */ -#ifndef RS_PACKETSH -#define RS_PACKETSH +#pragma once #define RS_MAGIC_LEN (6) #define RS_PROTO_VER_LEN (2) @@ -36,7 +35,7 @@ #include -namespace RS +namespace STG::RS { struct PACKET_HEADER @@ -58,5 +57,3 @@ int8_t padding[7]; } __attribute__((__packed__)); // 992 bytes, 124 blocks } // namespace RS - -#endif diff --git a/include/stg/subscriptions.h b/include/stg/subscriptions.h index a50cbba3..9ee9c64a 100644 --- a/include/stg/subscriptions.h +++ b/include/stg/subscriptions.h @@ -10,24 +10,23 @@ namespace STG class Connection { public: - Connection() noexcept : m_connected(false) {} + Connection() = default; Connection(const Connection&) = delete; Connection& operator=(const Connection&) = delete; Connection(Connection&&) = default; Connection& operator=(Connection&&) = default; - Connection(const std::function& f) noexcept : m_disconnect(f), m_connected(true) {} + Connection(const std::function& f) noexcept : m_disconnect(f) {} void disconnect() noexcept { - if (!m_connected) + if (!m_disconnect) return; m_disconnect(); - m_connected = false; + m_disconnect = {}; } private: std::function m_disconnect; - bool m_connected; }; class ScopedConnection diff --git a/include/stg/user.h b/include/stg/user.h index b08f3cd0..78b602ba 100644 --- a/include/stg/user.h +++ b/include/stg/user.h @@ -20,8 +20,8 @@ #pragma once -#include "notifer.h" #include "message.h" +#include "user_property.h" #include #include @@ -37,77 +37,91 @@ class UserProperties; class DirTraff; struct Auth; -using CURR_IP_NOTIFIER = PropertyNotifierBase; -using CONNECTED_NOTIFIER = PropertyNotifierBase; +class User +{ + public: + User() noexcept + : m_connectedBase(false), + m_currIPBase(0), + m_connected(m_connectedBase), + m_currIP(m_currIPBase) + { + } + + virtual ~User() = default; -struct User { - virtual ~User() = default; + virtual int WriteConf() = 0; + virtual int WriteStat() = 0; - virtual int WriteConf() = 0; - virtual int WriteStat() = 0; + virtual const std::string& GetLogin() const = 0; - virtual const std::string& GetLogin() const = 0; + uint32_t GetCurrIP() const { return m_currIP; } + time_t GetCurrIPModificationTime() const { return m_currIP.ModificationTime(); } - virtual uint32_t GetCurrIP() const = 0; - virtual time_t GetCurrIPModificationTime() const = 0; + template + auto beforeCurrIPChange(F&& f) { return m_currIP.beforeChange(std::forward(f)); } + template + auto afterCurrIPChange(F&& f) { return m_currIP.afterChange(std::forward(f)); } - virtual void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER* notifier) = 0; - virtual void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER* notifier) = 0; + template + auto beforeConnectedChange(F&& f) { return m_connected.beforeChange(std::forward(f)); } + template + auto afterConnectedChange(F&& f) { return m_connected.afterChange(std::forward(f)); } - virtual void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER* notifier) = 0; - virtual void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER* notifier) = 0; + virtual int GetID() const = 0; - virtual void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER* notifier) = 0; - virtual void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER* notifier) = 0; + virtual double GetPassiveTimePart() const = 0; - virtual void AddConnectedAfterNotifier(CONNECTED_NOTIFIER* notifier) = 0; - virtual void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER* notifier) = 0; + virtual const Tariff* GetTariff() const = 0; + virtual void ResetNextTariff() = 0; - virtual int GetID() const = 0; + virtual const DirTraff& GetSessionUpload() const = 0; + virtual const DirTraff& GetSessionDownload() const = 0; + virtual time_t GetSessionUploadModificationTime() const = 0; + virtual time_t GetSessionDownloadModificationTime() const = 0; - virtual double GetPassiveTimePart() const = 0; + bool GetConnected() const { return m_connected; } + time_t GetConnectedModificationTime() const { return m_connected.ModificationTime(); } - virtual const Tariff* GetTariff() const = 0; - virtual void ResetNextTariff() = 0; + virtual const std::string& GetLastDisconnectReason() const = 0; + virtual int GetAuthorized() const = 0; + virtual time_t GetAuthorizedModificationTime() const = 0; - virtual const DirTraff& GetSessionUpload() const = 0; - virtual const DirTraff& GetSessionDownload() const = 0; - virtual time_t GetSessionUploadModificationTime() const = 0; - virtual time_t GetSessionDownloadModificationTime() const = 0; + virtual bool IsAuthorizedBy(const Auth * auth) const = 0; + virtual std::vector GetAuthorizers() const = 0; - virtual bool GetConnected() const = 0; - virtual time_t GetConnectedModificationTime() const = 0; - virtual const std::string& GetLastDisconnectReason() const = 0; - virtual int GetAuthorized() const = 0; - virtual time_t GetAuthorizedModificationTime() const = 0; + virtual int AddMessage(Message* msg) = 0; - virtual bool IsAuthorizedBy(const Auth * auth) const = 0; - virtual std::vector GetAuthorizers() const = 0; + virtual void UpdatePingTime(time_t t = 0) = 0; + virtual time_t GetPingTime() const = 0; - virtual int AddMessage(Message* msg) = 0; + virtual void Run() = 0; - virtual void UpdatePingTime(time_t t = 0) = 0; - virtual time_t GetPingTime() const = 0; + virtual const std::string& GetStrError() const = 0; - virtual void Run() = 0; + virtual UserProperties& GetProperties() = 0; + virtual const UserProperties& GetProperties() const = 0; - virtual const std::string& GetStrError() const = 0; + virtual bool GetDeleted() const = 0; + virtual void SetDeleted() = 0; - virtual UserProperties& GetProperties() = 0; - virtual const UserProperties& GetProperties() const = 0; + virtual time_t GetLastWriteStatTime() const = 0; - virtual bool GetDeleted() const = 0; - virtual void SetDeleted() = 0; + virtual bool IsInetable() = 0; + virtual std::string GetEnabledDirs() const = 0; - virtual time_t GetLastWriteStatTime() const = 0; + virtual void OnAdd() = 0; + virtual void OnDelete() = 0; - virtual bool IsInetable() = 0; - virtual std::string GetEnabledDirs() const = 0; + virtual std::string GetParamValue(const std::string& name) const = 0; - virtual void OnAdd() = 0; - virtual void OnDelete() = 0; + private: + bool m_connectedBase; + uint32_t m_currIPBase; - virtual std::string GetParamValue(const std::string& name) const = 0; + protected: + UserProperty m_connected; + UserProperty m_currIP; }; } diff --git a/include/stg/user_property.h b/include/stg/user_property.h index 529d854a..d73a636b 100644 --- a/include/stg/user_property.h +++ b/include/stg/user_property.h @@ -4,7 +4,7 @@ #include "stg/user_ips.h" #include "stg/store.h" #include "stg/admin.h" -#include "stg/notifer.h" +#include "stg/subscriptions.h" #include "stg/admin_conf.h" #include "stg/logger.h" #include "stg/locker.h" @@ -25,7 +25,8 @@ namespace STG { //----------------------------------------------------------------------------- -struct UserPropertyBase { +struct UserPropertyBase +{ virtual ~UserPropertyBase() = default; virtual std::string ToString() const = 0; }; @@ -33,7 +34,8 @@ struct UserPropertyBase { using Registry = std::map; //----------------------------------------------------------------------------- template -class UserProperty : public UserPropertyBase { +class UserProperty : public UserPropertyBase +{ public: explicit UserProperty(T& val); @@ -47,11 +49,10 @@ class UserProperty : public UserPropertyBase { operator const T&() const noexcept { return value; } - void AddBeforeNotifier(PropertyNotifierBase* n); - void DelBeforeNotifier(const PropertyNotifierBase* n); - - void AddAfterNotifier(PropertyNotifierBase* n); - void DelAfterNotifier(const PropertyNotifierBase* n); + template + auto beforeChange(F&& f) { return m_beforeCallbacks.add(std::forward(f)); } + template + auto afterChange(F&& f) { return m_afterCallbacks.add(std::forward(f)); } time_t ModificationTime() const noexcept { return modificationTime; } void ModifyTime() noexcept; @@ -60,13 +61,14 @@ class UserProperty : public UserPropertyBase { private: T& value; time_t modificationTime; - std::set*> beforeNotifiers; - std::set*> afterNotifiers; + Subscriptions m_beforeCallbacks; + Subscriptions m_afterCallbacks; std::mutex mutex; }; //----------------------------------------------------------------------------- template -class UserPropertyLogged: public UserProperty { +class UserPropertyLogged: public UserProperty +{ public: UserPropertyLogged(T& val, const std::string& n, @@ -110,7 +112,8 @@ class UserPropertyLogged: public UserProperty { const Settings& settings; }; //----------------------------------------------------------------------------- -class UserProperties { +class UserProperties +{ /* В этом месте важен порядок следования приватной и открытой частей. Это связано с тем, что часть которая находится в публичной секции @@ -184,9 +187,7 @@ template inline UserProperty::UserProperty(T& val) : value(val), - modificationTime(time(NULL)), - beforeNotifiers(), - afterNotifiers() + modificationTime(time(NULL)) { } //----------------------------------------------------------------------------- @@ -199,22 +200,18 @@ void UserProperty::ModifyTime() noexcept //----------------------------------------------------------------------------- template inline -void UserProperty::Set(const T& rvalue) +void UserProperty::Set(const T& rhs) { std::lock_guard lock(mutex); T oldVal = value; - auto ni = beforeNotifiers.begin(); - while (ni != beforeNotifiers.end()) - (*ni++)->notify(oldVal, rvalue); + m_beforeCallbacks.notify(oldVal, rhs); - value = rvalue; + value = rhs; modificationTime = time(NULL); - ni = afterNotifiers.begin(); - while (ni != afterNotifiers.end()) - (*ni++)->notify(oldVal, rvalue); + m_afterCallbacks.notify(oldVal, rhs); } //----------------------------------------------------------------------------- template @@ -225,38 +222,6 @@ UserProperty& UserProperty::operator=(const T& newValue) return *this; } //----------------------------------------------------------------------------- -template -inline -void UserProperty::AddBeforeNotifier(PropertyNotifierBase* n) -{ - std::lock_guard lock(mutex); - beforeNotifiers.insert(n); -} -//----------------------------------------------------------------------------- -template -inline -void UserProperty::DelBeforeNotifier(const PropertyNotifierBase* n) -{ - std::lock_guard lock(mutex); - beforeNotifiers.erase(const_cast*>(n)); -} -//----------------------------------------------------------------------------- -template -inline -void UserProperty::AddAfterNotifier(PropertyNotifierBase* n) -{ - std::lock_guard lock(mutex); - afterNotifiers.insert(n); -} -//----------------------------------------------------------------------------- -template -inline -void UserProperty::DelAfterNotifier(const PropertyNotifierBase* n) -{ - std::lock_guard lock(mutex); - afterNotifiers.erase(const_cast*>(n)); -} -//----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- template diff --git a/projects/rscriptd/listener.cpp b/projects/rscriptd/listener.cpp index b168e5e2..a1193527 100644 --- a/projects/rscriptd/listener.cpp +++ b/projects/rscriptd/listener.cpp @@ -199,7 +199,7 @@ bool LISTENER::RecvPacket(const std::stop_token& token) struct iovec iov[2]; char buffer[RS_MAX_PACKET_LEN]; -RS::PACKET_HEADER packetHead; +STG::RS::PACKET_HEADER packetHead; iov[0].iov_base = reinterpret_cast(&packetHead); iov[0].iov_len = sizeof(packetHead); @@ -266,7 +266,7 @@ return false; //----------------------------------------------------------------------------- bool LISTENER::GetParams(char * buffer, UserData & data) { -RS::PACKET_TAIL packetTail; +STG::RS::PACKET_TAIL packetTail; DecryptString(&packetTail, buffer, sizeof(packetTail), &ctxS); @@ -407,7 +407,7 @@ else return false; } //----------------------------------------------------------------------------- -bool LISTENER::CheckHeader(const RS::PACKET_HEADER & header) const +bool LISTENER::CheckHeader(const STG::RS::PACKET_HEADER & header) const { if (strncmp(reinterpret_cast(header.magic), RS_ID, RS_MAGIC_LEN)) return true; diff --git a/projects/rscriptd/listener.h b/projects/rscriptd/listener.h index 4d36b87a..473ce556 100644 --- a/projects/rscriptd/listener.h +++ b/projects/rscriptd/listener.h @@ -87,7 +87,7 @@ private: bool FinalizeNet(); bool RecvPacket(const std::stop_token& token); // Parsing stuff - bool CheckHeader(const RS::PACKET_HEADER & header) const; + bool CheckHeader(const STG::RS::PACKET_HEADER & header) const; bool GetParams(char * buffer, UserData & data); // Processing stuff void ProcessPending(); diff --git a/projects/stargazer/plugins/authorization/ao/ao.cpp b/projects/stargazer/plugins/authorization/ao/ao.cpp index 355c7061..cb9a804d 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.cpp +++ b/projects/stargazer/plugins/authorization/ao/ao.cpp @@ -32,6 +32,8 @@ #include +using STG::AUTH_AO; + extern "C" STG::Plugin* GetPlugin() { static AUTH_AO plugin; @@ -48,7 +50,7 @@ return "Always Online authorizator v.1.0"; AUTH_AO::AUTH_AO() : users(NULL), isRunning(false), - logger(STG::PluginLogger::get("auth_ao")) + logger(PluginLogger::get("auth_ao")) { } //----------------------------------------------------------------------------- @@ -76,88 +78,28 @@ if (!isRunning) m_onAddUserConn.disconnect(); m_onDelUserConn.disconnect(); -auto it = userList.begin(); -while (it != userList.end()) - { - if ((*it)->IsAuthorizedBy(this)) - users->Unauthorize((*it)->GetLogin(), this); - UnSetUserNotifiers(*it); - ++it; - } +m_conns.clear(); + isRunning = false; return 0; } //----------------------------------------------------------------------------- void AUTH_AO::SetUserNotifiers(UserPtr u) { -// ---------- AlwaysOnline ------------------- -CHG_BEFORE_NOTIFIER BeforeChgAONotifier(*this, u); -CHG_AFTER_NOTIFIER AfterChgAONotifier(*this, u); - -BeforeChgAONotifierList.push_front(BeforeChgAONotifier); -AfterChgAONotifierList.push_front(AfterChgAONotifier); - -u->GetProperties().alwaysOnline.AddBeforeNotifier(&BeforeChgAONotifierList.front()); -u->GetProperties().alwaysOnline.AddAfterNotifier(&AfterChgAONotifierList.front()); -// ---------- AlwaysOnline end --------------- - -// ---------- IP ------------------- -CHG_BEFORE_NOTIFIER BeforeChgIPNotifier(*this, u); -CHG_AFTER_NOTIFIER AfterChgIPNotifier(*this, u); - -BeforeChgIPNotifierList.push_front(BeforeChgIPNotifier); -AfterChgIPNotifierList.push_front(AfterChgIPNotifier); - -u->GetProperties().ips.AddBeforeNotifier(&BeforeChgIPNotifierList.front()); -u->GetProperties().ips.AddAfterNotifier(&AfterChgIPNotifierList.front()); -// ---------- IP end --------------- + m_conns.emplace_back( + u->GetID(), + u->GetProperties().alwaysOnline.beforeChange([this, u](auto, auto){ Unauthorize(u); }), + u->GetProperties().alwaysOnline.afterChange([this, u](auto, auto){ UpdateUserAuthorization(u); }), + u->GetProperties().ips.beforeChange([this, u](const auto&, const auto&){ Unauthorize(u); }), + u->GetProperties().ips.afterChange([this, u](const auto&, const auto&){ UpdateUserAuthorization(u); }) + ); } //----------------------------------------------------------------------------- void AUTH_AO::UnSetUserNotifiers(UserPtr u) { -// --- AlwaysOnline --- -auto aoBIter = find_if(BeforeChgAONotifierList.begin(), - BeforeChgAONotifierList.end(), - [u](auto notifier){ return notifier.GetUser() == u; }); - -if (aoBIter != BeforeChgAONotifierList.end()) - { - aoBIter->GetUser()->GetProperties().alwaysOnline.DelBeforeNotifier(&(*aoBIter)); - BeforeChgAONotifierList.erase(aoBIter); - } - -auto aoAIter = find_if(AfterChgAONotifierList.begin(), - AfterChgAONotifierList.end(), - [u](auto notifier){ return notifier.GetUser() == u; }); - -if (aoAIter != AfterChgAONotifierList.end()) - { - aoAIter->GetUser()->GetProperties().alwaysOnline.DelAfterNotifier(&(*aoAIter)); - AfterChgAONotifierList.erase(aoAIter); - } -// --- AlwaysOnline end --- - -// --- IP --- -auto ipBIter = std::find_if(BeforeChgIPNotifierList.begin(), - BeforeChgIPNotifierList.end(), - [u](auto notifier){ return notifier.GetUser() == u; }); - -if (ipBIter != BeforeChgIPNotifierList.end()) - { - ipBIter->GetUser()->GetProperties().ips.DelBeforeNotifier(&(*ipBIter)); - BeforeChgIPNotifierList.erase(ipBIter); - } - -auto ipAIter = find_if(AfterChgIPNotifierList.begin(), - AfterChgIPNotifierList.end(), - [u](auto notifier){ return notifier.GetUser() == u; }); - -if (ipAIter != AfterChgIPNotifierList.end()) - { - ipAIter->GetUser()->GetProperties().ips.DelAfterNotifier(&(*ipAIter)); - AfterChgIPNotifierList.erase(ipAIter); - } -// --- IP end --- + m_conns.erase(std::remove_if(m_conns.begin(), m_conns.end(), + [u](const auto& c){ return std::get<0>(c) == u->GetID(); }), + m_conns.end()); } //----------------------------------------------------------------------------- void AUTH_AO::GetUsers() @@ -202,22 +144,14 @@ UnSetUserNotifiers(u); userList.erase(std::remove(userList.begin(), userList.end(), u), userList.end()); } //----------------------------------------------------------------------------- -int AUTH_AO::SendMessage(const STG::Message &, uint32_t) const +int AUTH_AO::SendMessage(const Message &, uint32_t) const { errorStr = "Authorization modele \'AlwaysOnline\' does not support sending messages"; return -1; } //----------------------------------------------------------------------------- -template -void CHG_BEFORE_NOTIFIER::notify(const varParamType &, const varParamType &) +void AUTH_AO::Unauthorize(UserPtr user) { -if (user->IsAuthorizedBy(&auth)) - auth.users->Unauthorize(user->GetLogin(), &auth); + if (user->IsAuthorizedBy(this)) + users->Unauthorize(user->GetLogin(), this); } -//----------------------------------------------------------------------------- -template -void CHG_AFTER_NOTIFIER::notify(const varParamType &, const varParamType &) -{ -auth.UpdateUserAuthorization(user); -} -//----------------------------------------------------------------------------- diff --git a/projects/stargazer/plugins/authorization/ao/ao.h b/projects/stargazer/plugins/authorization/ao/ao.h index 18b41429..add62d4e 100644 --- a/projects/stargazer/plugins/authorization/ao/ao.h +++ b/projects/stargazer/plugins/authorization/ao/ao.h @@ -23,7 +23,6 @@ #include "stg/auth.h" #include "stg/module_settings.h" #include "stg/store.h" -#include "stg/notifer.h" #include "stg/subscriptions.h" #include "stg/user_ips.h" #include "stg/user.h" @@ -38,98 +37,58 @@ namespace STG { struct Users; -} class AUTH_AO; -using UserPtr = STG::User*; -using ConstUserPtr = const STG::User*; - -template -class CHG_BEFORE_NOTIFIER : public STG::PropertyNotifierBase { -public: - CHG_BEFORE_NOTIFIER(AUTH_AO & a, UserPtr u) - : user(u), auth(a) {} - CHG_BEFORE_NOTIFIER(const CHG_BEFORE_NOTIFIER & rvalue) - : user(rvalue.user), auth(rvalue.auth) {} - void notify(const T & oldValue, const T & newValue) override; - UserPtr GetUser() const { return user; } - -private: - CHG_BEFORE_NOTIFIER & operator=(const CHG_BEFORE_NOTIFIER & rvalue); - - UserPtr user; - const AUTH_AO & auth; -}; +using UserPtr = User*; +using ConstUserPtr = const User*; //----------------------------------------------------------------------------- -template -class CHG_AFTER_NOTIFIER : public STG::PropertyNotifierBase { -public: - CHG_AFTER_NOTIFIER(AUTH_AO & a, UserPtr u) - : user(u), auth(a) {} - CHG_AFTER_NOTIFIER(const CHG_AFTER_NOTIFIER & rvalue) - : user(rvalue.user), auth(rvalue.auth) {} - void notify(const T & oldValue, const T & newValue) override; - UserPtr GetUser() const { return user; } - -private: - CHG_AFTER_NOTIFIER & operator=(const CHG_AFTER_NOTIFIER & rvalue); - - UserPtr user; - const AUTH_AO & auth; +class AUTH_AO : public Auth +{ + public: + AUTH_AO(); + + void SetUsers(Users * u) override { users = u; } + + int Start() override; + int Stop() override; + int Reload(const ModuleSettings & /*ms*/) override { return 0; } + bool IsRunning() override { return isRunning; } + void SetSettings(const ModuleSettings &) override {} + int ParseSettings() override { return 0; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override; + uint16_t GetStartPosition() const override { return 30; } + uint16_t GetStopPosition() const override { return 30; } + + int SendMessage(const Message & msg, uint32_t ip) const override; + + private: + AUTH_AO(const AUTH_AO & rvalue); + AUTH_AO & operator=(const AUTH_AO & rvalue); + + void AddUser(UserPtr u); + void DelUser(UserPtr u); + + void GetUsers(); + void SetUserNotifiers(UserPtr u); + void UnSetUserNotifiers(UserPtr u); + void UpdateUserAuthorization(ConstUserPtr u) const; + void Unauthorize(UserPtr u); + + mutable std::string errorStr; + Users * users; + std::vector userList; + bool isRunning; + ModuleSettings settings; + + using ConnHolder = std::tuple; + std::vector m_conns; + + ScopedConnection m_onAddUserConn; + ScopedConnection m_onDelUserConn; + + PluginLogger logger; }; -//----------------------------------------------------------------------------- -class AUTH_AO : public STG::Auth { -public: - AUTH_AO(); - - void SetUsers(STG::Users * u) override { users = u; } - - int Start() override; - int Stop() override; - int Reload(const STG::ModuleSettings & /*ms*/) override { return 0; } - bool IsRunning() override { return isRunning; } - void SetSettings(const STG::ModuleSettings &) override {} - int ParseSettings() override { return 0; } - const std::string & GetStrError() const override { return errorStr; } - std::string GetVersion() const override; - uint16_t GetStartPosition() const override { return 30; } - uint16_t GetStopPosition() const override { return 30; } - - int SendMessage(const STG::Message & msg, uint32_t ip) const override; - -private: - AUTH_AO(const AUTH_AO & rvalue); - AUTH_AO & operator=(const AUTH_AO & rvalue); - void AddUser(UserPtr u); - void DelUser(UserPtr u); - - void GetUsers(); - void SetUserNotifiers(UserPtr u); - void UnSetUserNotifiers(UserPtr u); - void UpdateUserAuthorization(ConstUserPtr u) const; - - mutable std::string errorStr; - STG::Users * users; - std::vector userList; - bool isRunning; - STG::ModuleSettings settings; - - std::list > BeforeChgAONotifierList; - std::list > AfterChgAONotifierList; - - std::list > BeforeChgIPNotifierList; - std::list > AfterChgIPNotifierList; - - STG::ScopedConnection m_onAddUserConn; - STG::ScopedConnection m_onDelUserConn; - - STG::PluginLogger logger; - - friend class CHG_BEFORE_NOTIFIER; - friend class CHG_AFTER_NOTIFIER; - friend class CHG_BEFORE_NOTIFIER; - friend class CHG_AFTER_NOTIFIER; - -}; +} diff --git a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h index d620f392..65c15c7b 100644 --- a/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h +++ b/projects/stargazer/plugins/authorization/inetaccess/inetaccess.h @@ -22,7 +22,6 @@ #include "stg/auth.h" #include "stg/store.h" #include "stg/module_settings.h" -#include "stg/notifer.h" #include "stg/user_ips.h" #include "stg/user.h" #include "stg/users.h" diff --git a/projects/stargazer/plugins/other/ping/ping.cpp b/projects/stargazer/plugins/other/ping/ping.cpp index 71752de6..db081f7e 100644 --- a/projects/stargazer/plugins/other/ping/ping.cpp +++ b/projects/stargazer/plugins/other/ping/ping.cpp @@ -4,43 +4,32 @@ #include "stg/locker.h" #include "stg/user_property.h" +#include #include #include #include #include -#include + +using STG::PING; +using STG::PING_SETTINGS; namespace { -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -//----------------------------------------------------------------------------- -template -class HAS_USER: public std::binary_function -{ -public: - explicit HAS_USER(const UserPtr & u) : user(u) {} - bool operator()(varType notifier) const - { - return notifier.GetUser() == user; - } -private: - const UserPtr & user; -}; -} extern "C" STG::Plugin* GetPlugin() { static PING plugin; return &plugin; } + +} //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -int PING_SETTINGS::ParseSettings(const STG::ModuleSettings & s) +int PING_SETTINGS::ParseSettings(const ModuleSettings & s) { -STG::ParamValue pv; -std::vector::const_iterator pvi; +ParamValue pv; +std::vector::const_iterator pvi; pv.param = "PingDelay"; pvi = std::find(s.moduleParams.begin(), s.moduleParams.end(), pv); @@ -63,7 +52,7 @@ return 0; PING::PING() : users(nullptr), isRunning(false), - logger(STG::PluginLogger::get("ping")) + logger(PluginLogger::get("ping")) { } //----------------------------------------------------------------------------- @@ -112,13 +101,7 @@ for (int i = 0; i < 25; i++) m_onAddUserConn.disconnect(); m_onDelUserConn.disconnect(); -std::list::iterator users_iter; -users_iter = usersList.begin(); -while (users_iter != usersList.end()) - { - UnSetUserNotifiers(*users_iter); - ++users_iter; - } +m_conns.clear(); if (isRunning) m_thread.detach(); @@ -191,47 +174,18 @@ isRunning = false; //----------------------------------------------------------------------------- void PING::SetUserNotifiers(UserPtr u) { -CHG_CURRIP_NOTIFIER_PING ChgCurrIPNotifier(*this, u); -CHG_IPS_NOTIFIER_PING ChgIPNotifier(*this, u); - -ChgCurrIPNotifierList.push_front(ChgCurrIPNotifier); -ChgIPNotifierList.push_front(ChgIPNotifier); - -u->AddCurrIPAfterNotifier(&(*ChgCurrIPNotifierList.begin())); -u->GetProperties().ips.AddAfterNotifier(&(*ChgIPNotifierList.begin())); + m_conns.emplace_back( + u->GetID(), + u->afterCurrIPChange([this](auto oldVal, auto newVal){ updateCurrIP(oldVal, newVal); }), + u->GetProperties().ips.afterChange([this](const auto& oldVal, const auto& newVal){ updateIPs(oldVal, newVal); }) + ); } //----------------------------------------------------------------------------- void PING::UnSetUserNotifiers(UserPtr u) { -// --- CurrIP --- -HAS_USER IsContainsUserCurrIP(u); -HAS_USER IsContainsUserIP(u); - -std::list::iterator currIPter; -std::list::iterator IPIter; - -currIPter = find_if(ChgCurrIPNotifierList.begin(), - ChgCurrIPNotifierList.end(), - IsContainsUserCurrIP); - -if (currIPter != ChgCurrIPNotifierList.end()) - { - currIPter->GetUser()->DelCurrIPAfterNotifier(&(*currIPter)); - ChgCurrIPNotifierList.erase(currIPter); - } -// --- CurrIP end --- - -// --- IP --- -IPIter = find_if(ChgIPNotifierList.begin(), - ChgIPNotifierList.end(), - IsContainsUserIP); - -if (IPIter != ChgIPNotifierList.end()) - { - IPIter->GetUser()->GetProperties().ips.DelAfterNotifier(&(*IPIter)); - ChgIPNotifierList.erase(IPIter); - } -// --- IP end --- + m_conns.erase(std::remove_if(m_conns.begin(), m_conns.end(), + [u](const auto& c){ return std::get<0>(c) == u->GetID(); }), + m_conns.end()); } //----------------------------------------------------------------------------- void PING::GetUsers() @@ -289,18 +243,18 @@ while (users_iter != usersList.end()) } } //----------------------------------------------------------------------------- -void CHG_CURRIP_NOTIFIER_PING::notify(const uint32_t & oldIP, const uint32_t & newIP) +void PING::updateCurrIP(uint32_t oldVal, uint32_t newVal) { -ping.pinger.DelIP(oldIP); -if (newIP != 0) - ping.pinger.AddIP(newIP); + pinger.DelIP(oldVal); + if (newVal != 0) + pinger.AddIP(newVal); } //----------------------------------------------------------------------------- -void CHG_IPS_NOTIFIER_PING::notify(const STG::UserIPs & oldIPS, const STG::UserIPs & newIPS) +void PING::updateIPs(const UserIPs& oldVal, const UserIPs& newVal) { -if (oldIPS.onlyOneIP()) - ping.pinger.DelIP(oldIPS[0].ip); + if (oldVal.onlyOneIP()) + pinger.DelIP(oldVal[0].ip); -if (newIPS.onlyOneIP()) - ping.pinger.AddIP(newIPS[0].ip); + if (newVal.onlyOneIP()) + pinger.AddIP(newVal[0].ip); } diff --git a/projects/stargazer/plugins/other/ping/ping.h b/projects/stargazer/plugins/other/ping/ping.h index 68d79794..aaa2988a 100644 --- a/projects/stargazer/plugins/other/ping/ping.h +++ b/projects/stargazer/plugins/other/ping/ping.h @@ -2,7 +2,6 @@ #include "stg/plugin.h" #include "stg/module_settings.h" -#include "stg/notifer.h" #include "stg/subscriptions.h" #include "stg/user_ips.h" #include "stg/pinger.h" @@ -10,6 +9,8 @@ #include "stg/logger.h" #include +#include +#include #include #include #pragma GCC diagnostic push @@ -18,103 +19,77 @@ #pragma GCC diagnostic pop #include -class PING; - namespace STG { struct USER; struct SETTINGS; -} - -using UserPtr = STG::User*; -//-----------------------------------------------------------------------------*/ -class CHG_CURRIP_NOTIFIER_PING: public STG::PropertyNotifierBase { -public: - CHG_CURRIP_NOTIFIER_PING(const PING & p, UserPtr u) - : user(u), ping(p) {} - void notify(const uint32_t & oldIP, const uint32_t & newIP) override; - UserPtr GetUser() const { return user; } -private: - CHG_CURRIP_NOTIFIER_PING & operator=(const CHG_CURRIP_NOTIFIER_PING &); - - UserPtr user; - const PING & ping; -}; -//----------------------------------------------------------------------------- -class CHG_IPS_NOTIFIER_PING: public STG::PropertyNotifierBase { -public: - CHG_IPS_NOTIFIER_PING(const PING & p, UserPtr u) - : user(u), ping(p) {} - void notify(const STG::UserIPs & oldIPS, const STG::UserIPs & newIPS) override; - UserPtr GetUser() const { return user; } - -private: - CHG_IPS_NOTIFIER_PING & operator=(const CHG_IPS_NOTIFIER_PING &); - - UserPtr user; - const PING & ping; -}; +using UserPtr = User*; //----------------------------------------------------------------------------- -class PING_SETTINGS { -public: - PING_SETTINGS() : pingDelay(0) {} - const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const STG::ModuleSettings & s); - int GetPingDelay() const { return pingDelay; } -private: - int pingDelay; - mutable std::string errorStr; +class PING_SETTINGS +{ + public: + PING_SETTINGS() : pingDelay(0) {} + const std::string & GetStrError() const { return errorStr; } + int ParseSettings(const ModuleSettings & s); + int GetPingDelay() const { return pingDelay; } + private: + int pingDelay; + std::string errorStr; }; //----------------------------------------------------------------------------- -class PING : public STG::Plugin { -friend class CHG_CURRIP_NOTIFIER_PING; -friend class CHG_IPS_NOTIFIER_PING; -public: - PING(); - - void SetUsers(STG::Users * u) override { users = u; } - void SetSettings(const STG::ModuleSettings & s) override { settings = s; } - int ParseSettings() override; - - int Start() override; - int Stop() override; - int Reload(const STG::ModuleSettings & /*ms*/) override { return 0; } - bool IsRunning() override; - - const std::string & GetStrError() const override { return errorStr; } - std::string GetVersion() const override { return "Pinger v.1.01"; } - uint16_t GetStartPosition() const override { return 10; } - uint16_t GetStopPosition() const override { return 10; } - - void AddUser(UserPtr u); - void DelUser(UserPtr u); - -private: - explicit PING(const PING & rvalue); - PING & operator=(const PING & rvalue); - - void GetUsers(); - void SetUserNotifiers(UserPtr u); - void UnSetUserNotifiers(UserPtr u); - void Run(std::stop_token token); - - mutable std::string errorStr; - PING_SETTINGS pingSettings; - STG::ModuleSettings settings; - STG::Users * users; - std::list usersList; - - std::jthread m_thread; - std::mutex m_mutex; - bool isRunning; - mutable STG_PINGER pinger; - - std::list ChgCurrIPNotifierList; - std::list ChgIPNotifierList; - - STG::ScopedConnection m_onAddUserConn; - STG::ScopedConnection m_onDelUserConn; - - STG::PluginLogger logger; +class PING : public Plugin +{ + public: + PING(); + + void SetUsers(Users * u) override { users = u; } + void SetSettings(const ModuleSettings & s) override { settings = s; } + int ParseSettings() override; + + int Start() override; + int Stop() override; + int Reload(const ModuleSettings & /*ms*/) override { return 0; } + bool IsRunning() override; + + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return "Pinger v.1.01"; } + uint16_t GetStartPosition() const override { return 10; } + uint16_t GetStopPosition() const override { return 10; } + + void AddUser(UserPtr u); + void DelUser(UserPtr u); + + private: + explicit PING(const PING & rvalue); + PING & operator=(const PING & rvalue); + + void GetUsers(); + void SetUserNotifiers(UserPtr u); + void UnSetUserNotifiers(UserPtr u); + void Run(std::stop_token token); + + mutable std::string errorStr; + PING_SETTINGS pingSettings; + ModuleSettings settings; + Users * users; + std::list usersList; + + std::jthread m_thread; + std::mutex m_mutex; + bool isRunning; + mutable STG_PINGER pinger; + + void updateCurrIP(uint32_t oldVal, uint32_t newVal); + void updateIPs(const UserIPs& oldVal, const UserIPs& newVal); + + ScopedConnection m_onAddUserConn; + ScopedConnection m_onDelUserConn; + + using ConnHolder = std::tuple; + std::vector m_conns; + + PluginLogger logger; }; + +} diff --git a/projects/stargazer/plugins/other/rscript/rscript.cpp b/projects/stargazer/plugins/other/rscript/rscript.cpp index f8dc9d99..36e84be8 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.cpp +++ b/projects/stargazer/plugins/other/rscript/rscript.cpp @@ -45,21 +45,9 @@ extern volatile time_t stgTime; +namespace RS = STG::RS; using RS::REMOTE_SCRIPT; -namespace { - -template -struct USER_IS -{ - explicit USER_IS(RS::UserPtr u) : user(u) {} - bool operator()(const T & notifier) { return notifier.GetUser() == user; } - - RS::UserPtr user; -}; - -} // namespace anonymous - extern "C" STG::Plugin* GetPlugin() { static REMOTE_SCRIPT plugin; @@ -74,10 +62,10 @@ RS::SETTINGS::SETTINGS() { } //----------------------------------------------------------------------------- -int RS::SETTINGS::ParseSettings(const STG::ModuleSettings & s) +int RS::SETTINGS::ParseSettings(const ModuleSettings & s) { int p; -STG::ParamValue pv; +ParamValue pv; netRouters.clear(); /////////////////////////// pv.param = "Port"; @@ -147,7 +135,7 @@ NRMapParser nrMapParser; if (!nrMapParser.ReadFile(subnetFile)) netRouters = nrMapParser.GetMap(); else - STG::PluginLogger::get("rscript")("mod_rscript: error opening subnets file '%s'", subnetFile.c_str()); + PluginLogger::get("rscript")("mod_rscript: error opening subnets file '%s'", subnetFile.c_str()); return 0; } @@ -160,7 +148,7 @@ REMOTE_SCRIPT::REMOTE_SCRIPT() isRunning(false), users(nullptr), sock(0), - logger(STG::PluginLogger::get("rscript")) + logger(PluginLogger::get("rscript")) { } //----------------------------------------------------------------------------- @@ -223,10 +211,10 @@ if (!IsRunning()) m_thread.request_stop(); std::for_each( - authorizedUsers.begin(), - authorizedUsers.end(), - DisconnectUser(*this) - ); + authorizedUsers.begin(), + authorizedUsers.end(), + [this](auto& kv){ Send(kv.second, true); } +); FinalizeNet(); @@ -251,7 +239,7 @@ else return 0; } //----------------------------------------------------------------------------- -int REMOTE_SCRIPT::Reload(const STG::ModuleSettings & /*ms*/) +int REMOTE_SCRIPT::Reload(const ModuleSettings & /*ms*/) { NRMapParser nrMapParser; @@ -469,20 +457,18 @@ return {}; //----------------------------------------------------------------------------- void REMOTE_SCRIPT::SetUserNotifiers(UserPtr u) { -ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u)); -connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u)); + m_conns.emplace_back( + u->GetID(), + u->afterCurrIPChange([this, u](auto, auto newVal){ addDelUser(u, newVal != 0); }), + u->afterConnectedChange([this, u](auto, auto newVal){ addDelUser(u, newVal); }) + ); } //----------------------------------------------------------------------------- void REMOTE_SCRIPT::UnSetUserNotifiers(UserPtr u) { -ipNotifierList.erase(std::remove_if(ipNotifierList.begin(), - ipNotifierList.end(), - USER_IS(u)), - ipNotifierList.end()); -connNotifierList.erase(std::remove_if(connNotifierList.begin(), - connNotifierList.end(), - USER_IS(u)), - connNotifierList.end()); + m_conns.erase(std::remove_if(m_conns.begin(), m_conns.end(), + [u](const auto& c){ return std::get<0>(c) == u->GetID(); }), + m_conns.end()); } //----------------------------------------------------------------------------- @@ -517,20 +503,12 @@ if (it != authorizedUsers.end()) }*/ } //----------------------------------------------------------------------------- -void RS::IP_NOTIFIER::notify(const uint32_t & /*oldValue*/, const uint32_t & newValue) +void REMOTE_SCRIPT::addDelUser(UserPtr user, bool toAdd) { -if (newValue != 0) - rs.AddRSU(user); -else - rs.DelRSU(user); -} -//----------------------------------------------------------------------------- -void RS::CONNECTED_NOTIFIER::notify(const bool & /*oldValue*/, const bool & newValue) -{ -if (newValue) - rs.AddRSU(user); -else - rs.DelRSU(user); + if (toAdd) + AddRSU(user); + else + DelRSU(user); } //----------------------------------------------------------------------------- void REMOTE_SCRIPT::InitEncrypt(const std::string & password) const diff --git a/projects/stargazer/plugins/other/rscript/rscript.h b/projects/stargazer/plugins/other/rscript/rscript.h index d0bf1e7e..a27e2eff 100644 --- a/projects/stargazer/plugins/other/rscript/rscript.h +++ b/projects/stargazer/plugins/other/rscript/rscript.h @@ -24,7 +24,6 @@ #include "stg/plugin.h" #include "stg/module_settings.h" #include "stg/subscriptions.h" -#include "stg/notifer.h" #include "stg/user.h" #include "stg/blowfish.h" #include "stg/rs_packets.h" @@ -48,69 +47,16 @@ namespace STG { struct Settings; struct Settings; -} namespace RS { -class REMOTE_SCRIPT; +using UserPtr = User*; class UpdateRouter; -class DisconnectUser; - -using UserPtr = STG::User*; - -//----------------------------------------------------------------------------- -class IP_NOTIFIER: public STG::PropertyNotifierBase { -public: - IP_NOTIFIER(REMOTE_SCRIPT & r, UserPtr u) - : user(u), rs(r) { user->AddCurrIPAfterNotifier(this); } - IP_NOTIFIER(const IP_NOTIFIER & rhs) - : user(rhs.user), rs(rhs.rs) { user->AddCurrIPAfterNotifier(this); } - ~IP_NOTIFIER() { user->DelCurrIPAfterNotifier(this); } - - IP_NOTIFIER & operator=(const IP_NOTIFIER & rhs) - { - user->DelCurrIPAfterNotifier(this); - user = rhs.user; - user->AddCurrIPAfterNotifier(this); - return *this; - } - - void notify(const uint32_t & oldValue, const uint32_t & newValue) override; - UserPtr GetUser() const { return user; } - -private: - - UserPtr user; - REMOTE_SCRIPT & rs; -}; -//----------------------------------------------------------------------------- -class CONNECTED_NOTIFIER: public STG::PropertyNotifierBase { -public: - CONNECTED_NOTIFIER(REMOTE_SCRIPT & r, UserPtr u) - : user(u), rs(r) { user->AddConnectedAfterNotifier(this); } - CONNECTED_NOTIFIER(const CONNECTED_NOTIFIER & rhs) - : user(rhs.user), rs(rhs.rs) { user->AddConnectedAfterNotifier(this); } - ~CONNECTED_NOTIFIER() { user->DelConnectedAfterNotifier(this); } - - CONNECTED_NOTIFIER & operator=(const CONNECTED_NOTIFIER & rhs) - { - user->DelConnectedAfterNotifier(this); - user = rhs.user; - user->AddConnectedAfterNotifier(this); - return *this; - } - - void notify(const bool & oldValue, const bool & newValue) override; - UserPtr GetUser() const { return user; } - -private: - UserPtr user; - REMOTE_SCRIPT & rs; -}; //----------------------------------------------------------------------------- -struct USER { +struct USER +{ USER(const std::vector & r, UserPtr it) : lastSentTime(0), user(it), @@ -126,118 +72,110 @@ struct USER { uint32_t ip; }; //----------------------------------------------------------------------------- -class SETTINGS { -public: - SETTINGS(); - virtual ~SETTINGS() {} - const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const STG::ModuleSettings & s); - int GetSendPeriod() const { return sendPeriod; } - uint16_t GetPort() const { return port; } - const std::vector & GetSubnetsMap() const { return netRouters; } - const std::vector & GetUserParams() const { return userParams; } - const std::string & GetPassword() const { return password; } - const std::string & GetMapFileName() const { return subnetFile; } - -private: - int sendPeriod; - uint16_t port; - std::string errorStr; - std::vector netRouters; - std::vector userParams; - std::string password; - std::string subnetFile; +class SETTINGS +{ + public: + SETTINGS(); + virtual ~SETTINGS() {} + const std::string & GetStrError() const { return errorStr; } + int ParseSettings(const ModuleSettings & s); + int GetSendPeriod() const { return sendPeriod; } + uint16_t GetPort() const { return port; } + const std::vector & GetSubnetsMap() const { return netRouters; } + const std::vector & GetUserParams() const { return userParams; } + const std::string & GetPassword() const { return password; } + const std::string & GetMapFileName() const { return subnetFile; } + + private: + int sendPeriod; + uint16_t port; + std::string errorStr; + std::vector netRouters; + std::vector userParams; + std::string password; + std::string subnetFile; }; //----------------------------------------------------------------------------- -class REMOTE_SCRIPT : public STG::Plugin { -public: - REMOTE_SCRIPT(); +class REMOTE_SCRIPT : public Plugin +{ + public: + REMOTE_SCRIPT(); + + void SetUsers(Users * u) override { users = u; } + void SetSettings(const ModuleSettings & s) override { settings = s; } + int ParseSettings() override; - void SetUsers(STG::Users * u) override { users = u; } - void SetSettings(const STG::ModuleSettings & s) override { settings = s; } - int ParseSettings() override; + int Start() override; + int Stop() override; + int Reload(const ModuleSettings & ms) override; + bool IsRunning() override { return isRunning; } - int Start() override; - int Stop() override; - int Reload(const STG::ModuleSettings & ms) override; - bool IsRunning() override { return isRunning; } + const std::string & GetStrError() const override { return errorStr; } + std::string GetVersion() const override { return "Remote script v 0.3"; } + uint16_t GetStartPosition() const override { return 10; } + uint16_t GetStopPosition() const override { return 10; } - const std::string & GetStrError() const override { return errorStr; } - std::string GetVersion() const override { return "Remote script v 0.3"; } - uint16_t GetStartPosition() const override { return 10; } - uint16_t GetStopPosition() const override { return 10; } + void DelUser(UserPtr u) { UnSetUserNotifiers(u); } + void AddUser(UserPtr u) { SetUserNotifiers(u); } - void DelUser(UserPtr u) { UnSetUserNotifiers(u); } - void AddUser(UserPtr u) { SetUserNotifiers(u); } + void AddRSU(UserPtr user); + void DelRSU(UserPtr user); - void AddRSU(UserPtr user); - void DelRSU(UserPtr user); + private: + REMOTE_SCRIPT(const REMOTE_SCRIPT & rhs); + REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rhs); -private: - REMOTE_SCRIPT(const REMOTE_SCRIPT & rhs); - REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rhs); + void Run(std::stop_token token); + bool PrepareNet(); + bool FinalizeNet(); - void Run(std::stop_token token); - bool PrepareNet(); - bool FinalizeNet(); + bool Send(USER & rsu, bool forceDisconnect = false) const; + bool SendDirect(USER & rsu, uint32_t routerIP, bool forceDisconnect = false) const; + bool PreparePacket(char * buf, size_t bufSize, USER &rsu, bool forceDisconnect = false) const; + void PeriodicSend(); - bool Send(USER & rsu, bool forceDisconnect = false) const; - bool SendDirect(USER & rsu, uint32_t routerIP, bool forceDisconnect = false) const; - bool PreparePacket(char * buf, size_t bufSize, USER &rsu, bool forceDisconnect = false) const; - void PeriodicSend(); + std::vector IP2Routers(uint32_t ip); + bool GetUsers(); - std::vector IP2Routers(uint32_t ip); - bool GetUsers(); + void SetUserNotifiers(UserPtr u); + void UnSetUserNotifiers(UserPtr u); - void SetUserNotifiers(UserPtr u); - void UnSetUserNotifiers(UserPtr u); + void InitEncrypt(const std::string & password) const; + void Encrypt(void * dst, const void * src, size_t len8) const; - void InitEncrypt(const std::string & password) const; - void Encrypt(void * dst, const void * src, size_t len8) const; + mutable BLOWFISH_CTX ctx; + std::map authorizedUsers; - mutable BLOWFISH_CTX ctx; + mutable std::string errorStr; + SETTINGS rsSettings; + ModuleSettings settings; + int sendPeriod; + int halfPeriod; - std::list ipNotifierList; - std::list connNotifierList; - std::map authorizedUsers; + bool isRunning; - mutable std::string errorStr; - SETTINGS rsSettings; - STG::ModuleSettings settings; - int sendPeriod; - int halfPeriod; + Users * users; - bool isRunning; + std::vector netRouters; - STG::Users * users; + std::jthread m_thread; + std::mutex m_mutex; - std::vector netRouters; + int sock; - std::jthread m_thread; - std::mutex m_mutex; + ScopedConnection m_onAddUserConn; + ScopedConnection m_onDelUserConn; - int sock; + void addDelUser(UserPtr user, bool toAdd); - STG::ScopedConnection m_onAddUserConn; - STG::ScopedConnection m_onDelUserConn; + using ConnHolder = std::tuple; + std::vector m_conns; - STG::PluginLogger logger; + PluginLogger logger; - friend class RS::UpdateRouter; - friend class RS::DisconnectUser; - friend class RS::CONNECTED_NOTIFIER; -}; -//----------------------------------------------------------------------------- -class DisconnectUser : public std::unary_function &, void> { - public: - explicit DisconnectUser(REMOTE_SCRIPT & rs) : rscript(rs) {} - void operator()(std::pair & p) - { - rscript.Send(p.second, true); - } - private: - REMOTE_SCRIPT & rscript; + friend class RS::UpdateRouter; }; //----------------------------------------------------------------------------- } // namespace RS +} diff --git a/projects/stargazer/plugins/other/rscript/ur_functor.h b/projects/stargazer/plugins/other/rscript/ur_functor.h index 95b03ea2..a4addc83 100644 --- a/projects/stargazer/plugins/other/rscript/ur_functor.h +++ b/projects/stargazer/plugins/other/rscript/ur_functor.h @@ -18,8 +18,7 @@ * Author : Maxim Mamontov */ -#ifndef __UR_FUNCTOR_H__ -#define __UR_FUNCTOR_H__ +#pragma once #include "rscript.h" @@ -30,60 +29,58 @@ #include #include -namespace RS +namespace STG::RS { class UpdateRouter : public std::unary_function, void> { -public: - explicit UpdateRouter(REMOTE_SCRIPT & t) - : obj(t) {} + public: + explicit UpdateRouter(REMOTE_SCRIPT & t) + : obj(t) {} - void operator() (std::pair & val) - { - std::vector newRouters = obj.IP2Routers(val.second.ip); - std::vector::const_iterator oldIt(val.second.routers.begin()); - std::vector::const_iterator newIt(newRouters.begin()); - val.second.shortPacketsCount = 0; - while (oldIt != val.second.routers.end() || - newIt != newRouters.end()) + void operator() (std::pair & val) { - if (oldIt == val.second.routers.end()) + std::vector newRouters = obj.IP2Routers(val.second.ip); + std::vector::const_iterator oldIt(val.second.routers.begin()); + std::vector::const_iterator newIt(newRouters.begin()); + val.second.shortPacketsCount = 0; + while (oldIt != val.second.routers.end() || + newIt != newRouters.end()) { - if (newIt != newRouters.end()) + if (oldIt == val.second.routers.end()) + { + if (newIt != newRouters.end()) + { + obj.SendDirect(val.second, *newIt); // Connect on new router + ++newIt; + } + } + else if (newIt == newRouters.end()) + { + obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router + ++oldIt; + } + else if (*oldIt < *newIt) + { + obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router + ++oldIt; + } + else if (*oldIt > *newIt) { obj.SendDirect(val.second, *newIt); // Connect on new router ++newIt; } + else + { + ++oldIt; + if (newIt != newRouters.end()) + ++newIt; + } } - else if (newIt == newRouters.end()) - { - obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router - ++oldIt; - } - else if (*oldIt < *newIt) - { - obj.SendDirect(val.second, *oldIt, true); // Disconnect on old router - ++oldIt; - } - else if (*oldIt > *newIt) - { - obj.SendDirect(val.second, *newIt); // Connect on new router - ++newIt; - } - else - { - ++oldIt; - if (newIt != newRouters.end()) - ++newIt; - } + val.second.routers = newRouters; } - val.second.routers = newRouters; - } -private: - REMOTE_SCRIPT & obj; + private: + REMOTE_SCRIPT & obj; }; } // namespace RS - -#endif diff --git a/projects/stargazer/plugins/other/smux/handlers.cpp b/projects/stargazer/plugins/other/smux/handlers.cpp index ac179da9..cce188c8 100644 --- a/projects/stargazer/plugins/other/smux/handlers.cpp +++ b/projects/stargazer/plugins/other/smux/handlers.cpp @@ -10,6 +10,8 @@ #include "utils.h" #include "smux.h" +using STG::SMUX; + #ifdef SMUX_DEBUG bool SMUX::CloseHandler(const SMUX_PDUs_t * pdus) { diff --git a/projects/stargazer/plugins/other/smux/smux.cpp b/projects/stargazer/plugins/other/smux/smux.cpp index 07f9d200..59d93105 100644 --- a/projects/stargazer/plugins/other/smux/smux.cpp +++ b/projects/stargazer/plugins/other/smux/smux.cpp @@ -19,6 +19,9 @@ #include "smux.h" #include "utils.h" +using STG::SMUX; +using STG::SMUX_SETTINGS; + namespace { @@ -41,9 +44,9 @@ SMUX_SETTINGS::SMUX_SETTINGS() port(0) {} -int SMUX_SETTINGS::ParseSettings(const STG::ModuleSettings & s) +int SMUX_SETTINGS::ParseSettings(const ModuleSettings & s) { -STG::ParamValue pv; +ParamValue pv; int p; pv.param = "Port"; @@ -100,7 +103,7 @@ SMUX::SMUX() lastReconnectTry(0), reconnectTimeout(1), sock(-1), - logger(STG::PluginLogger::get("smux")) + logger(PluginLogger::get("smux")) { smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler; smuxHandlers[SMUX_PDUs_PR_registerResponse] = &SMUX::RegisterResponseHandler; @@ -226,7 +229,7 @@ printfd(__FILE__, "SMUX::Stop() - After\n"); return 0; } -int SMUX::Reload(const STG::ModuleSettings & /*ms*/) +int SMUX::Reload(const ModuleSettings & /*ms*/) { if (Stop() != 0) return -1; @@ -411,23 +414,17 @@ return true; void SMUX::SetNotifier(UserPtr userPtr) { -notifiers.emplace_back(*this, userPtr); -userPtr->GetProperties().tariffName.AddAfterNotifier(¬ifiers.back()); + m_conns.emplace_back( + userPtr->GetID(), + userPtr->GetProperties().tariffName.afterChange([this](const auto&, const auto&){ UpdateTables(); }) + ); } void SMUX::UnsetNotifier(UserPtr userPtr) { -auto it = notifiers.begin(); -while (it != notifiers.end()) - { - if (it->GetUserPtr() == userPtr) - { - userPtr->GetProperties().tariffName.DelAfterNotifier(&(*it)); - notifiers.erase(it); - break; - } - ++it; - } + m_conns.erase(std::remove_if(m_conns.begin(), m_conns.end(), + [userPtr](const auto& c){ return std::get<0>(c) == userPtr->GetID(); }), + m_conns.end()); } void SMUX::SetNotifiers() @@ -450,7 +447,7 @@ m_onDelUserConn = users->onDel([this](auto user){ UpdateTables(); }); -auto updateTables = [this](const STG::TariffData&){ UpdateTables(); }; +auto updateTables = [this](const TariffData&){ UpdateTables(); }; m_onAddTariffConn = tariffs->onAdd(updateTables); m_onDelTariffConn = tariffs->onDel(updateTables); } @@ -463,11 +460,5 @@ m_onDelTariffConn.disconnect(); m_onAddUserConn.disconnect(); m_onDelUserConn.disconnect(); -auto it = notifiers.begin(); -while (it != notifiers.end()) - { - it->GetUserPtr()->GetProperties().tariffName.DelAfterNotifier(&(*it)); - ++it; - } -notifiers.clear(); +m_conns.clear(); } diff --git a/projects/stargazer/plugins/other/smux/smux.h b/projects/stargazer/plugins/other/smux/smux.h index 3e708e2b..bb62c7c0 100644 --- a/projects/stargazer/plugins/other/smux/smux.h +++ b/projects/stargazer/plugins/other/smux/smux.h @@ -10,7 +10,6 @@ #include "stg/plugin.h" #include "stg/module_settings.h" #include "stg/subscriptions.h" -#include "stg/notifer.h" #include "stg/noncopyable.h" #include "stg/logger.h" @@ -33,7 +32,6 @@ struct Tariffs; struct Services; struct Corporations; struct TraffCounter; -} class SMUX; @@ -42,135 +40,115 @@ typedef bool (SMUX::*PDUsHandler)(const PDUs_t * pdus); typedef std::map SMUXHandlers; typedef std::map PDUsHandlers; -using UserPtr = STG::User*; -//----------------------------------------------------------------------------- -class SMUX_SETTINGS { -public: - SMUX_SETTINGS(); - virtual ~SMUX_SETTINGS() {} - const std::string & GetStrError() const { return errorStr; } - int ParseSettings(const STG::ModuleSettings & s); - - uint32_t GetIP() const { return ip; } - uint16_t GetPort() const { return port; } - const std::string GetPassword() const { return password; } - -private: - mutable std::string errorStr; - - uint32_t ip; - uint16_t port; - std::string password; -}; +using UserPtr = User*; //----------------------------------------------------------------------------- -class CHG_AFTER_NOTIFIER : public STG::PropertyNotifierBase { -public: - CHG_AFTER_NOTIFIER(SMUX & s, const UserPtr & u) - : STG::PropertyNotifierBase(), - smux(s), userPtr(u) {} - CHG_AFTER_NOTIFIER(const CHG_AFTER_NOTIFIER & rvalue) - : STG::PropertyNotifierBase(), - smux(rvalue.smux), userPtr(rvalue.userPtr) {} - void notify(const std::string &, const std::string &) override; - - UserPtr GetUserPtr() const { return userPtr; } - -private: - CHG_AFTER_NOTIFIER & operator=(const CHG_AFTER_NOTIFIER & rvalue); - SMUX & smux; - UserPtr userPtr; +class SMUX_SETTINGS +{ + public: + SMUX_SETTINGS(); + virtual ~SMUX_SETTINGS() {} + const std::string & GetStrError() const { return errorStr; } + int ParseSettings(const ModuleSettings & s); + + uint32_t GetIP() const { return ip; } + uint16_t GetPort() const { return port; } + const std::string GetPassword() const { return password; } + + private: + mutable std::string errorStr; + + uint32_t ip; + uint16_t port; + std::string password; }; //----------------------------------------------------------------------------- -class SMUX : public STG::Plugin { -public: - SMUX(); - virtual ~SMUX(); - - void SetUsers(STG::Users * u) { users = u; } - void SetTariffs(STG::Tariffs * t) { tariffs = t; } - void SetAdmins(STG::Admins * a) { admins = a; } - void SetServices(STG::Services * s) { services = s; } - void SetTraffcounter(STG::TraffCounter * tc) { traffcounter = tc; } - void SetCorporations(STG::Corporations * c) { corporations = c; } - void SetSettings(const STG::ModuleSettings & s) { settings = s; } - int ParseSettings(); - - int Start(); - int Stop(); - int Reload(const STG::ModuleSettings & ms); - bool IsRunning() { return m_thread.joinable() && !stopped; } - - const std::string & GetStrError() const { return errorStr; } - std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; } - uint16_t GetStartPosition() const { return 10; } - uint16_t GetStopPosition() const { return 10; } - - bool UpdateTables(); - - void SetNotifier(UserPtr userPtr); - void UnsetNotifier(UserPtr userPtr); - -private: - SMUX(const SMUX & rvalue); - SMUX & operator=(const SMUX & rvalue); - - void Run(std::stop_token token); - bool PrepareNet(); - bool Reconnect(); - - bool DispatchPDUs(const SMUX_PDUs_t * pdus); - - bool CloseHandler(const SMUX_PDUs_t * pdus); - bool RegisterResponseHandler(const SMUX_PDUs_t * pdus); - bool PDUsRequestHandler(const SMUX_PDUs_t * pdus); - bool CommitOrRollbackHandler(const SMUX_PDUs_t * pdus); - - bool GetRequestHandler(const PDUs_t * pdus); - bool GetNextRequestHandler(const PDUs_t * pdus); - bool SetRequestHandler(const PDUs_t * pdus); - - void SetNotifiers(); - void ResetNotifiers(); - - STG::Users * users; - STG::Tariffs * tariffs; - STG::Admins * admins; - STG::Services * services; - STG::Corporations * corporations; - STG::TraffCounter * traffcounter; - - mutable std::string errorStr; - SMUX_SETTINGS smuxSettings; - STG::ModuleSettings settings; - - std::jthread m_thread; - std::mutex m_mutex; - bool stopped; - bool needReconnect; - - time_t lastReconnectTry; - unsigned reconnectTimeout; - - int sock; - - SMUXHandlers smuxHandlers; - PDUsHandlers pdusHandlers; - Sensors sensors; - Tables tables; - - STG::ScopedConnection m_onAddUserConn; - STG::ScopedConnection m_onDelUserConn; - STG::ScopedConnection m_onAddTariffConn; - STG::ScopedConnection m_onDelTariffConn; - - std::list notifiers; - - STG::PluginLogger logger; +class SMUX : public Plugin +{ + public: + SMUX(); + virtual ~SMUX(); + + void SetUsers(Users * u) { users = u; } + void SetTariffs(Tariffs * t) { tariffs = t; } + void SetAdmins(Admins * a) { admins = a; } + void SetServices(Services * s) { services = s; } + void SetTraffcounter(TraffCounter * tc) { traffcounter = tc; } + void SetCorporations(Corporations * c) { corporations = c; } + void SetSettings(const ModuleSettings & s) { settings = s; } + int ParseSettings(); + + int Start(); + int Stop(); + int Reload(const ModuleSettings & ms); + bool IsRunning() { return m_thread.joinable() && !stopped; } + + const std::string & GetStrError() const { return errorStr; } + std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; } + uint16_t GetStartPosition() const { return 10; } + uint16_t GetStopPosition() const { return 10; } + + bool UpdateTables(); + + void SetNotifier(UserPtr userPtr); + void UnsetNotifier(UserPtr userPtr); + + private: + SMUX(const SMUX & rvalue); + SMUX & operator=(const SMUX & rvalue); + + void Run(std::stop_token token); + bool PrepareNet(); + bool Reconnect(); + + bool DispatchPDUs(const SMUX_PDUs_t * pdus); + + bool CloseHandler(const SMUX_PDUs_t * pdus); + bool RegisterResponseHandler(const SMUX_PDUs_t * pdus); + bool PDUsRequestHandler(const SMUX_PDUs_t * pdus); + bool CommitOrRollbackHandler(const SMUX_PDUs_t * pdus); + + bool GetRequestHandler(const PDUs_t * pdus); + bool GetNextRequestHandler(const PDUs_t * pdus); + bool SetRequestHandler(const PDUs_t * pdus); + + void SetNotifiers(); + void ResetNotifiers(); + + Users * users; + Tariffs * tariffs; + Admins * admins; + Services * services; + Corporations * corporations; + TraffCounter * traffcounter; + + mutable std::string errorStr; + SMUX_SETTINGS smuxSettings; + ModuleSettings settings; + + std::jthread m_thread; + std::mutex m_mutex; + bool stopped; + bool needReconnect; + + time_t lastReconnectTry; + unsigned reconnectTimeout; + + int sock; + + SMUXHandlers smuxHandlers; + PDUsHandlers pdusHandlers; + Sensors sensors; + Tables tables; + + ScopedConnection m_onAddUserConn; + ScopedConnection m_onDelUserConn; + ScopedConnection m_onAddTariffConn; + ScopedConnection m_onDelTariffConn; + + using ConnHolder = std::tuple; + std::vector m_conns; + + PluginLogger logger; }; -//----------------------------------------------------------------------------- -inline -void CHG_AFTER_NOTIFIER::notify(const std::string &, const std::string &) -{ -smux.UpdateTables(); } diff --git a/projects/stargazer/traffcounter_impl.cpp b/projects/stargazer/traffcounter_impl.cpp index 44f2e558..a4227497 100644 --- a/projects/stargazer/traffcounter_impl.cpp +++ b/projects/stargazer/traffcounter_impl.cpp @@ -51,8 +51,6 @@ #define REMOVE_TIME (31) using STG::TraffCounterImpl; -using STG::TRF_IP_BEFORE; -using STG::TRF_IP_AFTER; namespace AsyncPoolST = STG::AsyncPoolST; @@ -82,8 +80,7 @@ m_onAddUserConn = users->onImplAdd([this](auto user){ AsyncPoolST::enqueue([this, user](){ SetUserNotifiers(user); }); }); m_onDelUserConn = users->onImplDel([this](auto user){ - AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); }); - AsyncPoolST::enqueue([this, user](){ DelUser(user->GetCurrIP()); }); + AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); DelUser(user->GetCurrIP()); }); }); } //----------------------------------------------------------------------------- @@ -128,10 +125,7 @@ m_thread.request_stop(); int h = users->OpenSearch(); assert(h && "USERS::OpenSearch is always correct"); -UserImpl * u; -while (users->SearchNext(h, &u) == 0) - UnSetUserNotifiers(u); -users->CloseSearch(h); +m_onIPConns.clear(); //5 seconds to thread stops itself struct timespec ts = {0, 200000000}; @@ -446,47 +440,22 @@ while (pi.first != pi.second) ip2packets.erase(pi.first, pi.second); } //----------------------------------------------------------------------------- -void TraffCounterImpl::SetUserNotifiers(UserImpl * user) +void TraffCounterImpl::SetUserNotifiers(UserImpl* user) { -// Adding user. Adding notifiers to user. -TRF_IP_BEFORE ipBNotifier(*this, user); -ipBeforeNotifiers.push_front(ipBNotifier); -user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin())); - -TRF_IP_AFTER ipANotifier(*this, user); -ipAfterNotifiers.push_front(ipANotifier); -user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin())); + // Adding user. Adding notifiers to user. + m_onIPConns.emplace_back( + user->GetID(), + user->beforeCurrIPChange([this](auto oldVal, auto /*newVal*/){ beforeIPChange(oldVal); }), + user->afterCurrIPChange([this, user](auto /*oldVal*/, auto newVal){ afterIPChange(user, newVal); }) + ); } //----------------------------------------------------------------------------- void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user) { -// Removing user. Removing notifiers from user. -std::list::iterator bi; -std::list::iterator ai; - -bi = ipBeforeNotifiers.begin(); -while (bi != ipBeforeNotifiers.end()) - { - if (user->GetLogin() == bi->GetUser()->GetLogin()) - { - user->DelCurrIPBeforeNotifier(&(*bi)); - ipBeforeNotifiers.erase(bi); - break; - } - ++bi; - } - -ai = ipAfterNotifiers.begin(); -while (ai != ipAfterNotifiers.end()) - { - if (user->GetLogin() == ai->GetUser()->GetLogin()) - { - user->DelCurrIPAfterNotifier(&(*ai)); - ipAfterNotifiers.erase(ai); - break; - } - ++ai; - } + // Removing user. Removing notifiers from user. + m_onIPConns.erase(std::remove_if(m_onIPConns.begin(), m_onIPConns.end(), + [user](const auto& cs){ return std::get<0>(cs) == user->GetID(); }), + m_onIPConns.end()); } //----------------------------------------------------------------------------- void TraffCounterImpl::DeterminateDir(const RawPacket & packet, @@ -851,21 +820,21 @@ monitorDir = dir; monitoring = !monitorDir.empty(); } //----------------------------------------------------------------------------- -void TRF_IP_BEFORE::notify(const uint32_t & oldValue, const uint32_t &) +void TraffCounterImpl::beforeIPChange(uint32_t oldVal) { -// User changes his address. Remove old IP -if (!oldValue) - return; + // User changes his address. Remove old IP + if (!oldVal) + return; -AsyncPoolST::enqueue([this, oldValue](){ traffCnt.DelUser(oldValue); }); + AsyncPoolST::enqueue([this, oldVal](){ DelUser(oldVal); }); } //----------------------------------------------------------------------------- -void TRF_IP_AFTER::notify(const uint32_t &, const uint32_t & newValue) +void TraffCounterImpl::afterIPChange(UserImpl* user, uint32_t newVal) { -// User changes his address. Add new IP -if (!newValue) - return; + // User changes his address. Add new IP + if (!newVal) + return; -AsyncPoolST::enqueue([this](){ traffCnt.AddUser(user); }); + AsyncPoolST::enqueue([this, user](){ AddUser(user); }); } //----------------------------------------------------------------------------- diff --git a/projects/stargazer/traffcounter_impl.h b/projects/stargazer/traffcounter_impl.h index 474b6694..03c118df 100644 --- a/projects/stargazer/traffcounter_impl.h +++ b/projects/stargazer/traffcounter_impl.h @@ -24,11 +24,11 @@ #include "stg/logger.h" #include "stg/raw_ip_packet.h" #include "stg/subscriptions.h" -#include "stg/notifer.h" #include "user_impl.h" -#include #include +#include +#include #include #include #include @@ -37,6 +37,7 @@ #include #pragma GCC diagnostic pop #include +#include #define PROTOMAX (5) @@ -81,58 +82,7 @@ struct PacketExtraData { uint32_t lenD; // Download length }; //----------------------------------------------------------------------------- -class TraffCounterImpl; -//----------------------------------------------------------------------------- -class TRF_IP_BEFORE: public PropertyNotifierBase { -public: - TRF_IP_BEFORE(TraffCounterImpl & t, UserImpl * u) - : PropertyNotifierBase(), - traffCnt(t), - user(u) - {} - TRF_IP_BEFORE(const TRF_IP_BEFORE & rvalue) - : PropertyNotifierBase(), - traffCnt(rvalue.traffCnt), - user(rvalue.user) - {} - void notify(const uint32_t & oldValue, const uint32_t & newValue) override; - void SetUser(UserImpl * u) { user = u; } - UserImpl * GetUser() const { return user; } - -private: - TRF_IP_BEFORE & operator=(const TRF_IP_BEFORE & rvalue); - - TraffCounterImpl & traffCnt; - UserImpl * user; -}; -//----------------------------------------------------------------------------- -class TRF_IP_AFTER: public PropertyNotifierBase { -public: - TRF_IP_AFTER(TraffCounterImpl & t, UserImpl * u) - : PropertyNotifierBase(), - traffCnt(t), - user(u) - {} - TRF_IP_AFTER(const TRF_IP_AFTER & rvalue) - : PropertyNotifierBase(), - traffCnt(rvalue.traffCnt), - user(rvalue.user) - {} - void notify(const uint32_t & oldValue, const uint32_t & newValue) override; - void SetUser(UserImpl * u) { user = u; } - UserImpl * GetUser() const { return user; } -private: - TRF_IP_AFTER & operator=(const TRF_IP_AFTER & rvalue); - - TraffCounterImpl & traffCnt; - UserImpl * user; -}; - -using UserImplPtr = UserImpl*; -//----------------------------------------------------------------------------- class TraffCounterImpl : public TraffCounter { - friend class TRF_IP_BEFORE; - friend class TRF_IP_AFTER; public: TraffCounterImpl(UsersImpl * users, const std::string & rulesFileName); ~TraffCounterImpl(); @@ -162,8 +112,8 @@ class TraffCounterImpl : public TraffCounter { void AddUser(UserImpl * user); void DelUser(uint32_t uip); - void SetUserNotifiers(UserImpl * user); - void UnSetUserNotifiers(UserImpl * user); + void SetUserNotifiers(UserImpl* user); + void UnSetUserNotifiers(UserImpl* user); typedef std::list::iterator rule_iter; @@ -197,8 +147,10 @@ class TraffCounterImpl : public TraffCounter { ScopedConnection m_onAddUserConn; ScopedConnection m_onDelUserConn; - std::list ipBeforeNotifiers; - std::list ipAfterNotifiers; + using OnIPConns = std::tuple; + std::vector m_onIPConns; + void beforeIPChange(uint32_t oldVal); + void afterIPChange(UserImpl* user, uint32_t newVal); }; } diff --git a/projects/stargazer/user_impl.cpp b/projects/stargazer/user_impl.cpp index 60e801b9..7116a11e 100644 --- a/projects/stargazer/user_impl.cpp +++ b/projects/stargazer/user_impl.cpp @@ -88,10 +88,6 @@ UserImpl::UserImpl(const Settings * s, WriteServLog(Logger::get()), lastScanMessages(0), id(0), - __connected(0), - connected(__connected), - __currIP(0), - currIP(__currIP), lastIPForDisconnect(0), pingTime(0), sysAdmin(a), @@ -139,14 +135,9 @@ UserImpl::UserImpl(const Settings * s, userdata8(properties.userdata8), userdata9(properties.userdata9), sessionUploadModTime(stgTime), - sessionDownloadModTime(stgTime), - passiveNotifier(this), - disabledNotifier(this), - tariffNotifier(this), - cashNotifier(this), - ipNotifier(this) + sessionDownloadModTime(stgTime) { -Init(); + Init(); } //----------------------------------------------------------------------------- void UserImpl::Init() @@ -158,11 +149,11 @@ ips = UserIPs::parse("*"); lastWriteStat = stgTime + random() % settings->GetStatWritePeriod(); lastWriteDetailedStat = stgTime; -properties.tariffName.AddBeforeNotifier(&tariffNotifier); -properties.passive.AddBeforeNotifier(&passiveNotifier); -properties.disabled.AddAfterNotifier(&disabledNotifier); -properties.cash.AddBeforeNotifier(&cashNotifier); -ips.AddAfterNotifier(&ipNotifier); +m_beforePassiveConn = properties.passive.beforeChange([this](auto oldVal, auto newVal){ onPassiveChange(oldVal, newVal); }); +m_afterDisabledConn = properties.disabled.afterChange([this](auto oldVal, auto newVal){ onDisabledChange(oldVal, newVal); }); +m_beforeTariffConn = properties.tariffName.beforeChange([this](const auto& oldVal, const auto& newVal){ onTariffChange(oldVal, newVal); }); +m_beforeCashConn = properties.cash.beforeChange([this](auto oldVal, auto newVal){ onCashChange(oldVal, newVal); }); +m_afterIPConn = ips.afterChange([this](const auto& oldVal, const auto& newVal){ onIPChange(oldVal, newVal); }); pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); @@ -177,10 +168,6 @@ UserImpl::UserImpl(const UserImpl & u) lastScanMessages(0), login(u.login), id(u.id), - __connected(0), - connected(__connected), - __currIP(u.__currIP), - currIP(__currIP), lastIPForDisconnect(0), pingTime(u.pingTime), sysAdmin(u.sysAdmin), @@ -233,36 +220,27 @@ UserImpl::UserImpl(const UserImpl & u) sessionUpload(), sessionDownload(), sessionUploadModTime(stgTime), - sessionDownloadModTime(stgTime), - passiveNotifier(this), - disabledNotifier(this), - tariffNotifier(this), - cashNotifier(this), - ipNotifier(this) + sessionDownloadModTime(stgTime) { -if (&u == this) - return; + if (&u == this) + return; -properties.tariffName.AddBeforeNotifier(&tariffNotifier); -properties.passive.AddBeforeNotifier(&passiveNotifier); -properties.disabled.AddAfterNotifier(&disabledNotifier); -properties.cash.AddBeforeNotifier(&cashNotifier); -ips.AddAfterNotifier(&ipNotifier); + m_beforePassiveConn = properties.passive.beforeChange([this](auto oldVal, auto newVal){ onPassiveChange(oldVal, newVal); }); + m_afterDisabledConn = properties.disabled.afterChange([this](auto oldVal, auto newVal){ onDisabledChange(oldVal, newVal); }); + m_beforeTariffConn = properties.tariffName.beforeChange([this](const auto& oldVal, const auto& newVal){ onTariffChange(oldVal, newVal); }); + m_beforeCashConn = properties.cash.beforeChange([this](auto oldVal, auto newVal){ onCashChange(oldVal, newVal); }); + m_afterIPConn = ips.afterChange([this](const auto& oldVal, const auto& newVal){ onIPChange(oldVal, newVal); }); -properties.SetProperties(u.properties); + properties.SetProperties(u.properties); -pthread_mutexattr_t attr; -pthread_mutexattr_init(&attr); -pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); -pthread_mutex_init(&mutex, &attr); + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&mutex, &attr); } //----------------------------------------------------------------------------- UserImpl::~UserImpl() { -properties.tariffName.DelBeforeNotifier(&tariffNotifier); -properties.passive.DelBeforeNotifier(&passiveNotifier); -properties.disabled.DelAfterNotifier(&disabledNotifier); -properties.cash.DelBeforeNotifier(&cashNotifier); pthread_mutex_destroy(&mutex); } //----------------------------------------------------------------------------- @@ -428,7 +406,7 @@ dirsFromBits(enabledDirs, dirs); if (!authorizedBy.empty()) { - if (currIP != ip) + if (m_currIP != ip) { // We are already authorized, but with different IP address errorStr = "User " + login + " already authorized with IP address " + inet_ntostring(ip); @@ -458,8 +436,8 @@ else if (ips.ConstData().find(ip)) { - currIP = ip; - lastIPForDisconnect = currIP; + m_currIP = ip; + lastIPForDisconnect = m_currIP; } else { @@ -492,9 +470,9 @@ authorizedModificationTime = stgTime; if (authorizedBy.empty()) { lastDisconnectReason = reason; - lastIPForDisconnect = currIP; - currIP = 0; // DelUser in traffcounter - if (connected) + lastIPForDisconnect = m_currIP; + m_currIP = 0; // DelUser in traffcounter + if (m_connected) Disconnect(false, "not authorized"); return; } @@ -536,7 +514,7 @@ if (!fakeConnect) "%s \"%s\" \"%s\" \"%f\" \"%d\" \"%s\"", scriptOnConnect.c_str(), login.c_str(), - inet_ntostring(currIP).c_str(), + inet_ntostring(m_currIP).c_str(), cash.ConstData(), id, dirs.c_str()); @@ -555,17 +533,17 @@ if (!fakeConnect) WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str()); } - connected = true; + m_connected = true; } -if (!settings->GetDisableSessionLog() && store->WriteUserConnect(login, currIP)) +if (!settings->GetDisableSessionLog() && store->WriteUserConnect(login, m_currIP)) { WriteServLog("Cannot write connect for user %s.", login.c_str()); WriteServLog("%s", store->GetStrError().c_str()); } if (!fakeConnect) - lastIPForDisconnect = currIP; + lastIPForDisconnect = m_currIP; } //----------------------------------------------------------------------------- void UserImpl::Disconnect(bool fakeDisconnect, const std::string & reason) @@ -615,7 +593,7 @@ if (!fakeDisconnect) WriteServLog("Script OnDisconnect cannot be executed. File not found."); } - connected = false; + m_connected = false; } std::string reasonMessage(reason); @@ -665,13 +643,13 @@ if (passive.ConstData() if (!authorizedBy.empty()) { - if (connected) + if (m_connected) properties.Stat().lastActivityTime = stgTime; - if (!connected && IsInetable()) + if (!m_connected && IsInetable()) Connect(); - if (connected && !IsInetable()) + if (m_connected && !IsInetable()) { if (disabled) Disconnect(false, "disabled"); @@ -689,7 +667,7 @@ if (!authorizedBy.empty()) } else { - if (connected) + if (m_connected) Disconnect(false, "not authorized"); } @@ -734,7 +712,7 @@ void UserImpl::AddTraffStatU(int dir, uint32_t ip, uint32_t len) { STG_LOCKER lock(&mutex); -if (!connected || tariff == NULL) +if (!m_connected || tariff == NULL) return; double cost = 0; @@ -827,7 +805,7 @@ void UserImpl::AddTraffStatD(int dir, uint32_t ip, uint32_t len) { STG_LOCKER lock(&mutex); -if (!connected || tariff == NULL) +if (!m_connected || tariff == NULL) return; double cost = 0; @@ -911,54 +889,6 @@ else } } //----------------------------------------------------------------------------- -void UserImpl::AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -currIP.AddBeforeNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -currIP.DelBeforeNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -currIP.AddAfterNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -currIP.DelAfterNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -connected.AddBeforeNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -connected.DelBeforeNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -connected.AddAfterNotifier(notifier); -} -//----------------------------------------------------------------------------- -void UserImpl::DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) -{ -STG_LOCKER lock(&mutex); -connected.DelAfterNotifier(notifier); -} -//----------------------------------------------------------------------------- void UserImpl::OnAdd() { STG_LOCKER lock(&mutex); @@ -1087,7 +1017,7 @@ void UserImpl::MidnightResetSessionStat() { STG_LOCKER lock(&mutex); -if (connected) +if (m_connected) { Disconnect(true, "fake"); Connect(true); @@ -1098,7 +1028,7 @@ void UserImpl::ProcessNewMonth() { STG_LOCKER lock(&mutex); // Reset traff -if (connected) +if (m_connected) Disconnect(true, "fake"); WriteMonthStat(); @@ -1106,7 +1036,7 @@ WriteMonthStat(); properties.Stat().monthUp.reset(); properties.Stat().monthDown.reset(); -if (connected) +if (m_connected) Connect(true); // Set new tariff @@ -1399,7 +1329,7 @@ int ret = -1; std::set::iterator it(authorizedBy.begin()); while (it != authorizedBy.end()) { - if (!(*it++)->SendMessage(msg, currIP)) + if (!(*it++)->SendMessage(msg, m_currIP)) ret = 0; } if (!ret) @@ -1479,7 +1409,7 @@ std::string UserImpl::GetParamValue(const std::string & name) const return stream.str(); } if (lowerName == "login") return login; - if (lowerName == "currip") return currIP.ToString(); + if (lowerName == "currip") return m_currIP.ToString(); if (lowerName == "enableddirs") return GetEnabledDirs(); if (lowerName == "tariff") return properties.tariffName; if (properties.Exists(lowerName)) @@ -1493,51 +1423,52 @@ std::string UserImpl::GetParamValue(const std::string & name) const //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- -void STG::CHG_PASSIVE_NOTIFIER::notify(const int & oldPassive, const int & newPassive) +void UserImpl::onPassiveChange(int oldVal, int newVal) { -if (newPassive && !oldPassive && user->tariff != NULL) - user->properties.cash.Set(user->cash - user->tariff->GetPassiveCost(), - *user->sysAdmin, - user->login, - *user->store, + if (newVal && !oldVal && tariff != NULL) + properties.cash.Set(cash - tariff->GetPassiveCost(), + *sysAdmin, + login, + *store, "Freeze"); } //----------------------------------------------------------------------------- -void STG::CHG_DISABLED_NOTIFIER::notify(const int & oldValue, const int & newValue) +void UserImpl::onDisabledChange(int oldVal, int newVal) { -if (oldValue && !newValue && user->GetConnected()) - user->Disconnect(false, "disabled"); -else if (!oldValue && newValue && user->IsInetable()) - user->Connect(false); + if (oldVal && !newVal && GetConnected()) + Disconnect(false, "disabled"); + else if (!oldVal && newVal && IsInetable()) + Connect(false); } //----------------------------------------------------------------------------- -void STG::CHG_TARIFF_NOTIFIER::notify(const std::string &, const std::string & newTariff) +void UserImpl::onTariffChange(const std::string& /*oldVal*/, const std::string& newVal) { -STG_LOCKER lock(&user->mutex); -if (user->settings->GetReconnectOnTariffChange() && user->connected) - user->Disconnect(false, "Change tariff"); -user->tariff = user->tariffs->FindByName(newTariff); -if (user->settings->GetReconnectOnTariffChange() && - !user->authorizedBy.empty() && - user->IsInetable()) + STG_LOCKER lock(&mutex); + if (settings->GetReconnectOnTariffChange() && m_connected) + Disconnect(false, "Change tariff"); + tariff = tariffs->FindByName(newVal); + if (settings->GetReconnectOnTariffChange() && + !authorizedBy.empty() && + IsInetable()) { - // This notifier gets called *before* changing the tariff, and in Connect we want to see new tariff name. - user->properties.Conf().tariffName = newTariff; - user->Connect(false); + // This notifier gets called *before* changing the tariff, and in Connect we want to see new tariff name. + properties.Conf().tariffName = newVal; + Connect(false); } } //----------------------------------------------------------------------------- -void STG::CHG_CASH_NOTIFIER::notify(const double & oldCash, const double & newCash) +void UserImpl::onCashChange(double oldVal, double newVal) { -user->lastCashAddTime = *const_cast(&stgTime); -user->lastCashAdd = newCash - oldCash; + time_t now = stgTime; + lastCashAddTime = now; + lastCashAdd = newVal - oldVal; } //----------------------------------------------------------------------------- -void STG::CHG_IPS_NOTIFIER::notify(const UserIPs & from, const UserIPs & to) +void UserImpl::onIPChange(const UserIPs& oldVal, const UserIPs& newVal) { -printfd(__FILE__, "Change IP from '%s' to '%s'\n", from.toString().c_str(), to.toString().c_str()); -if (user->connected) - user->Disconnect(false, "Change IP"); -if (!user->authorizedBy.empty() && user->IsInetable()) - user->Connect(false); + printfd(__FILE__, "Change IP from '%s' to '%s'\n", oldVal.toString().c_str(), newVal.toString().c_str()); + if (m_connected) + Disconnect(false, "Change IP"); + if (!authorizedBy.empty() && IsInetable()) + Connect(false); } diff --git a/projects/stargazer/user_impl.h b/projects/stargazer/user_impl.h index 4beeb2e2..ff7e28a0 100644 --- a/projects/stargazer/user_impl.h +++ b/projects/stargazer/user_impl.h @@ -51,57 +51,8 @@ struct Settings; class SettingsImpl; #endif //----------------------------------------------------------------------------- -class CHG_PASSIVE_NOTIFIER : public PropertyNotifierBase { - public: - explicit CHG_PASSIVE_NOTIFIER(UserImpl * u) : user(u) {} - void notify(const int & oldPassive, const int & newPassive) override; - - private: - UserImpl * user; -}; -//----------------------------------------------------------------------------- -class CHG_DISABLED_NOTIFIER : public PropertyNotifierBase { -public: - explicit CHG_DISABLED_NOTIFIER(UserImpl * u) : user(u) {} - void notify(const int & oldValue, const int & newValue) override; - -private: - UserImpl * user; -}; -//----------------------------------------------------------------------------- -class CHG_TARIFF_NOTIFIER : public PropertyNotifierBase { -public: - explicit CHG_TARIFF_NOTIFIER(UserImpl * u) : user(u) {} - void notify(const std::string & oldTariff, const std::string & newTariff) override; - -private: - UserImpl * user; -}; -//----------------------------------------------------------------------------- -class CHG_CASH_NOTIFIER : public PropertyNotifierBase { -public: - explicit CHG_CASH_NOTIFIER(UserImpl * u) : user(u) {} - void notify(const double & oldCash, const double & newCash) override; - -private: - UserImpl * user; -}; -//----------------------------------------------------------------------------- -class CHG_IPS_NOTIFIER : public PropertyNotifierBase { -public: - explicit CHG_IPS_NOTIFIER(UserImpl * u) : user(u) {} - void notify(const UserIPs & oldIPs, const UserIPs & newIPs) override; - -private: - UserImpl * user; -}; -//----------------------------------------------------------------------------- -class UserImpl : public User { - friend class CHG_PASSIVE_NOTIFIER; - friend class CHG_DISABLED_NOTIFIER; - friend class CHG_TARIFF_NOTIFIER; - friend class CHG_CASH_NOTIFIER; - friend class CHG_IPS_NOTIFIER; +class UserImpl : public User +{ public: #ifdef USE_ABSTRACT_SETTINGS using Settings = STG::Settings; @@ -126,21 +77,6 @@ class UserImpl : public User { const std::string & GetLogin() const override { return login; } void SetLogin(std::string const & l); - uint32_t GetCurrIP() const override{ return currIP; } - time_t GetCurrIPModificationTime() const override { return currIP.ModificationTime(); } - - void AddCurrIPBeforeNotifier(CURR_IP_NOTIFIER * notifier) override; - void DelCurrIPBeforeNotifier(const CURR_IP_NOTIFIER * notifier) override; - - void AddCurrIPAfterNotifier(CURR_IP_NOTIFIER * notifier) override; - void DelCurrIPAfterNotifier(const CURR_IP_NOTIFIER * notifier) override; - - void AddConnectedBeforeNotifier(CONNECTED_NOTIFIER * notifier) override; - void DelConnectedBeforeNotifier(const CONNECTED_NOTIFIER * notifier) override; - - void AddConnectedAfterNotifier(CONNECTED_NOTIFIER * notifier) override; - void DelConnectedAfterNotifier(const CONNECTED_NOTIFIER * notifier) override; - int GetID() const override { return id; } double GetPassiveTimePart() const override; @@ -165,8 +101,6 @@ class UserImpl : public User { time_t GetSessionUploadModificationTime() const override { return sessionUploadModTime; } time_t GetSessionDownloadModificationTime() const override { return sessionDownloadModTime; } - bool GetConnected() const override { return connected; } - time_t GetConnectedModificationTime() const override { return connected.ModificationTime(); } const std::string & GetLastDisconnectReason() const override { return lastDisconnectReason; } int GetAuthorized() const override { return static_cast(authorizedBy.size()); } time_t GetAuthorizedModificationTime() const override { return authorizedModificationTime; } @@ -230,14 +164,9 @@ class UserImpl : public User { std::string login; int id; - bool __connected; - UserProperty connected; bool enabledDirs[DIR_NUM]; - uint32_t __currIP; // Current user's ip - UserProperty currIP; - uint32_t lastIPForDisconnect; // User's ip after unauth but before disconnect std::string lastDisconnectReason; @@ -309,11 +238,20 @@ class UserImpl : public User { time_t sessionUploadModTime; time_t sessionDownloadModTime; - CHG_PASSIVE_NOTIFIER passiveNotifier; - CHG_DISABLED_NOTIFIER disabledNotifier; - CHG_TARIFF_NOTIFIER tariffNotifier; - CHG_CASH_NOTIFIER cashNotifier; - CHG_IPS_NOTIFIER ipNotifier; + ScopedConnection m_beforePassiveConn; + void onPassiveChange(int oldVal, int newVal); + + ScopedConnection m_afterDisabledConn; + void onDisabledChange(int oldVal, int newVal); + + ScopedConnection m_beforeTariffConn; + void onTariffChange(const std::string& oldVal, const std::string& newVal); + + ScopedConnection m_beforeCashConn; + void onCashChange(double oldVal, double newVal); + + ScopedConnection m_afterIPConn; + void onIPChange(const UserIPs& oldVal, const UserIPs& newVal); mutable pthread_mutex_t mutex; diff --git a/projects/stargazer/users_impl.h b/projects/stargazer/users_impl.h index 7b6f900a..d84dcb6e 100644 --- a/projects/stargazer/users_impl.h +++ b/projects/stargazer/users_impl.h @@ -20,7 +20,14 @@ #pragma once -#include +#include "settings_impl.h" +#include "user_impl.h" +#include "stg/store.h" +#include "stg/users.h" +#include "stg/user.h" +#include "stg/tariffs.h" +#include "stg/logger.h" +#include "stg/noncopyable.h" #include #include @@ -34,16 +41,6 @@ #include #include -#include "stg/store.h" -#include "stg/users.h" -#include "stg/user.h" -#include "stg/tariffs.h" -#include "stg/logger.h" -#include "stg/notifer.h" -#include "stg/noncopyable.h" -#include "settings_impl.h" -#include "user_impl.h" - namespace STG { diff --git a/tests/test_reconnect_on_tariff_change.cpp b/tests/test_reconnect_on_tariff_change.cpp index c47bc1fd..856c85d3 100644 --- a/tests/test_reconnect_on_tariff_change.cpp +++ b/tests/test_reconnect_on_tariff_change.cpp @@ -24,19 +24,19 @@ volatile time_t stgTime = 0; namespace { -class AfterConnectedNotifier : public STG::PropertyNotifierBase +class ConnectCtr { public: - AfterConnectedNotifier() + ConnectCtr() : m_connects(0), m_disconnects(0) {} - void notify(const bool& oldValue, const bool& newValue) override + void update(bool isConnect) { - if (!oldValue && newValue) + if (isConnect) ++m_connects; - if (oldValue && !newValue) + else ++m_disconnects; } @@ -77,9 +77,8 @@ BOOST_AUTO_TEST_CASE(NormalBehavior) TestServices services; STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - AfterConnectedNotifier connectionNotifier; - - user.AddConnectedAfterNotifier(&connectionNotifier); + ConnectCtr ctr; + STG::ScopedConnection conn = user.afterConnectedChange([&ctr](auto, auto newVal){ ctr.update(newVal); }); STG::UserProperty & tariffName = user.GetProperties().tariffName; STG::UserProperty & ips = user.GetProperties().ips; @@ -87,8 +86,8 @@ BOOST_AUTO_TEST_CASE(NormalBehavior) ips = STG::UserIPs::parse("*"); BOOST_CHECK_EQUAL(user.GetConnected(), false); - BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(0)); - BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.disconnects(), static_cast(0)); BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); @@ -98,8 +97,8 @@ BOOST_AUTO_TEST_CASE(NormalBehavior) BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); BOOST_CHECK_EQUAL(user.GetConnected(), true); - BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(1)); - BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(ctr.disconnects(), static_cast(0)); tariffName = "test"; BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); @@ -107,8 +106,8 @@ BOOST_AUTO_TEST_CASE(NormalBehavior) BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); BOOST_CHECK_EQUAL(user.GetConnected(), true); - BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(1)); - BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(ctr.disconnects(), static_cast(0)); } BOOST_AUTO_TEST_CASE(Reconnect) @@ -130,9 +129,8 @@ BOOST_AUTO_TEST_CASE(Reconnect) TestServices services; STG::UserImpl user(&settings, &store, &tariffs, &admin, &users, services); - AfterConnectedNotifier connectionNotifier; - - user.AddConnectedAfterNotifier(&connectionNotifier); + ConnectCtr ctr; + STG::ScopedConnection conn = user.afterConnectedChange([&ctr](auto, auto newVal){ ctr.update(newVal); }); STG::UserProperty & tariffName = user.GetProperties().tariffName; STG::UserProperty & ips = user.GetProperties().ips; @@ -140,8 +138,8 @@ BOOST_AUTO_TEST_CASE(Reconnect) ips = STG::UserIPs::parse("*"); BOOST_CHECK_EQUAL(user.GetConnected(), false); - BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(0)); - BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.connects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.disconnects(), static_cast(0)); BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), NO_TARIFF_NAME); @@ -151,8 +149,8 @@ BOOST_AUTO_TEST_CASE(Reconnect) BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); BOOST_CHECK_EQUAL(user.GetConnected(), true); - BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(1)); - BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(0)); + BOOST_CHECK_EQUAL(ctr.connects(), static_cast(1)); + BOOST_CHECK_EQUAL(ctr.disconnects(), static_cast(0)); tariffName = "test"; BOOST_CHECK_EQUAL(user.GetProperties().tariffName.ConstData(), "test"); @@ -160,8 +158,8 @@ BOOST_AUTO_TEST_CASE(Reconnect) BOOST_CHECK_EQUAL(user.IsAuthorizedBy(&auth), true); BOOST_CHECK_EQUAL(user.GetConnected(), true); - BOOST_CHECK_EQUAL(connectionNotifier.connects(), static_cast(2)); - BOOST_CHECK_EQUAL(connectionNotifier.disconnects(), static_cast(1)); + BOOST_CHECK_EQUAL(ctr.connects(), static_cast(2)); + BOOST_CHECK_EQUAL(ctr.disconnects(), static_cast(1)); } BOOST_AUTO_TEST_SUITE_END() -- 2.44.2 From b27841d687ec9e84983340b5581376dfb24010ea Mon Sep 17 00:00:00 2001 From: Maksym Mamontov Date: Sat, 27 Aug 2022 18:41:54 +0300 Subject: [PATCH 07/16] Fight CLang warnings. --- include/stg/corporations.h | 2 +- include/stg/plugin.h | 4 +- include/stg/services.h | 2 +- include/stg/tariffs.h | 2 +- include/stg/users.h | 4 +- libs/ia/ia.cpp | 589 +++++++------- libs/ia/include/stg/ia.h | 276 ++++--- libs/pinger/include/stg/pinger.h | 130 ++- libs/pinger/pinger.cpp | 157 ++-- libs/srvconf/include/stg/servconf.h | 2 +- libs/srvconf/netunit.cpp | 128 +-- libs/srvconf/netunit.h | 18 +- libs/srvconf/servconf.cpp | 154 ++-- projects/sgauth/web.cpp | 186 ++--- projects/sgauth/web.h | 72 +- projects/sgconf/options.cpp | 44 +- projects/sgconf/options.h | 48 +- projects/stargazer/admins_impl.h | 2 +- projects/stargazer/corps_impl.h | 2 +- projects/stargazer/plugin_runner.h | 4 +- .../stargazer/plugins/authorization/ao/ao.h | 4 +- .../plugins/capture/cap_nf/cap_nf.cpp | 4 +- .../stargazer/plugins/capture/cap_nf/cap_nf.h | 4 +- .../capture/divert_freebsd/divert_cap.h | 4 +- .../plugins/capture/ether_linux/ether_cap.h | 4 +- .../plugins/capture/nfqueue/nfqueue.h | 4 +- .../stargazer/plugins/capture/pcap/pcap_cap.h | 4 +- .../configuration/rpcconfig/info_methods.h | 4 +- .../rpcconfig/messages_methods.h | 2 +- .../configuration/rpcconfig/rpcconfig.h | 4 +- .../configuration/rpcconfig/tariffs_methods.h | 4 +- .../configuration/rpcconfig/user_helper.h | 8 +- .../configuration/rpcconfig/users_methods.h | 4 +- .../configuration/sgconfig/configproto.h | 4 +- .../plugins/configuration/sgconfig/conn.h | 6 +- .../plugins/configuration/sgconfig/parser.h | 2 +- .../configuration/sgconfig/parser_admins.h | 2 +- .../configuration/sgconfig/parser_auth_by.h | 4 +- .../configuration/sgconfig/parser_message.h | 4 +- .../sgconfig/parser_server_info.h | 6 +- .../configuration/sgconfig/parser_tariffs.h | 6 +- .../configuration/sgconfig/parser_user_info.h | 2 +- .../configuration/sgconfig/parser_users.h | 8 +- .../stargazer/plugins/other/smux/handlers.cpp | 13 +- .../stargazer/plugins/other/smux/sensors.cpp | 14 +- .../stargazer/plugins/other/smux/sensors.h | 42 +- .../stargazer/plugins/other/smux/smux.cpp | 22 +- projects/stargazer/plugins/other/smux/smux.h | 9 +- .../stargazer/plugins/other/smux/tables.cpp | 27 +- .../stargazer/plugins/other/smux/tables.h | 15 +- .../stargazer/plugins/other/smux/types.cpp | 4 +- projects/stargazer/plugins/other/smux/types.h | 15 +- .../stargazer/plugins/other/smux/utils.cpp | 20 +- projects/stargazer/plugins/other/smux/utils.h | 12 +- .../stargazer/plugins/other/smux/value2os.h | 27 +- .../plugins/store/files/file_store.cpp | 754 +++++++++--------- .../plugins/store/files/file_store.h | 334 ++++---- .../plugins/store/firebird/firebird_store.h | 180 +++-- .../store/firebird/firebird_store_admins.cpp | 15 +- .../store/firebird/firebird_store_users.cpp | 2 +- .../store/postgresql/postgresql_store.h | 229 +++--- .../postgresql/postgresql_store_tariffs.cpp | 2 +- projects/stargazer/services_impl.h | 2 +- projects/stargazer/tariffs_impl.cpp | 8 +- projects/stargazer/tariffs_impl.h | 2 +- projects/stargazer/user_impl.h | 4 +- projects/stargazer/users_impl.cpp | 2 +- projects/stargazer/users_impl.h | 4 - 68 files changed, 1831 insertions(+), 1851 deletions(-) diff --git a/include/stg/corporations.h b/include/stg/corporations.h index 944844c6..d5898fa7 100644 --- a/include/stg/corporations.h +++ b/include/stg/corporations.h @@ -25,7 +25,7 @@ namespace STG { -struct Admin; +class Admin; struct CorpConf; struct Corporations { diff --git a/include/stg/plugin.h b/include/stg/plugin.h index c638a2f5..9e0b362c 100644 --- a/include/stg/plugin.h +++ b/include/stg/plugin.h @@ -30,8 +30,8 @@ struct TraffCounter; struct Settings; struct Store; struct Admins; -struct Users; -struct Tariffs; +class Users; +class Tariffs; struct Services; struct Corporations; struct ModuleSettings; diff --git a/include/stg/services.h b/include/stg/services.h index 5d3b2bee..41c0cf54 100644 --- a/include/stg/services.h +++ b/include/stg/services.h @@ -25,7 +25,7 @@ namespace STG { -struct Admin; +class Admin; struct ServiceConf; struct ServiceConfOpt; diff --git a/include/stg/tariffs.h b/include/stg/tariffs.h index c47b857f..959c6112 100644 --- a/include/stg/tariffs.h +++ b/include/stg/tariffs.h @@ -28,7 +28,7 @@ namespace STG { -struct Admin; +class Admin; struct Tariff; struct TariffData; diff --git a/include/stg/users.h b/include/stg/users.h index 1587f350..a0be8493 100644 --- a/include/stg/users.h +++ b/include/stg/users.h @@ -29,8 +29,8 @@ namespace STG { -struct Admin; -struct User; +class Admin; +class User; struct Auth; class Users diff --git a/libs/ia/ia.cpp b/libs/ia/ia.cpp index a05d3061..bdfa67f1 100644 --- a/libs/ia/ia.cpp +++ b/libs/ia/ia.cpp @@ -29,6 +29,14 @@ //--------------------------------------------------------------------------- +#include "stg/common.h" +#include "stg/ia.h" + +#include +#include +#include +#include + #ifdef WIN32 #include #include @@ -42,14 +50,6 @@ #include #endif -#include -#include -#include -#include - -#include "stg/common.h" -#include "stg/ia.h" - #define IA_NONE (0) #define IA_CONNECT (1) #define IA_DISCONNECT (2) @@ -75,7 +75,7 @@ sigset_t signalSet; sigfillset(&signalSet); pthread_sigmask(SIG_BLOCK, &signalSet, NULL); -IA_CLIENT_PROT * c = (IA_CLIENT_PROT *)data; +auto* c = static_cast(data); static int a = 0; if (a == 0) @@ -101,7 +101,7 @@ return tv.tv_sec*1000 + tv.tv_usec/1000; //--------------------------------------------------------------------------- unsigned long WINAPI RunW(void * data) { -IA_CLIENT_PROT * c = (IA_CLIENT_PROT *)data; +auto* c = static_cast(data); while (c->GetNonstop()) c->Run(); return 0; @@ -120,7 +120,7 @@ if (ip == INADDR_NONE) hostent * phe = gethostbyname(hostName.c_str()); if (phe) { - ip = *((uint32_t *)phe->h_addr_list[0]); + ip = *reinterpret_cast(phe->h_addr_list[0]); } else { @@ -138,81 +138,79 @@ return true; //--------------------------------------------------------------------------- IA_CLIENT_PROT::IA_CLIENT_PROT(const std::string & sn, unsigned short p, const std::string & ln, uint16_t lp) - : action(IA_NONE), - phase(1), - phaseTime(0), - codeError(0), - nonstop(false), - isNetPrepared(false), - proxyMode(false), - serverName(sn), - port(p), - ip(0), - localName(ln), - localPort(lp), - firstConnect(true), - reconnect(0), - sockr(0), - protNum(0), - userTimeout(60), - aliveTimeout(5), - rnd(0), - pStatusChangedCb(NULL), - pStatChangedCb(NULL), - pInfoCb(NULL), - pErrorCb(NULL), - pDirNameCb(NULL), - statusChangedCbData(NULL), - statChangedCbData(NULL), - infoCbData(NULL), - errorCbData(NULL), - dirNameCbData(NULL), - connSyn8(NULL), - connSynAck8(NULL), - connAck8(NULL), - aliveSyn8(NULL), - aliveAck8(NULL), - disconnSyn8(NULL), - disconnSynAck8(NULL), - disconnAck8(NULL), - info(NULL) -{ -memset(&stat, 0, sizeof(stat)); + : m_action(IA_NONE), + m_phase(1), + m_phaseTime(0), + m_codeError(0), + m_nonstop(false), + m_isNetPrepared(false), + m_proxyMode(false), + m_serverName(sn), + m_port(p), + m_ip(0), + m_localName(ln), + m_localPort(lp), + m_firstConnect(true), + m_reconnect(0), + m_sockr(0), + m_protNum(0), + m_userTimeout(60), + m_aliveTimeout(5), + m_rnd(0), + m_pStatusChangedCb(NULL), + m_pStatChangedCb(NULL), + m_pInfoCb(NULL), + m_pErrorCb(NULL), + m_pDirNameCb(NULL), + m_statusChangedCbData(NULL), + m_statChangedCbData(NULL), + m_infoCbData(NULL), + m_errorCbData(NULL), + m_dirNameCbData(NULL), + m_connSyn8(NULL), + m_connSynAck8(NULL), + m_connAck8(NULL), + m_aliveSyn8(NULL), + m_aliveAck8(NULL), + m_disconnSyn8(NULL), + m_disconnSynAck8(NULL), + m_disconnAck8(NULL), + m_info(NULL) +{ +memset(&m_stat, 0, sizeof(m_stat)); #ifdef WIN32 -WSAStartup(MAKEWORD(2, 0), &wsaData); +WSAStartup(MAKEWORD(2, 0), &m_wsaData); #endif -packetTypes["CONN_SYN"] = CONN_SYN_N; -packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N; -packetTypes["CONN_ACK"] = CONN_ACK_N; -packetTypes["ALIVE_SYN"] = ALIVE_SYN_N; -packetTypes["ALIVE_ACK"] = ALIVE_ACK_N; -packetTypes["DISCONN_SYN"] = DISCONN_SYN_N; -packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N; -packetTypes["DISCONN_ACK"] = DISCONN_ACK_N; -packetTypes["FIN"] = FIN_N; -packetTypes["ERR"] = ERROR_N; -packetTypes["INFO"] = INFO_N; -packetTypes["INFO_7"] = INFO_7_N; -packetTypes["INFO_8"] = INFO_8_N; - -unsigned char key[IA_PASSWD_LEN]; +m_packetTypes["CONN_SYN"] = CONN_SYN_N; +m_packetTypes["CONN_SYN_ACK"] = CONN_SYN_ACK_N; +m_packetTypes["CONN_ACK"] = CONN_ACK_N; +m_packetTypes["ALIVE_SYN"] = ALIVE_SYN_N; +m_packetTypes["ALIVE_ACK"] = ALIVE_ACK_N; +m_packetTypes["DISCONN_SYN"] = DISCONN_SYN_N; +m_packetTypes["DISCONN_SYN_ACK"] = DISCONN_SYN_ACK_N; +m_packetTypes["DISCONN_ACK"] = DISCONN_ACK_N; +m_packetTypes["FIN"] = FIN_N; +m_packetTypes["ERR"] = ERROR_N; +m_packetTypes["INFO"] = INFO_N; +m_packetTypes["INFO_7"] = INFO_7_N; +m_packetTypes["INFO_8"] = INFO_8_N; + +char key[IA_PASSWD_LEN]; memset(key, 0, IA_PASSWD_LEN); -strncpy((char *)key, "pr7Hhen", 8); -Blowfish_Init(&ctxHdr, key, IA_PASSWD_LEN); +strncpy(key, "pr7Hhen", 8); +Blowfish_Init(&m_ctxHdr, key, IA_PASSWD_LEN); memset(key, 0, IA_PASSWD_LEN); -Blowfish_Init(&ctxPass, key, IA_PASSWD_LEN); +Blowfish_Init(&m_ctxPass, key, IA_PASSWD_LEN); for (size_t i = 0; i < DIR_NUM; ++i) - { - selectedDirs[i] = false; - } + m_selectedDirs[i] = false; -servAddr.sin_family = AF_INET; -servAddr.sin_port = htons(port); -servAddr.sin_addr.s_addr = ip; +m_servAddr.sin_family = AF_INET; +m_servAddr.sin_port = htons(m_port); +m_servAddr.sin_addr.s_addr = m_ip; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::PrepareNet() @@ -237,74 +235,74 @@ if (ip == INADDR_NONE) } }*/ -if (!HostNameToIP(serverName, ip)) +if (!HostNameToIP(m_serverName, m_ip)) { - ip = 0; - strError = std::string("Unknown host ") + "\'" + serverName + "\'"; - codeError = IA_GETHOSTBYNAME_ERROR; - if (pErrorCb != NULL) - pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData); + m_ip = 0; + m_strError = std::string("Unknown host ") + "\'" + m_serverName + "\'"; + m_codeError = IA_GETHOSTBYNAME_ERROR; + if (m_pErrorCb != NULL) + m_pErrorCb(m_strError, IA_GETHOSTBYNAME_ERROR, m_errorCbData); return; } #ifndef WIN32 -close(sockr); +close(m_sockr); #else -closesocket(sockr); +closesocket(m_sockr); #endif -sockr = socket(AF_INET, SOCK_DGRAM, 0); +m_sockr = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in localAddrR; localAddrR.sin_family = AF_INET; -if (localPort) - localAddrR.sin_port = htons(localPort); +if (m_localPort) + localAddrR.sin_port = htons(m_localPort); else - localAddrR.sin_port = htons(port); + localAddrR.sin_port = htons(m_port); -if (!localName.empty()) +if (!m_localName.empty()) { - if (!HostNameToIP(localName, localIP)) + if (!HostNameToIP(m_localName, m_localIP)) { - strError = std::string("Unknown host ") + "\'" + serverName + "\'"; - codeError = IA_GETHOSTBYNAME_ERROR; - if (pErrorCb != NULL) - pErrorCb(strError, IA_GETHOSTBYNAME_ERROR, errorCbData); - localIP = INADDR_ANY; + m_strError = std::string("Unknown host ") + "\'" + m_serverName + "\'"; + m_codeError = IA_GETHOSTBYNAME_ERROR; + if (m_pErrorCb != NULL) + m_pErrorCb(m_strError, IA_GETHOSTBYNAME_ERROR, m_errorCbData); + m_localIP = INADDR_ANY; } } else { - localIP = INADDR_ANY; + m_localIP = INADDR_ANY; } -localAddrR.sin_addr.s_addr = localIP; +localAddrR.sin_addr.s_addr = m_localIP; -servAddr.sin_family = AF_INET; -servAddr.sin_port = htons(port); -servAddr.sin_addr.s_addr = ip; +m_servAddr.sin_family = AF_INET; +m_servAddr.sin_port = htons(m_port); +m_servAddr.sin_addr.s_addr = m_ip; -int res = bind(sockr, (struct sockaddr*)&localAddrR, sizeof(localAddrR)); +int res = bind(m_sockr, reinterpret_cast(&localAddrR), sizeof(localAddrR)); if (res == -1) { - strError = "bind error"; - codeError = IA_BIND_ERROR; - if (pErrorCb != NULL) - pErrorCb(strError, IA_BIND_ERROR, errorCbData); + m_strError = "bind error"; + m_codeError = IA_BIND_ERROR; + if (m_pErrorCb != NULL) + m_pErrorCb(m_strError, IA_BIND_ERROR, m_errorCbData); return; } #ifdef WIN32 unsigned long arg = 1; -ioctlsocket(sockr, FIONBIO, &arg); +ioctlsocket(m_sockr, FIONBIO, &arg); #else -if (0 != fcntl(sockr, F_SETFL, O_NONBLOCK)) +if (0 != fcntl(m_sockr, F_SETFL, O_NONBLOCK)) { - strError = "fcntl error"; - codeError = IA_FCNTL_ERROR; - if (pErrorCb != NULL) - pErrorCb(strError, IA_FCNTL_ERROR, errorCbData); + m_strError = "fcntl error"; + m_codeError = IA_FCNTL_ERROR; + if (m_pErrorCb != NULL) + m_pErrorCb(m_strError, IA_FCNTL_ERROR, m_errorCbData); } #endif @@ -313,9 +311,9 @@ if (0 != fcntl(sockr, F_SETFL, O_NONBLOCK)) IA_CLIENT_PROT::~IA_CLIENT_PROT() { #ifndef WIN32 -close(sockr); +close(m_sockr); #else -closesocket(sockr); +closesocket(m_sockr); WSACleanup(); #endif } @@ -323,8 +321,8 @@ WSACleanup(); int IA_CLIENT_PROT::DeterminatePacketType(const char * buffer) { std::map::iterator pi; -pi = packetTypes.find(buffer); -if (pi == packetTypes.end()) +pi = m_packetTypes.find(buffer); +if (pi == m_packetTypes.end()) { return -1; } @@ -334,30 +332,30 @@ else } } //--------------------------------------------------------------------------- -void IA_CLIENT_PROT::FillHdr8(char * buffer, unsigned long) +void IA_CLIENT_PROT::FillHdr8(char* buffer, unsigned long) { strncpy(buffer, IA_ID, 6); buffer[IA_MAGIC_LEN] = 0; buffer[IA_MAGIC_LEN + 1] = IA_PROTO_VER; -strncpy(buffer + sizeof(HDR_8), login.c_str(), IA_LOGIN_LEN); +strncpy(buffer + sizeof(HDR_8), m_login.c_str(), IA_LOGIN_LEN); } //--------------------------------------------------------------------------- int IA_CLIENT_PROT::Send(char * buffer, int len) { -if (!isNetPrepared) +if (!m_isNetPrepared) { PrepareNet(); - isNetPrepared = true; + m_isNetPrepared = true; } int db = sizeof(HDR_8); -EncryptString(buffer + db, buffer + db, IA_LOGIN_LEN, &ctxHdr); +EncryptString(buffer + db, buffer + db, IA_LOGIN_LEN, &m_ctxHdr); db += IA_LOGIN_LEN; int encLen = (len - sizeof(HDR_8) - IA_LOGIN_LEN); -EncryptString(buffer + db, buffer + db, encLen, &ctxPass); +EncryptString(buffer + db, buffer + db, encLen, &m_ctxPass); -return sendto(sockr, buffer, len, 0, (struct sockaddr*)&servAddr, sizeof(servAddr)); +return sendto(m_sockr, buffer, len, 0, reinterpret_cast(&m_servAddr), sizeof(m_servAddr)); } //--------------------------------------------------------------------------- int IA_CLIENT_PROT::Recv(char * buffer, int len) @@ -370,13 +368,13 @@ socklen_t fromLen; struct sockaddr_in addr; fromLen = sizeof(addr); -int res = recvfrom(sockr, buffer, len, 0, (struct sockaddr*)&addr, &fromLen); +int res = recvfrom(m_sockr, buffer, len, 0, reinterpret_cast(&addr), &fromLen); if (res == -1) return res; if (strcmp(buffer + 4 + sizeof(HDR_8), "ERR")) - DecryptString(buffer, buffer, len, &ctxPass); + DecryptString(buffer, buffer, len, &m_ctxPass); return 0; } @@ -467,113 +465,113 @@ return ret; //--------------------------------------------------------------------------- void IA_CLIENT_PROT::Start() { -nonstop = true; +m_nonstop = true; #ifdef WIN32 unsigned long pt; CreateThread(NULL, 16384, RunW, this, 0, &pt); #else -pthread_create(&thread, NULL, RunL, this); +pthread_create(&m_thread, NULL, RunL, this); #endif } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::Stop() { -nonstop = false; +m_nonstop = false; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::Run() { NetRecv(); -switch (phase) +switch (m_phase) { case 1: - if (action == IA_CONNECT) + if (m_action == IA_CONNECT) { - action = IA_NONE; + m_action = IA_NONE; NetSend(CONN_SYN_N); - phase = 2; - phaseTime = GetTickCount(); + m_phase = 2; + m_phaseTime = GetTickCount(); } - if (reconnect && !firstConnect) + if (m_reconnect && !m_firstConnect) { - action = IA_CONNECT; + m_action = IA_CONNECT; } break; case 2: - if ((int)(GetTickCount() - phaseTime)/1000 > aliveTimeout) + if (static_cast(GetTickCount() - m_phaseTime)/1000 > m_aliveTimeout) { - phase = 1; - phaseTime = GetTickCount(); - if (pStatusChangedCb != NULL) - pStatusChangedCb(0, statusChangedCbData); + m_phase = 1; + m_phaseTime = GetTickCount(); + if (m_pStatusChangedCb != NULL) + m_pStatusChangedCb(0, m_statusChangedCbData); } - if (action == IA_DISCONNECT) + if (m_action == IA_DISCONNECT) { - action = IA_NONE; + m_action = IA_NONE; NetSend(DISCONN_SYN_N); - phase = 4; - phaseTime = GetTickCount(); + m_phase = 4; + m_phaseTime = GetTickCount(); } break; case 3: - if ((int)(GetTickCount() - phaseTime)/1000 > userTimeout) + if (static_cast(GetTickCount() - m_phaseTime)/1000 > m_userTimeout) { - phase = 1; - phaseTime = GetTickCount(); - if (pStatusChangedCb != NULL) - pStatusChangedCb(0, statusChangedCbData); - firstConnect = false; + m_phase = 1; + m_phaseTime = GetTickCount(); + if (m_pStatusChangedCb != NULL) + m_pStatusChangedCb(0, m_statusChangedCbData); + m_firstConnect = false; } - if (action == IA_DISCONNECT) + if (m_action == IA_DISCONNECT) { - action = IA_NONE; + m_action = IA_NONE; NetSend(DISCONN_SYN_N); - phase = 4; - phaseTime = GetTickCount(); + m_phase = 4; + m_phaseTime = GetTickCount(); } break; case 4: - if ((int)(GetTickCount() - phaseTime)/1000 > aliveTimeout) + if (static_cast(GetTickCount() - m_phaseTime)/1000 > m_aliveTimeout) { - phase=1; - phaseTime = GetTickCount(); - if (pStatusChangedCb != NULL) - pStatusChangedCb(0, statusChangedCbData); + m_phase=1; + m_phaseTime = GetTickCount(); + if (m_pStatusChangedCb != NULL) + m_pStatusChangedCb(0, m_statusChangedCbData); } - if (action == IA_CONNECT) + if (m_action == IA_CONNECT) { - action = IA_NONE; + m_action = IA_NONE; NetSend(CONN_SYN_N); - phase = 2; - phaseTime = GetTickCount(); + m_phase = 2; + m_phaseTime = GetTickCount(); } break; case 5: - if ((int)(GetTickCount() - phaseTime)/1000 > aliveTimeout) + if (static_cast(GetTickCount() - m_phaseTime)/1000 > m_aliveTimeout) { - phase = 1; - phaseTime = GetTickCount(); - if (pStatusChangedCb != NULL) - pStatusChangedCb(0, statusChangedCbData); + m_phase = 1; + m_phaseTime = GetTickCount(); + if (m_pStatusChangedCb != NULL) + m_pStatusChangedCb(0, m_statusChangedCbData); } - if (action == IA_CONNECT) + if (m_action == IA_CONNECT) { - action = IA_NONE; + m_action = IA_NONE; NetSend(CONN_SYN_N); - phase = 2; - phaseTime = GetTickCount(); + m_phase = 2; + m_phaseTime = GetTickCount(); } break; @@ -584,164 +582,162 @@ return; //--------------------------------------------------------------------------- void IA_CLIENT_PROT::GetStat(LOADSTAT * ls) { -memcpy(ls, &stat, sizeof(stat)); +memcpy(ls, &m_stat, sizeof(m_stat)); } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetServer(const std::string & sn, unsigned short p) { -serverName = sn; -port = p; +m_serverName = sn; +m_port = p; PrepareNet(); } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetLogin(const std::string & l) { -login = l; +m_login = l; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetPassword(const std::string & p) { -password = p; +m_password = p; -unsigned char keyL[IA_PASSWD_LEN]; +char keyL[IA_PASSWD_LEN]; memset(keyL, 0, IA_PASSWD_LEN); -strncpy((char *)keyL, password.c_str(), IA_PASSWD_LEN); -Blowfish_Init(&ctxPass, keyL, IA_PASSWD_LEN); +strncpy(keyL, m_password.c_str(), IA_PASSWD_LEN); +Blowfish_Init(&m_ctxPass, keyL, IA_PASSWD_LEN); } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetEnabledDirs(const bool * selectedDirs) { -memcpy(IA_CLIENT_PROT::selectedDirs, selectedDirs, sizeof(bool) * DIR_NUM); +memcpy(m_selectedDirs, selectedDirs, sizeof(bool) * DIR_NUM); } //--------------------------------------------------------------------------- int IA_CLIENT_PROT::Connect() { -action = IA_CONNECT; +m_action = IA_CONNECT; return 0; } //--------------------------------------------------------------------------- int IA_CLIENT_PROT::Disconnect() { -firstConnect = true; -action = IA_DISCONNECT; +m_firstConnect = true; +m_action = IA_DISCONNECT; return 0; } //--------------------------------------------------------------------------- int IA_CLIENT_PROT::GetStrError(std::string * error) const { -int ret = codeError; -*error = strError; -strError = ""; -codeError = 0; +int ret = m_codeError; +*error = m_strError; +m_strError = ""; +m_codeError = 0; return ret; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Process_CONN_SYN_ACK_8(const char * buffer) +int IA_CLIENT_PROT::Process_CONN_SYN_ACK_8(const void* buffer) { std::vector dirNames; -connSynAck8 = (CONN_SYN_ACK_8*)buffer; +m_connSynAck8 = static_cast(buffer); #ifdef ARCH_BE -SwapBytes(connSynAck8->len); -SwapBytes(connSynAck8->rnd); -SwapBytes(connSynAck8->userTimeOut); -SwapBytes(connSynAck8->aliveDelay); +SwapBytes(m_connSynAck8->len); +SwapBytes(m_connSynAck8->rnd); +SwapBytes(m_connSynAck8->userTimeOut); +SwapBytes(m_connSynAck8->aliveDelay); #endif -rnd = connSynAck8->rnd; -userTimeout = connSynAck8->userTimeOut; -aliveTimeout = connSynAck8->aliveDelay; +m_rnd = m_connSynAck8->rnd; +m_userTimeout = m_connSynAck8->userTimeOut; +m_aliveTimeout = m_connSynAck8->aliveDelay; for (int i = 0; i < DIR_NUM; i++) - { - dirNames.push_back((const char*)connSynAck8->dirName[i]); - } + dirNames.push_back(reinterpret_cast(m_connSynAck8->dirName[i])); -if (pDirNameCb != NULL) - pDirNameCb(dirNames, dirNameCbData); +if (m_pDirNameCb != NULL) + m_pDirNameCb(dirNames, m_dirNameCbData); NetSend(CONN_ACK_N); -phase = 3; -phaseTime = GetTickCount(); +m_phase = 3; +m_phaseTime = GetTickCount(); return CONN_SYN_ACK_N; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Process_ALIVE_SYN_8(const char * buffer) +int IA_CLIENT_PROT::Process_ALIVE_SYN_8(const void* buffer) { -aliveSyn8 = (ALIVE_SYN_8*)buffer; +m_aliveSyn8 = static_cast(buffer); #ifdef ARCH_BE -SwapBytes(aliveSyn8->len); -SwapBytes(aliveSyn8->rnd); -SwapBytes(aliveSyn8->cash); -SwapBytes(aliveSyn8->status); +SwapBytes(m_aliveSyn8->len); +SwapBytes(m_aliveSyn8->rnd); +SwapBytes(m_aliveSyn8->cash); +SwapBytes(m_aliveSyn8->status); for (int i = 0; i < DIR_NUM; ++i) { - SwapBytes(aliveSyn8->mu[i]); - SwapBytes(aliveSyn8->md[i]); - SwapBytes(aliveSyn8->su[i]); - SwapBytes(aliveSyn8->sd[i]); + SwapBytes(m_aliveSyn8->mu[i]); + SwapBytes(m_aliveSyn8->md[i]); + SwapBytes(m_aliveSyn8->su[i]); + SwapBytes(m_aliveSyn8->sd[i]); } #endif -rnd = aliveSyn8->rnd; -memcpy(&stat, (char*)aliveSyn8->mu, sizeof(stat)); +m_rnd = m_aliveSyn8->rnd; +memcpy(&m_stat, m_aliveSyn8->mu, sizeof(m_stat)); -if (pStatChangedCb != NULL) - pStatChangedCb(stat, statChangedCbData); +if (m_pStatChangedCb != NULL) + m_pStatChangedCb(m_stat, m_statChangedCbData); -if (pStatusChangedCb != NULL) - pStatusChangedCb(1, statusChangedCbData); +if (m_pStatusChangedCb != NULL) + m_pStatusChangedCb(1, m_statusChangedCbData); NetSend(ALIVE_ACK_N); -phaseTime = GetTickCount(); +m_phaseTime = GetTickCount(); return ALIVE_SYN_N; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Process_DISCONN_SYN_ACK_8(const char * buffer) +int IA_CLIENT_PROT::Process_DISCONN_SYN_ACK_8(const void* buffer) { -disconnSynAck8 = (DISCONN_SYN_ACK_8*)buffer; +m_disconnSynAck8 = static_cast(buffer); #ifdef ARCH_BE -SwapBytes(disconnSynAck8->len); -SwapBytes(disconnSynAck8->rnd); +SwapBytes(m_disconnSynAck8->len); +SwapBytes(m_disconnSynAck8->rnd); #endif -rnd = disconnSynAck8->rnd; +m_rnd = m_disconnSynAck8->rnd; NetSend(DISCONN_ACK_N); -phase = 5; -phaseTime = GetTickCount(); +m_phase = 5; +m_phaseTime = GetTickCount(); return DISCONN_SYN_ACK_N; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Process_FIN_8(const char *) +int IA_CLIENT_PROT::Process_FIN_8(const void*) { -phase = 1; -phaseTime = GetTickCount(); -if (pStatusChangedCb != NULL) - pStatusChangedCb(0, statusChangedCbData); +m_phase = 1; +m_phaseTime = GetTickCount(); +if (m_pStatusChangedCb != NULL) + m_pStatusChangedCb(0, m_statusChangedCbData); return FIN_N; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Process_INFO_8(const char * buffer) +int IA_CLIENT_PROT::Process_INFO_8(const void* buffer) { -info = (INFO_8*)buffer; +m_info = static_cast(buffer); #ifdef ARCH_BE -SwapBytes(info->len); -SwapBytes(info->sendTime); +SwapBytes(m_info->len); +SwapBytes(m_info->sendTime); #endif -if (pInfoCb != NULL) - pInfoCb((char*)info->text, info->infoType, info->showTime, info->sendTime, infoCbData); +if (m_pInfoCb != NULL) + m_pInfoCb(reinterpret_cast(m_info->text), m_info->infoType, m_info->showTime, m_info->sendTime, m_infoCbData); return INFO_8_N; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Process_ERROR(const char * buffer) +int IA_CLIENT_PROT::Process_ERROR(const void* buffer) { ERR_8 err; memcpy(&err, buffer, sizeof(err)); @@ -750,142 +746,139 @@ memcpy(&err, buffer, sizeof(err)); SwapBytes(err.len); #endif -KOIToWin((const char*)err.text, &messageText); -if (pErrorCb != NULL) - pErrorCb(messageText, IA_SERVER_ERROR, errorCbData); -phase = 1; -phaseTime = GetTickCount(); -codeError = IA_SERVER_ERROR; +KOIToWin(reinterpret_cast(err.text), &m_messageText); +if (m_pErrorCb != NULL) + m_pErrorCb(m_messageText, IA_SERVER_ERROR, m_errorCbData); +m_phase = 1; +m_phaseTime = GetTickCount(); +m_codeError = IA_SERVER_ERROR; return ERROR_N; } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Prepare_CONN_SYN_8(char * buffer) +int IA_CLIENT_PROT::Prepare_CONN_SYN_8(void* buffer) { -connSyn8 = (CONN_SYN_8*)buffer; +m_connSyn8 = static_cast(buffer); assert(sizeof(CONN_SYN_8) == Min8(sizeof(CONN_SYN_8)) && "CONN_SYN_8 is not aligned to 8 bytes"); -connSyn8->len = sizeof(CONN_SYN_8); +m_connSyn8->len = sizeof(CONN_SYN_8); #ifdef ARCH_BE -SwapBytes(connSyn8->len); +SwapBytes(m_connSyn8->len); #endif -strncpy((char*)connSyn8->type, "CONN_SYN", IA_MAX_TYPE_LEN); -strncpy((char*)connSyn8->login, login.c_str(), IA_LOGIN_LEN); -connSyn8->dirs = 0; +strncpy(reinterpret_cast(m_connSyn8->type), "CONN_SYN", IA_MAX_TYPE_LEN); +strncpy(reinterpret_cast(m_connSyn8->login), m_login.c_str(), IA_LOGIN_LEN); +m_connSyn8->dirs = 0; for (int i = 0; i < DIR_NUM; i++) - { - connSyn8->dirs |= (selectedDirs[i] << i); - } + m_connSyn8->dirs |= (m_selectedDirs[i] << i); return sizeof(CONN_SYN_8); } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Prepare_CONN_ACK_8(char * buffer) +int IA_CLIENT_PROT::Prepare_CONN_ACK_8(void* buffer) { -connAck8 = (CONN_ACK_8*)buffer; +m_connAck8 = static_cast(buffer); assert(sizeof(CONN_ACK_8) == Min8(sizeof(CONN_ACK_8)) && "CONN_ACK_8 is not aligned to 8 bytes"); -connAck8->len = sizeof(CONN_ACK_8); -strncpy((char*)connAck8->loginS, login.c_str(), IA_LOGIN_LEN); -strncpy((char*)connAck8->type, "CONN_ACK", IA_MAX_TYPE_LEN); -rnd++; -connAck8->rnd = rnd; +m_connAck8->len = sizeof(CONN_ACK_8); +strncpy(reinterpret_cast(m_connAck8->loginS), m_login.c_str(), IA_LOGIN_LEN); +strncpy(reinterpret_cast(m_connAck8->type), "CONN_ACK", IA_MAX_TYPE_LEN); +m_rnd++; +m_connAck8->rnd = m_rnd; #ifdef ARCH_BE -SwapBytes(connAck8->len); -SwapBytes(connAck8->rnd); +SwapBytes(m_connAck8->len); +SwapBytes(m_connAck8->rnd); #endif return sizeof(CONN_ACK_8); } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Prepare_ALIVE_ACK_8(char * buffer) +int IA_CLIENT_PROT::Prepare_ALIVE_ACK_8(void* buffer) { -aliveAck8 = (ALIVE_ACK_8*)buffer; +m_aliveAck8 = static_cast(buffer); assert(Min8(sizeof(ALIVE_ACK_8)) == sizeof(ALIVE_ACK_8) && "ALIVE_ACK_8 is not aligned to 8 bytes"); -aliveAck8 = (ALIVE_ACK_8*)buffer; -aliveAck8->len = sizeof(ALIVE_ACK_8); -strncpy((char*)aliveAck8->loginS, login.c_str(), IA_LOGIN_LEN); -strncpy((char*)aliveAck8->type, "ALIVE_ACK", IA_MAX_TYPE_LEN); -aliveAck8->rnd = ++rnd; +m_aliveAck8->len = sizeof(ALIVE_ACK_8); +strncpy(reinterpret_cast(m_aliveAck8->loginS), m_login.c_str(), IA_LOGIN_LEN); +strncpy(reinterpret_cast(m_aliveAck8->type), "ALIVE_ACK", IA_MAX_TYPE_LEN); +m_aliveAck8->rnd = ++m_rnd; #ifdef ARCH_BE -SwapBytes(aliveAck8->len); -SwapBytes(aliveAck8->rnd); +SwapBytes(m_aliveAck8->len); +SwapBytes(m_aliveAck8->rnd); #endif return sizeof(ALIVE_ACK_8); } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Prepare_DISCONN_SYN_8(char * buffer) +int IA_CLIENT_PROT::Prepare_DISCONN_SYN_8(void* buffer) { -disconnSyn8 = (DISCONN_SYN_8*)buffer; +m_disconnSyn8 = static_cast(buffer); assert(Min8(sizeof(DISCONN_SYN_8)) == sizeof(DISCONN_SYN_8) && "DISCONN_SYN_8 is not aligned to 8 bytes"); -disconnSyn8->len = sizeof(DISCONN_SYN_8); +m_disconnSyn8->len = sizeof(DISCONN_SYN_8); #ifdef ARCH_BE -SwapBytes(disconnSyn8->len); +SwapBytes(m_disconnSyn8->len); #endif -strncpy((char*)disconnSyn8->loginS, login.c_str(), IA_LOGIN_LEN); -strncpy((char*)disconnSyn8->type, "DISCONN_SYN", IA_MAX_TYPE_LEN); -strncpy((char*)disconnSyn8->login, login.c_str(), IA_LOGIN_LEN); +strncpy(reinterpret_cast(m_disconnSyn8->loginS), m_login.c_str(), IA_LOGIN_LEN); +strncpy(reinterpret_cast(m_disconnSyn8->type), "DISCONN_SYN", IA_MAX_TYPE_LEN); +strncpy(reinterpret_cast(m_disconnSyn8->login), m_login.c_str(), IA_LOGIN_LEN); return sizeof(DISCONN_SYN_8); } //--------------------------------------------------------------------------- -int IA_CLIENT_PROT::Prepare_DISCONN_ACK_8(char * buffer) +int IA_CLIENT_PROT::Prepare_DISCONN_ACK_8(void* buffer) { -disconnAck8 = (DISCONN_ACK_8*)buffer; +m_disconnAck8 = static_cast(buffer); assert(Min8(sizeof(DISCONN_ACK_8)) == sizeof(DISCONN_ACK_8) && "DISCONN_ACK_8 is not aligned to 8 bytes"); -disconnAck8->len = Min8(sizeof(DISCONN_ACK_8)); -disconnAck8->rnd = rnd + 1; +m_disconnAck8->len = Min8(sizeof(DISCONN_ACK_8)); +m_disconnAck8->rnd = m_rnd + 1; #ifdef ARCH_BE -SwapBytes(disconnAck8->len); -SwapBytes(disconnAck8->rnd); +SwapBytes(m_disconnAck8->len); +SwapBytes(m_disconnAck8->rnd); #endif -strncpy((char*)disconnAck8->loginS, login.c_str(), IA_LOGIN_LEN); -strncpy((char*)disconnAck8->type, "DISCONN_ACK", IA_MAX_TYPE_LEN); +strncpy(reinterpret_cast(m_disconnAck8->loginS), m_login.c_str(), IA_LOGIN_LEN); +strncpy(reinterpret_cast(m_disconnAck8->type), "DISCONN_ACK", IA_MAX_TYPE_LEN); return Min8(sizeof(DISCONN_ACK_8)); } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetStatusChangedCb(tpStatusChangedCb p, void * data) { -pStatusChangedCb = p; -statusChangedCbData = data; +m_pStatusChangedCb = p; +m_statusChangedCbData = data; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetStatChangedCb(tpStatChangedCb p, void * data) { -pStatChangedCb = p; -statChangedCbData = data; +m_pStatChangedCb = p; +m_statChangedCbData = data; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetInfoCb(tpCallBackInfoFn p, void * data) { -pInfoCb = p; -infoCbData = data; +m_pInfoCb = p; +m_infoCbData = data; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetDirNameCb(tpCallBackDirNameFn p, void * data) { -pDirNameCb = p; -dirNameCbData = data; +m_pDirNameCb = p; +m_dirNameCbData = data; } //--------------------------------------------------------------------------- void IA_CLIENT_PROT::SetErrorCb(tpCallBackErrorFn p, void * data) { -pErrorCb = p; -errorCbData = data; +m_pErrorCb = p; +m_errorCbData = data; } //--------------------------------------------------------------------------- diff --git a/libs/ia/include/stg/ia.h b/libs/ia/include/stg/ia.h index c37f4394..11030a7e 100644 --- a/libs/ia/include/stg/ia.h +++ b/libs/ia/include/stg/ia.h @@ -24,8 +24,14 @@ * Author : Boris Mikhailenko */ //--------------------------------------------------------------------------- -#ifndef IA_AUTH_C_H -#define IA_AUTH_C_H +#pragma once + +#include "stg/blowfish.h" +#include "stg/ia_packets.h" + +#include +#include +#include #ifndef WIN32 #include @@ -36,13 +42,6 @@ #include #endif -#include -#include -#include - -#include "stg/blowfish.h" -#include "stg/ia_packets.h" - #define IA_BIND_ERROR (1) #define IA_SERVER_ERROR (2) #define IA_FCNTL_ERROR (3) @@ -66,134 +65,134 @@ friend unsigned long WINAPI RunW(void * data); friend void * RunL(void * data); #endif -public: - IA_CLIENT_PROT(const std::string & sn, uint16_t p, const std::string & localName = "", uint16_t localPort = 0); - ~IA_CLIENT_PROT(); - - void Start(); - void Stop(); - void GetStat(LOADSTAT * ls); - - void SetServer(const std::string & sn, unsigned short port); - void SetLogin(const std::string & login); - void SetPassword(const std::string & password); - void SetEnabledDirs(const bool * selectedDirs); - - void SetStatusChangedCb(tpStatusChangedCb p, void * data); - void SetStatChangedCb(tpStatChangedCb p, void * data); - void SetInfoCb(tpCallBackInfoFn p, void * data); - void SetErrorCb(tpCallBackErrorFn p, void * data); - void SetDirNameCb(tpCallBackDirNameFn p, void * data); - - int Connect(); - int Disconnect(); - int GetAuthorized() const { return phase == 3 || phase == 4; }; - int GetPhase() const { return phase; }; - int GetStatus() const; - int GetReconnect() const { return reconnect; }; - void SetReconnect(int r) { reconnect = r; }; - char GetProtoVer() const { return proxyMode ? IA_PROTO_PROXY_VER : IA_PROTO_VER; }; - void GetMessageText(std::string * text) const { *text = messageText; }; - void GetInfoText(std::string * text) const { *text = infoText; }; - int GetStrError(std::string * error) const; - - void SetProxyMode(bool on) { proxyMode = on; }; - bool GetProxyMode() const { return proxyMode; }; - - void SetIP(uint32_t ip) { IA_CLIENT_PROT::ip = ip; }; - uint32_t GetIP() const { return ip; }; - -private: - void Run(); - int NetRecv(); - int NetSend(int n); - bool GetNonstop() const { return nonstop; }; - void PrepareNet(); - int DeterminatePacketType(const char * buffer); - - int Process_CONN_SYN_ACK_8(const char * buffer); - int Process_ALIVE_SYN_8(const char * buffer); - int Process_DISCONN_SYN_ACK_8(const char * buffer); - int Process_FIN_8(const char * buffer); - int Process_INFO_8(const char * buffer); - int Process_ERROR(const char * buffer); - - int Prepare_CONN_SYN_8(char * buffer); - int Prepare_CONN_ACK_8(char * buffer); - int Prepare_ALIVE_ACK_8(char * buffer); - int Prepare_DISCONN_SYN_8(char * buffer); - int Prepare_DISCONN_ACK_8(char * buffer); - - void FillHdr8(char * buffer, unsigned long ip); - int Send(char * buffer, int len); - int Recv(char * buffer, int len); - - LOADSTAT stat; - int action; - int phase; - int phaseTime; - std::string messageText; - std::string infoText; - mutable std::string strError; - mutable int codeError; - bool nonstop; - bool isNetPrepared; - bool proxyMode; - - BLOWFISH_CTX ctxPass; - BLOWFISH_CTX ctxHdr; - - bool selectedDirs[DIR_NUM]; - - std::string password; - std::string login; - - #ifdef WIN32 - WSADATA wsaData; - #else - pthread_t thread; - #endif - - std::string serverName; - uint16_t port; - uint32_t ip; - std::string localName; - uint32_t localIP; - uint32_t localPort; - - struct sockaddr_in servAddr; - - bool firstConnect; - int reconnect; - int sockr; - int protNum; - int userTimeout; - int aliveTimeout; - unsigned int rnd; - - tpStatusChangedCb pStatusChangedCb; - tpStatChangedCb pStatChangedCb; - tpCallBackInfoFn pInfoCb; - tpCallBackErrorFn pErrorCb; - tpCallBackDirNameFn pDirNameCb; - - void * statusChangedCbData; - void * statChangedCbData; - void * infoCbData; - void * errorCbData; - void * dirNameCbData; - - std::map packetTypes; - - CONN_SYN_8 * connSyn8; - CONN_SYN_ACK_8 * connSynAck8; - CONN_ACK_8 * connAck8; - ALIVE_SYN_8 * aliveSyn8; - ALIVE_ACK_8 * aliveAck8; - DISCONN_SYN_8 * disconnSyn8; - DISCONN_SYN_ACK_8 * disconnSynAck8; - DISCONN_ACK_8 * disconnAck8; - INFO_8 * info; + public: + IA_CLIENT_PROT(const std::string & sn, uint16_t p, const std::string & localName = "", uint16_t localPort = 0); + ~IA_CLIENT_PROT(); + + void Start(); + void Stop(); + void GetStat(LOADSTAT * ls); + + void SetServer(const std::string & sn, unsigned short port); + void SetLogin(const std::string & login); + void SetPassword(const std::string & password); + void SetEnabledDirs(const bool * selectedDirs); + + void SetStatusChangedCb(tpStatusChangedCb p, void * data); + void SetStatChangedCb(tpStatChangedCb p, void * data); + void SetInfoCb(tpCallBackInfoFn p, void * data); + void SetErrorCb(tpCallBackErrorFn p, void * data); + void SetDirNameCb(tpCallBackDirNameFn p, void * data); + + int Connect(); + int Disconnect(); + int GetAuthorized() const { return m_phase == 3 || m_phase == 4; }; + int GetPhase() const { return m_phase; }; + int GetStatus() const; + int GetReconnect() const { return m_reconnect; }; + void SetReconnect(int r) { m_reconnect = r; }; + char GetProtoVer() const { return m_proxyMode ? IA_PROTO_PROXY_VER : IA_PROTO_VER; }; + void GetMessageText(std::string * text) const { *text = m_messageText; }; + void GetInfoText(std::string * text) const { *text = m_infoText; }; + int GetStrError(std::string * error) const; + + void SetProxyMode(bool on) { m_proxyMode = on; }; + bool GetProxyMode() const { return m_proxyMode; }; + + void SetIP(uint32_t ip) { m_ip = ip; }; + uint32_t GetIP() const { return m_ip; }; + + private: + void Run(); + int NetRecv(); + int NetSend(int n); + bool GetNonstop() const { return m_nonstop; }; + void PrepareNet(); + int DeterminatePacketType(const char * buffer); + + int Process_CONN_SYN_ACK_8(const void* buffer); + int Process_ALIVE_SYN_8(const void* buffer); + int Process_DISCONN_SYN_ACK_8(const void* buffer); + int Process_FIN_8(const void* buffer); + int Process_INFO_8(const void* buffer); + int Process_ERROR(const void* buffer); + + int Prepare_CONN_SYN_8(void* buffer); + int Prepare_CONN_ACK_8(void* buffer); + int Prepare_ALIVE_ACK_8(void* buffer); + int Prepare_DISCONN_SYN_8(void* buffer); + int Prepare_DISCONN_ACK_8(void* buffer); + + void FillHdr8(char* buffer, unsigned long ip); + int Send(char * buffer, int len); + int Recv(char * buffer, int len); + + LOADSTAT m_stat; + int m_action; + int m_phase; + int m_phaseTime; + std::string m_messageText; + std::string m_infoText; + mutable std::string m_strError; + mutable int m_codeError; + bool m_nonstop; + bool m_isNetPrepared; + bool m_proxyMode; + + BLOWFISH_CTX m_ctxPass; + BLOWFISH_CTX m_ctxHdr; + + bool m_selectedDirs[DIR_NUM]; + + std::string m_password; + std::string m_login; + + #ifdef WIN32 + WSADATA m_wsaData; + #else + pthread_t m_thread; + #endif + + std::string m_serverName; + uint16_t m_port; + uint32_t m_ip; + std::string m_localName; + uint32_t m_localIP; + uint32_t m_localPort; + + struct sockaddr_in m_servAddr; + + bool m_firstConnect; + int m_reconnect; + int m_sockr; + int m_protNum; + int m_userTimeout; + int m_aliveTimeout; + unsigned int m_rnd; + + tpStatusChangedCb m_pStatusChangedCb; + tpStatChangedCb m_pStatChangedCb; + tpCallBackInfoFn m_pInfoCb; + tpCallBackErrorFn m_pErrorCb; + tpCallBackDirNameFn m_pDirNameCb; + + void * m_statusChangedCbData; + void * m_statChangedCbData; + void * m_infoCbData; + void * m_errorCbData; + void * m_dirNameCbData; + + std::map m_packetTypes; + + CONN_SYN_8 * m_connSyn8; + const CONN_SYN_ACK_8 * m_connSynAck8; + CONN_ACK_8 * m_connAck8; + const ALIVE_SYN_8 * m_aliveSyn8; + ALIVE_ACK_8 * m_aliveAck8; + DISCONN_SYN_8 * m_disconnSyn8; + const DISCONN_SYN_ACK_8 * m_disconnSynAck8; + DISCONN_ACK_8 * m_disconnAck8; + const INFO_8 * m_info; }; //--------------------------------------------------------------------------- #ifdef WIN32 @@ -201,6 +200,3 @@ unsigned long WINAPI RunW(void *); #else void * RunW(void *); #endif - -//--------------------------------------------------------------------------- -#endif //IA_AUTH_C_H diff --git a/libs/pinger/include/stg/pinger.h b/libs/pinger/include/stg/pinger.h index 26f5f4b3..b726a751 100644 --- a/libs/pinger/include/stg/pinger.h +++ b/libs/pinger/include/stg/pinger.h @@ -4,13 +4,13 @@ $Author: nobunaga $ */ -#ifndef PINGER_H -#define PINGER_H +#pragma once -#include #include #include #include +#include +#include #ifdef LINUX #include @@ -27,26 +27,24 @@ #include #endif -#include - //----------------------------------------------------------------------------- struct ICMP_HDR { -uint8_t type; -uint8_t code; -uint16_t checksum; -union + uint8_t type; + uint8_t code; + uint16_t checksum; + union { - struct + struct { - uint16_t id; - uint16_t sequence; + uint16_t id; + uint16_t sequence; } echo; - uint32_t gateway; - struct + uint32_t gateway; + struct { - uint16_t unused; - uint16_t mtu; + uint16_t unused; + uint16_t mtu; } frag; } un; }; @@ -68,8 +66,8 @@ struct IP_HDR //----------------------------------------------------------------------------- struct PING_IP_TIME { -uint32_t ip; -time_t pingTime; + uint32_t ip; + time_t pingTime; }; //----------------------------------------------------------------------------- @@ -83,53 +81,51 @@ struct PING_MESSAGE //----------------------------------------------------------------------------- class STG_PINGER { -public: - typedef std::multimap PingIPs; - typedef PingIPs::size_type SizeType; - - explicit STG_PINGER(time_t delay = 15); - ~STG_PINGER(); - - int Start(); - int Stop(); - void AddIP(uint32_t ip); - void DelIP(uint32_t ip); - SizeType GetPingIPNum() const { return pingIP.size(); } - void PrintAllIP(); - int GetIPTime(uint32_t ip, time_t * t) const; - void SetDelayTime(time_t d) { delay = d; } - time_t GetDelayTime() const { return delay; } - const std::string & GetStrError() const { return errorStr; } - -private: - uint16_t PingCheckSum(void * data, int len); - int SendPing(uint32_t ip); - uint32_t RecvPing(); - void RealAddIP(); - void RealDelIP(); - - static void * RunSendPing(void * d); - static void * RunRecvPing(void * d); - - time_t delay; - bool nonstop; - bool isRunningRecver; - bool isRunningSender; - int sendSocket; - int recvSocket; - pthread_t sendThread; - pthread_t recvThread; - - PING_MESSAGE pmSend; - uint32_t pid; - - std::string errorStr; - - std::multimap pingIP; - std::list ipToAdd; - std::list ipToDel; - - mutable pthread_mutex_t mutex; + public: + typedef std::multimap PingIPs; + typedef PingIPs::size_type SizeType; + + explicit STG_PINGER(time_t delay = 15); + ~STG_PINGER(); + + int Start(); + int Stop(); + void AddIP(uint32_t ip); + void DelIP(uint32_t ip); + SizeType GetPingIPNum() const { return m_pingIP.size(); } + void PrintAllIP(); + int GetIPTime(uint32_t ip, time_t * t) const; + void SetDelayTime(time_t d) { m_delay = d; } + time_t GetDelayTime() const { return m_delay; } + const std::string & GetStrError() const { return m_errorStr; } + + private: + uint16_t PingCheckSum(void * data, int len); + int SendPing(uint32_t ip); + uint32_t RecvPing(); + void RealAddIP(); + void RealDelIP(); + + static void * RunSendPing(void * d); + static void * RunRecvPing(void * d); + + time_t m_delay; + bool m_nonstop; + bool m_isRunningRecver; + bool m_isRunningSender; + int m_sendSocket; + int m_recvSocket; + pthread_t m_sendThread; + pthread_t m_recvThread; + + PING_MESSAGE m_pmSend; + uint32_t m_pid; + + std::string m_errorStr; + + std::multimap m_pingIP; + std::list m_ipToAdd; + std::list m_ipToDel; + + mutable pthread_mutex_t m_mutex; }; -//----------------------------------------------------------------------------- -#endif diff --git a/libs/pinger/pinger.cpp b/libs/pinger/pinger.cpp index 07415812..042edcba 100644 --- a/libs/pinger/pinger.cpp +++ b/libs/pinger/pinger.cpp @@ -26,54 +26,46 @@ extern volatile time_t stgTime; //----------------------------------------------------------------------------- STG_PINGER::STG_PINGER(time_t d) - : delay(d), - nonstop(false), - isRunningRecver(false), - isRunningSender(false), - sendSocket(-1), - recvSocket(-1), - sendThread(), - recvThread(), - pmSend(), - pid(0), - errorStr(), - pingIP(), - ipToAdd(), - ipToDel(), - mutex() + : m_delay(d), + m_nonstop(false), + m_isRunningRecver(false), + m_isRunningSender(false), + m_sendSocket(-1), + m_recvSocket(-1), + m_pid(0) { -pthread_mutex_init(&mutex, NULL); -memset(&pmSend, 0, sizeof(pmSend)); +pthread_mutex_init(&m_mutex, NULL); +memset(&m_pmSend, 0, sizeof(m_pmSend)); } //----------------------------------------------------------------------------- STG_PINGER::~STG_PINGER() { -pthread_mutex_destroy(&mutex); +pthread_mutex_destroy(&m_mutex); } //----------------------------------------------------------------------------- int STG_PINGER::Start() { struct protoent *proto = NULL; proto = getprotobyname("ICMP"); -sendSocket = socket(PF_INET, SOCK_RAW, proto->p_proto); -recvSocket = socket(PF_INET, SOCK_RAW, proto->p_proto); -nonstop = true; -pid = (int) getpid() % 65535; -if (sendSocket < 0 || recvSocket < 0) +m_sendSocket = socket(PF_INET, SOCK_RAW, proto->p_proto); +m_recvSocket = socket(PF_INET, SOCK_RAW, proto->p_proto); +m_nonstop = true; +m_pid = static_cast(getpid()) % 65535; +if (m_sendSocket < 0 || m_recvSocket < 0) { - errorStr = "Cannot create socket."; + m_errorStr = "Cannot create socket."; return -1; } -if (pthread_create(&sendThread, NULL, RunSendPing, this)) +if (pthread_create(&m_sendThread, NULL, RunSendPing, this)) { - errorStr = "Cannot create send thread."; + m_errorStr = "Cannot create send thread."; return -1; } -if (pthread_create(&recvThread, NULL, RunRecvPing, this)) +if (pthread_create(&m_recvThread, NULL, RunRecvPing, this)) { - errorStr = "Cannot create recv thread."; + m_errorStr = "Cannot create recv thread."; return -1; } @@ -82,9 +74,9 @@ return 0; //----------------------------------------------------------------------------- int STG_PINGER::Stop() { -close(recvSocket); -nonstop = false; -if (isRunningRecver) +close(m_recvSocket); +m_nonstop = false; +if (m_isRunningRecver) { //5 seconds to thread stops itself for (size_t i = 0; i < 25; i++) @@ -92,7 +84,7 @@ if (isRunningRecver) if (i % 5 == 0) SendPing(0x0100007f);//127.0.0.1 - if (!isRunningRecver) + if (!m_isRunningRecver) break; struct timespec ts = {0, 200000000}; @@ -100,12 +92,12 @@ if (isRunningRecver) } } -if (isRunningSender) +if (m_isRunningSender) { //5 seconds to thread stops itself for (size_t i = 0; i < 25; i++) { - if (!isRunningSender) + if (!m_isRunningSender) break; struct timespec ts = {0, 200000000}; @@ -113,9 +105,9 @@ if (isRunningSender) } } -close(sendSocket); +close(m_sendSocket); -if (isRunningSender || isRunningRecver) +if (m_isRunningSender || m_isRunningRecver) return -1; return 0; @@ -123,54 +115,50 @@ return 0; //----------------------------------------------------------------------------- void STG_PINGER::AddIP(uint32_t ip) { -STG_LOCKER lock(&mutex); -ipToAdd.push_back(ip); +STG_LOCKER lock(&m_mutex); +m_ipToAdd.push_back(ip); } //----------------------------------------------------------------------------- void STG_PINGER::DelIP(uint32_t ip) { -STG_LOCKER lock(&mutex); -ipToDel.push_back(ip); +STG_LOCKER lock(&m_mutex); +m_ipToDel.push_back(ip); } //----------------------------------------------------------------------------- void STG_PINGER::RealAddIP() { -STG_LOCKER lock(&mutex); +STG_LOCKER lock(&m_mutex); -std::list::iterator iter; -iter = ipToAdd.begin(); -while (iter != ipToAdd.end()) +auto iter = m_ipToAdd.begin(); +while (iter != m_ipToAdd.end()) { - pingIP.insert(std::make_pair(*iter, 0)); + m_pingIP.insert(std::make_pair(*iter, 0)); ++iter; } -ipToAdd.erase(ipToAdd.begin(), ipToAdd.end()); +m_ipToAdd.erase(m_ipToAdd.begin(), m_ipToAdd.end()); } //----------------------------------------------------------------------------- void STG_PINGER::RealDelIP() { -STG_LOCKER lock(&mutex); +STG_LOCKER lock(&m_mutex); -std::list::iterator iter; -std::multimap::iterator treeIter; -iter = ipToDel.begin(); -while (iter != ipToDel.end()) +auto iter = m_ipToDel.begin(); +while (iter != m_ipToDel.end()) { - treeIter = pingIP.find(*iter); - if (treeIter != pingIP.end()) - pingIP.erase(treeIter); + auto treeIter = m_pingIP.find(*iter); + if (treeIter != m_pingIP.end()) + m_pingIP.erase(treeIter); ++iter; } -ipToDel.erase(ipToDel.begin(), ipToDel.end()); +m_ipToDel.erase(m_ipToDel.begin(), m_ipToDel.end()); } //----------------------------------------------------------------------------- void STG_PINGER::PrintAllIP() { -STG_LOCKER lock(&mutex); -std::multimap::iterator iter; -iter = pingIP.begin(); -while (iter != pingIP.end()) +STG_LOCKER lock(&m_mutex); +auto iter = m_pingIP.begin(); +while (iter != m_pingIP.end()) { uint32_t ip = iter->first; time_t t = iter->second; @@ -183,11 +171,10 @@ while (iter != pingIP.end()) //----------------------------------------------------------------------------- int STG_PINGER::GetIPTime(uint32_t ip, time_t * t) const { -STG_LOCKER lock(&mutex); -std::multimap::const_iterator treeIter; +STG_LOCKER lock(&m_mutex); -treeIter = pingIP.find(ip); -if (treeIter == pingIP.end()) +auto treeIter = m_pingIP.find(ip); +if (treeIter == m_pingIP.end()) return -1; *t = treeIter->second; @@ -220,16 +207,16 @@ addr.sin_family = AF_INET; addr.sin_port = 0; addr.sin_addr.s_addr = ip; -memset(&pmSend, 0, sizeof(pmSend)); -pmSend.hdr.type = ICMP_ECHO; -pmSend.hdr.un.echo.id = static_cast(pid); -memcpy(pmSend.msg, &ip, sizeof(ip)); +memset(&m_pmSend, 0, sizeof(m_pmSend)); +m_pmSend.hdr.type = ICMP_ECHO; +m_pmSend.hdr.un.echo.id = static_cast(m_pid); +memcpy(m_pmSend.msg, &ip, sizeof(ip)); -pmSend.hdr.checksum = PingCheckSum(&pmSend, sizeof(pmSend)); +m_pmSend.hdr.checksum = PingCheckSum(&m_pmSend, sizeof(m_pmSend)); -if (sendto(sendSocket, &pmSend, sizeof(pmSend), 0, (sockaddr *)&addr, sizeof(addr)) <= 0 ) +if (sendto(m_sendSocket, &m_pmSend, sizeof(m_pmSend), 0, reinterpret_cast(&addr), sizeof(addr)) <= 0 ) { - errorStr = "Send ping error: " + std::string(strerror(errno)); + m_errorStr = "Send ping error: " + std::string(strerror(errno)); return -1; } @@ -246,12 +233,12 @@ char buf[128]; memset(buf, 0, sizeof(buf)); socklen_t len = sizeof(addr); -if (recvfrom(recvSocket, &buf, sizeof(buf), 0, reinterpret_cast(&addr), &len)) +if (recvfrom(m_recvSocket, &buf, sizeof(buf), 0, reinterpret_cast(&addr), &len)) { struct IP_HDR * ip = static_cast(static_cast(buf)); struct ICMP_HDR *icmp = static_cast(static_cast(buf + ip->ihl * 4)); - if (icmp->un.echo.id != pid) + if (icmp->un.echo.id != m_pid) return 0; ipAddr = *static_cast(static_cast(buf + sizeof(ICMP_HDR) + ip->ihl * 4)); @@ -266,18 +253,18 @@ sigset_t signalSet; sigfillset(&signalSet); pthread_sigmask(SIG_BLOCK, &signalSet, NULL); -STG_PINGER * pinger = static_cast(d); +auto* pinger = static_cast(d); -pinger->isRunningSender = true; +pinger->m_isRunningSender = true; time_t lastPing = 0; -while (pinger->nonstop) +while (pinger->m_nonstop) { pinger->RealAddIP(); pinger->RealDelIP(); std::multimap::iterator iter; - iter = pinger->pingIP.begin(); - while (iter != pinger->pingIP.end()) + iter = pinger->m_pingIP.begin(); + while (iter != pinger->m_pingIP.end()) { pinger->SendPing(iter->first); ++iter; @@ -292,7 +279,7 @@ while (pinger->nonstop) currTime = lastPing = time(NULL); #endif - while (currTime - lastPing < pinger->delay && pinger->nonstop) + while (currTime - lastPing < pinger->m_delay && pinger->m_nonstop) { #ifdef STG_TIME currTime = stgTime; @@ -304,7 +291,7 @@ while (pinger->nonstop) } } -pinger->isRunningSender = false; +pinger->m_isRunningSender = false; return NULL; } @@ -315,18 +302,18 @@ sigset_t signalSet; sigfillset(&signalSet); pthread_sigmask(SIG_BLOCK, &signalSet, NULL); -STG_PINGER * pinger = static_cast(d); +auto* pinger = static_cast(d); -pinger->isRunningRecver = true; +pinger->m_isRunningRecver = true; -while (pinger->nonstop) +while (pinger->m_nonstop) { uint32_t ip = pinger->RecvPing(); if (ip) { - std::multimap::iterator treeIterUpper = pinger->pingIP.upper_bound(ip); - std::multimap::iterator treeIterLower = pinger->pingIP.lower_bound(ip); + auto treeIterUpper = pinger->m_pingIP.upper_bound(ip); + auto treeIterLower = pinger->m_pingIP.lower_bound(ip); while (treeIterUpper != treeIterLower) { #ifdef STG_TIME @@ -339,7 +326,7 @@ while (pinger->nonstop) } } -pinger->isRunningRecver = false; +pinger->m_isRunningRecver = false; return NULL; } //----------------------------------------------------------------------------- diff --git a/libs/srvconf/include/stg/servconf.h b/libs/srvconf/include/stg/servconf.h index 2f246b67..fe3cb32c 100644 --- a/libs/srvconf/include/stg/servconf.h +++ b/libs/srvconf/include/stg/servconf.h @@ -101,7 +101,7 @@ class ServConf private: class Impl; - Impl* pImpl; + Impl* m_impl; }; } // namespace STG diff --git a/libs/srvconf/netunit.cpp b/libs/srvconf/netunit.cpp index ec2e3c5b..7d6332c6 100644 --- a/libs/srvconf/netunit.cpp +++ b/libs/srvconf/netunit.cpp @@ -80,25 +80,25 @@ const char RECV_HEADER_ANSWER_ERROR[] = "Error receiving header answer."; //--------------------------------------------------------------------------- NetTransact::NetTransact(const std::string& s, uint16_t p, const std::string& l, const std::string& pwd) - : server(s), - port(p), - localPort(0), - login(l), - password(pwd), - sock(-1) + : m_server(s), + m_port(p), + m_localPort(0), + m_login(l), + m_password(pwd), + m_sock(-1) { } //--------------------------------------------------------------------------- NetTransact::NetTransact(const std::string& s, uint16_t p, const std::string& la, uint16_t lp, const std::string& l, const std::string& pwd) - : server(s), - port(p), - localAddress(la), - localPort(lp), - login(l), - password(pwd), - sock(-1) + : m_server(s), + m_port(p), + m_localAddress(la), + m_localPort(lp), + m_login(l), + m_password(pwd), + m_sock(-1) { } //--------------------------------------------------------------------------- @@ -109,43 +109,43 @@ NetTransact::~NetTransact() //--------------------------------------------------------------------------- int NetTransact::Connect() { - sock = socket(PF_INET, SOCK_STREAM, 0); - if (sock < 0) + m_sock = socket(PF_INET, SOCK_STREAM, 0); + if (m_sock < 0) { - errorMsg = CREATE_SOCKET_ERROR; + m_errorMsg = CREATE_SOCKET_ERROR; return st_conn_fail; } - if (!localAddress.empty()) + if (!m_localAddress.empty()) { - if (localPort == 0) - localPort = port; + if (m_localPort == 0) + m_localPort = m_port; - unsigned long ip = inet_addr(localAddress.c_str()); + uint32_t ip = inet_addr(m_localAddress.c_str()); if (ip == INADDR_NONE) { - auto phe = gethostbyname(localAddress.c_str()); + auto phe = gethostbyname(m_localAddress.c_str()); if (phe == NULL) { - errorMsg = "Can not reslove '" + localAddress + "'"; + m_errorMsg = "Can not reslove '" + m_localAddress + "'"; return st_dns_err; } struct hostent he; memcpy(&he, phe, sizeof(he)); - ip = *((long *)he.h_addr_list[0]); + ip = *reinterpret_cast(he.h_addr_list[0]); } struct sockaddr_in localAddr; memset(&localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET; - localAddr.sin_port = htons(localPort); + localAddr.sin_port = htons(m_localPort); localAddr.sin_addr.s_addr = ip; - if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) + if (bind(m_sock, reinterpret_cast(&localAddr), sizeof(localAddr)) < 0) { - errorMsg = BIND_FAILED; + m_errorMsg = BIND_FAILED; return st_conn_fail; } } @@ -153,29 +153,29 @@ int NetTransact::Connect() struct sockaddr_in outerAddr; memset(&outerAddr, 0, sizeof(outerAddr)); - unsigned long ip = inet_addr(server.c_str()); + uint32_t ip = inet_addr(m_server.c_str()); if (ip == INADDR_NONE) { - auto phe = gethostbyname(server.c_str()); + auto phe = gethostbyname(m_server.c_str()); if (phe == NULL) { - errorMsg = "Can not reslove '" + server + "'"; + m_errorMsg = "Can not reslove '" + m_server + "'"; return st_dns_err; } struct hostent he; memcpy(&he, phe, sizeof(he)); - ip = *((long *)he.h_addr_list[0]); + ip = *reinterpret_cast(he.h_addr_list[0]); } outerAddr.sin_family = AF_INET; - outerAddr.sin_port = htons(port); + outerAddr.sin_port = htons(m_port); outerAddr.sin_addr.s_addr = ip; - if (connect(sock, (struct sockaddr *)&outerAddr, sizeof(outerAddr)) < 0) + if (connect(m_sock, reinterpret_cast(&outerAddr), sizeof(outerAddr)) < 0) { - errorMsg = CONNECT_FAILED; + m_errorMsg = CONNECT_FAILED; return st_conn_fail; } @@ -184,11 +184,11 @@ int NetTransact::Connect() //--------------------------------------------------------------------------- void NetTransact::Disconnect() { - if (sock != -1) + if (m_sock != -1) { - shutdown(sock, SHUT_RDWR); - close(sock); - sock = -1; + shutdown(m_sock, SHUT_RDWR); + close(m_sock); + m_sock = -1; } } //--------------------------------------------------------------------------- @@ -224,9 +224,9 @@ int NetTransact::Transact(const std::string& request, Callback callback, void* d //--------------------------------------------------------------------------- int NetTransact::TxHeader() { - if (!WriteAll(sock, STG_HEADER, strlen(STG_HEADER))) + if (!WriteAll(m_sock, STG_HEADER, strlen(STG_HEADER))) { - errorMsg = SEND_HEADER_ERROR; + m_errorMsg = SEND_HEADER_ERROR; return st_send_fail; } @@ -237,9 +237,9 @@ int NetTransact::RxHeaderAnswer() { char buffer[sizeof(STG_HEADER) + 1]; - if (!ReadAll(sock, buffer, strlen(OK_HEADER))) + if (!ReadAll(m_sock, buffer, strlen(OK_HEADER))) { - errorMsg = RECV_HEADER_ANSWER_ERROR; + m_errorMsg = RECV_HEADER_ANSWER_ERROR; return st_recv_fail; } @@ -248,11 +248,11 @@ int NetTransact::RxHeaderAnswer() if (strncmp(ERR_HEADER, buffer, strlen(ERR_HEADER)) == 0) { - errorMsg = INCORRECT_HEADER; + m_errorMsg = INCORRECT_HEADER; return st_header_err; } - errorMsg = UNKNOWN_ERROR; + m_errorMsg = UNKNOWN_ERROR; return st_unknown_err; } //--------------------------------------------------------------------------- @@ -260,11 +260,11 @@ int NetTransact::TxLogin() { char loginZ[ADM_LOGIN_LEN + 1]; memset(loginZ, 0, ADM_LOGIN_LEN + 1); - strncpy(loginZ, login.c_str(), ADM_LOGIN_LEN); + strncpy(loginZ, m_login.c_str(), ADM_LOGIN_LEN); - if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN)) + if (!WriteAll(m_sock, loginZ, ADM_LOGIN_LEN)) { - errorMsg = SEND_LOGIN_ERROR; + m_errorMsg = SEND_LOGIN_ERROR; return st_send_fail; } @@ -275,9 +275,9 @@ int NetTransact::RxLoginAnswer() { char buffer[sizeof(OK_LOGIN) + 1]; - if (!ReadAll(sock, buffer, strlen(OK_LOGIN))) + if (!ReadAll(m_sock, buffer, strlen(OK_LOGIN))) { - errorMsg = RECV_LOGIN_ANSWER_ERROR; + m_errorMsg = RECV_LOGIN_ANSWER_ERROR; return st_recv_fail; } @@ -286,11 +286,11 @@ int NetTransact::RxLoginAnswer() if (strncmp(ERR_LOGIN, buffer, strlen(ERR_LOGIN)) == 0) { - errorMsg = INCORRECT_LOGIN; + m_errorMsg = INCORRECT_LOGIN; return st_login_err; } - errorMsg = UNKNOWN_ERROR; + m_errorMsg = UNKNOWN_ERROR; return st_unknown_err; } //--------------------------------------------------------------------------- @@ -300,11 +300,11 @@ int NetTransact::TxLoginS() memset(loginZ, 0, ADM_LOGIN_LEN + 1); BLOWFISH_CTX ctx; - InitContext(password.c_str(), PASSWD_LEN, &ctx); - EncryptString(loginZ, login.c_str(), std::min(login.length() + 1, ADM_LOGIN_LEN), &ctx); - if (!WriteAll(sock, loginZ, ADM_LOGIN_LEN)) + InitContext(m_password.c_str(), PASSWD_LEN, &ctx); + EncryptString(loginZ, m_login.c_str(), std::min(m_login.length() + 1, ADM_LOGIN_LEN), &ctx); + if (!WriteAll(m_sock, loginZ, ADM_LOGIN_LEN)) { - errorMsg = SEND_LOGIN_ERROR; + m_errorMsg = SEND_LOGIN_ERROR; return st_send_fail; } @@ -315,9 +315,9 @@ int NetTransact::RxLoginSAnswer() { char buffer[sizeof(OK_LOGINS) + 1]; - if (!ReadAll(sock, buffer, strlen(OK_LOGINS))) + if (!ReadAll(m_sock, buffer, strlen(OK_LOGINS))) { - errorMsg = RECV_LOGIN_ANSWER_ERROR; + m_errorMsg = RECV_LOGIN_ANSWER_ERROR; return st_recv_fail; } @@ -326,21 +326,21 @@ int NetTransact::RxLoginSAnswer() if (strncmp(ERR_LOGINS, buffer, strlen(ERR_LOGINS)) == 0) { - errorMsg = INCORRECT_LOGIN; + m_errorMsg = INCORRECT_LOGIN; return st_logins_err; } - errorMsg = UNKNOWN_ERROR; + m_errorMsg = UNKNOWN_ERROR; return st_unknown_err; } //--------------------------------------------------------------------------- int NetTransact::TxData(const std::string& text) { - STG::ENCRYPT_STREAM stream(password, TxCrypto, this); + STG::ENCRYPT_STREAM stream(m_password, TxCrypto, this); stream.Put(text.c_str(), text.length() + 1, true); if (!stream.IsOk()) { - errorMsg = SEND_DATA_ERROR; + m_errorMsg = SEND_DATA_ERROR; return st_send_fail; } @@ -350,14 +350,14 @@ int NetTransact::TxData(const std::string& text) int NetTransact::RxDataAnswer(Callback callback, void* data) { ReadState state = {false, callback, data, this}; - STG::DECRYPT_STREAM stream(password, RxCrypto, &state); + STG::DECRYPT_STREAM stream(m_password, RxCrypto, &state); while (!state.last) { char buffer[1024]; - ssize_t res = read(sock, buffer, sizeof(buffer)); + ssize_t res = read(m_sock, buffer, sizeof(buffer)); if (res < 0) { - errorMsg = RECV_DATA_ANSWER_ERROR; + m_errorMsg = RECV_DATA_ANSWER_ERROR; return st_recv_fail; } stream.Put(buffer, res, res == 0); @@ -372,7 +372,7 @@ bool NetTransact::TxCrypto(const void* block, size_t size, void* data) { assert(data != NULL); auto& nt = *static_cast(data); - if (!WriteAll(nt.sock, block, size)) + if (!WriteAll(nt.m_sock, block, size)) return false; return true; } diff --git a/libs/srvconf/netunit.h b/libs/srvconf/netunit.h index 66d95c3d..b9980abe 100644 --- a/libs/srvconf/netunit.h +++ b/libs/srvconf/netunit.h @@ -39,7 +39,7 @@ class NetTransact ~NetTransact(); int Transact(const std::string& request, Callback f, void* data); - const std::string & GetError() const { return errorMsg; } + const std::string & GetError() const { return m_errorMsg; } int Connect(); void Disconnect(); @@ -57,14 +57,14 @@ class NetTransact int TxData(const std::string& text); int RxDataAnswer(Callback f, void* data); - std::string server; - uint16_t port; - std::string localAddress; - uint16_t localPort; - std::string login; - std::string password; - int sock; - std::string errorMsg; + std::string m_server; + uint16_t m_port; + std::string m_localAddress; + uint16_t m_localPort; + std::string m_login; + std::string m_password; + int m_sock; + std::string m_errorMsg; static bool TxCrypto(const void * block, size_t size, void * data); static bool RxCrypto(const void * block, size_t size, void * data); diff --git a/libs/srvconf/servconf.cpp b/libs/srvconf/servconf.cpp index c038fd29..408e93fc 100644 --- a/libs/srvconf/servconf.cpp +++ b/libs/srvconf/servconf.cpp @@ -65,7 +65,7 @@ class ServConf::Impl Impl(const std::string& server, uint16_t port, const std::string& localAddress, uint16_t localPort, const std::string& login, const std::string& password); - ~Impl() { XML_ParserFree(parser); } + ~Impl() { XML_ParserFree(m_parser); } const std::string& GetStrError() const; static void Start(void* data, const char* el, const char** attr); @@ -76,23 +76,23 @@ class ServConf::Impl template int Exec(const std::string& request, C callback, void* data) { - return ExecImpl(request, P(callback, data, encoding)); + return ExecImpl(request, P(callback, data, m_encoding)); } template int Exec(const std::string& tag, const std::string& request, C callback, void* data) { - return ExecImpl(request, P(tag, callback, data, encoding)); + return ExecImpl(request, P(tag, callback, data, m_encoding)); } - const std::string& Encoding() const { return encoding; } + const std::string& Encoding() const { return m_encoding; } private: - NetTransact nt; + NetTransact m_nt; - std::string encoding; - std::string errorMsg; - XML_Parser parser; + std::string m_encoding; + std::string m_errorMsg; + XML_Parser m_parser; static bool ParserRecv(const std::string& chunk, bool last, void* data); static bool SimpleRecv(const std::string& chunk, bool last, void* data); @@ -101,14 +101,14 @@ class ServConf::Impl bool ServConf::Impl::ParserRecv(const std::string& chunk, bool last, void* data) { - auto sc = static_cast(data); + auto* sc = static_cast(data); - if (XML_Parse(sc->parser, chunk.c_str(), chunk.length(), last) == XML_STATUS_ERROR) + if (XML_Parse(sc->m_parser, chunk.c_str(), chunk.length(), last) == XML_STATUS_ERROR) { - strprintf(&sc->errorMsg, "XML parse error at line %d, %d: %s. Is last: %d", - static_cast(XML_GetCurrentLineNumber(sc->parser)), - static_cast(XML_GetCurrentColumnNumber(sc->parser)), - XML_ErrorString(XML_GetErrorCode(sc->parser)), static_cast(last)); + strprintf(&sc->m_errorMsg, "XML parse error at line %d, %d: %s. Is last: %d", + static_cast(XML_GetCurrentLineNumber(sc->m_parser)), + static_cast(XML_GetCurrentColumnNumber(sc->m_parser)), + XML_ErrorString(XML_GetErrorCode(sc->m_parser)), static_cast(last)); return false; } @@ -123,106 +123,106 @@ bool ServConf::Impl::SimpleRecv(const std::string& chunk, bool /*last*/, void* d ServConf::ServConf(const std::string& server, uint16_t port, const std::string& login, const std::string& password) - : pImpl(new Impl(server, port, login, password)) + : m_impl(new Impl(server, port, login, password)) { } ServConf::ServConf(const std::string& server, uint16_t port, const std::string& localAddress, uint16_t localPort, const std::string& login, const std::string& password) - : pImpl(new Impl(server, port, localAddress, localPort, login, password)) + : m_impl(new Impl(server, port, localAddress, localPort, login, password)) { } ServConf::~ServConf() { - delete pImpl; + delete m_impl; } int ServConf::ServerInfo(ServerInfo::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::RawXML(const std::string& request, RawXML::Callback f, void* data) { - return pImpl->RawXML(request, f, data); + return m_impl->RawXML(request, f, data); } // -- Admins -- int ServConf::GetAdmins(GetContainer::Callback::Type f, void* data) { - return pImpl->Exec >("admins", "", f, data); + return m_impl->Exec >("admins", "", f, data); } int ServConf::GetAdmin(const std::string& login, GetAdmin::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::ChgAdmin(const AdminConfOpt& conf, Simple::Callback f, void* data) { - return pImpl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); + return m_impl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); } int ServConf::AddAdmin(const std::string& login, const AdminConfOpt& conf, Simple::Callback f, void* data) { - auto res = pImpl->Exec("AddAdmin", "", f, data); + auto res = m_impl->Exec("AddAdmin", "", f, data); if (res != st_ok) return res; - return pImpl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); + return m_impl->Exec("ChgAdmin", "Encoding()) + "/>", f, data); } int ServConf::DelAdmin(const std::string& login, Simple::Callback f, void* data) { - return pImpl->Exec("DelAdmin", "", f, data); + return m_impl->Exec("DelAdmin", "", f, data); } // -- Tariffs -- int ServConf::GetTariffs(GetContainer::Callback::Type f, void* data) { - return pImpl->Exec >("tariffs", "", f, data); + return m_impl->Exec >("tariffs", "", f, data); } int ServConf::GetTariff(const std::string& name, GetTariff::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::ChgTariff(const TariffDataOpt& tariffData, Simple::Callback f, void* data) { - return pImpl->Exec("SetTariff", "" + ChgTariff::serialize(tariffData, pImpl->Encoding()) + "", f, data); + return m_impl->Exec("SetTariff", "" + ChgTariff::serialize(tariffData, m_impl->Encoding()) + "", f, data); } int ServConf::AddTariff(const std::string& name, const TariffDataOpt& tariffData, Simple::Callback f, void* data) { - auto res = pImpl->Exec("AddTariff", "", f, data); + auto res = m_impl->Exec("AddTariff", "", f, data); if (res != st_ok) return res; - return pImpl->Exec("SetTariff", "" + ChgTariff::serialize(tariffData, pImpl->Encoding()) + "", f, data); + return m_impl->Exec("SetTariff", "" + ChgTariff::serialize(tariffData, m_impl->Encoding()) + "", f, data); } int ServConf::DelTariff(const std::string& name, Simple::Callback f, void* data) { - return pImpl->Exec("DelTariff", "", f, data); + return m_impl->Exec("DelTariff", "", f, data); } // -- Users -- int ServConf::GetUsers(GetContainer::Callback::Type f, void* data) { - return pImpl->Exec >("users", "", f, data); + return m_impl->Exec >("users", "", f, data); } int ServConf::GetUser(const std::string& login, GetUser::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::ChgUser(const std::string& login, @@ -230,12 +230,12 @@ int ServConf::ChgUser(const std::string& login, const UserStatOpt& stat, Simple::Callback f, void* data) { - return pImpl->Exec("" + ChgUser::serialize(conf, stat, pImpl->Encoding()) + "", f, data); + return m_impl->Exec("" + ChgUser::serialize(conf, stat, m_impl->Encoding()) + "", f, data); } int ServConf::DelUser(const std::string& login, Simple::Callback f, void* data) { - return pImpl->Exec("DelUser", "", f, data); + return m_impl->Exec("DelUser", "", f, data); } int ServConf::AddUser(const std::string& login, @@ -243,116 +243,116 @@ int ServConf::AddUser(const std::string& login, const UserStatOpt& stat, Simple::Callback f, void* data) { - auto res = pImpl->Exec("AddUser", "", f, data); + auto res = m_impl->Exec("AddUser", "", f, data); if (res != st_ok) return res; - return pImpl->Exec("" + ChgUser::serialize(conf, stat, pImpl->Encoding()) + "", f, data); + return m_impl->Exec("" + ChgUser::serialize(conf, stat, m_impl->Encoding()) + "", f, data); } int ServConf::AuthBy(const std::string& login, AuthBy::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::SendMessage(const std::string& login, const std::string& text, Simple::Callback f, void* data) { - return pImpl->Exec("SendMessageResult", "", f, data); + return m_impl->Exec("SendMessageResult", "", f, data); } int ServConf::CheckUser(const std::string& login, const std::string& password, Simple::Callback f, void* data) { - return pImpl->Exec("CheckUser", "", f, data); + return m_impl->Exec("CheckUser", "", f, data); } // -- Services -- int ServConf::GetServices(GetContainer::Callback::Type f, void* data) { - return pImpl->Exec >("services", "", f, data); + return m_impl->Exec >("services", "", f, data); } int ServConf::GetService(const std::string& name, GetService::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::ChgService(const ServiceConfOpt& conf, Simple::Callback f, void* data) { - return pImpl->Exec("SetService", "Encoding()) + "/>", f, data); + return m_impl->Exec("SetService", "Encoding()) + "/>", f, data); } int ServConf::AddService(const std::string& name, const ServiceConfOpt& conf, Simple::Callback f, void* data) { - auto res = pImpl->Exec("AddService", "", f, data); + auto res = m_impl->Exec("AddService", "", f, data); if (res != st_ok) return res; - return pImpl->Exec("SetService", "Encoding()) + "/>", f, data); + return m_impl->Exec("SetService", "Encoding()) + "/>", f, data); } int ServConf::DelService(const std::string& name, Simple::Callback f, void* data) { - return pImpl->Exec("DelService", "", f, data); + return m_impl->Exec("DelService", "", f, data); } // -- Corporations -- int ServConf::GetCorporations(GetContainer::Callback::Type f, void* data) { - return pImpl->Exec >("corporations", "", f, data); + return m_impl->Exec >("corporations", "", f, data); } int ServConf::GetCorp(const std::string& name, GetCorp::Callback f, void* data) { - return pImpl->Exec("", f, data); + return m_impl->Exec("", f, data); } int ServConf::ChgCorp(const CorpConfOpt & conf, Simple::Callback f, void* data) { - return pImpl->Exec("SetCorp", "" + ChgCorp::serialize(conf, pImpl->Encoding()) + "", f, data); + return m_impl->Exec("SetCorp", "" + ChgCorp::serialize(conf, m_impl->Encoding()) + "", f, data); } int ServConf::AddCorp(const std::string& name, const CorpConfOpt& conf, Simple::Callback f, void* data) { - auto res = pImpl->Exec("AddCorp", "", f, data); + auto res = m_impl->Exec("AddCorp", "", f, data); if (res != st_ok) return res; - return pImpl->Exec("SetCorp", "" + ChgCorp::serialize(conf, pImpl->Encoding()) + "", f, data); + return m_impl->Exec("SetCorp", "" + ChgCorp::serialize(conf, m_impl->Encoding()) + "", f, data); } int ServConf::DelCorp(const std::string& name, Simple::Callback f, void* data) { - return pImpl->Exec("DelCorp", "", f, data); + return m_impl->Exec("DelCorp", "", f, data); } const std::string& ServConf::GetStrError() const { - return pImpl->GetStrError(); + return m_impl->GetStrError(); } //----------------------------------------------------------------------------- ServConf::Impl::Impl(const std::string& server, uint16_t port, const std::string& login, const std::string& password) - : nt(server, port, login, password) + : m_nt(server, port, login, password) { setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); - encoding = nl_langinfo(CODESET); - parser = XML_ParserCreate(NULL); + m_encoding = nl_langinfo(CODESET); + m_parser = XML_ParserCreate(NULL); } //----------------------------------------------------------------------------- ServConf::Impl::Impl(const std::string& server, uint16_t port, const std::string& localAddress, uint16_t localPort, const std::string& login, const std::string& password) - : nt(server, port, localAddress, localPort, login, password) + : m_nt(server, port, localAddress, localPort, login, password) { setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); - encoding = nl_langinfo(CODESET); - parser = XML_ParserCreate(NULL); + m_encoding = nl_langinfo(CODESET); + m_parser = XML_ParserCreate(NULL); } //----------------------------------------------------------------------------- void ServConf::Impl::Start(void* data, const char* el, const char** attr) @@ -367,51 +367,51 @@ void ServConf::Impl::End(void* data, const char* el) //----------------------------------------------------------------------------- const std::string & ServConf::Impl::GetStrError() const { - return errorMsg; + return m_errorMsg; } //----------------------------------------------------------------------------- int ServConf::Impl::ExecImpl(const std::string& request, Parser&& cp) { - XML_ParserReset(parser, NULL); - XML_SetElementHandler(parser, Start, End); - XML_SetUserData(parser, &cp); + XML_ParserReset(m_parser, NULL); + XML_SetElementHandler(m_parser, Start, End); + XML_SetUserData(m_parser, &cp); int ret = 0; - if ((ret = nt.Connect()) != st_ok) + if ((ret = m_nt.Connect()) != st_ok) { - errorMsg = nt.GetError(); - cp.Failure(errorMsg); + m_errorMsg = m_nt.GetError(); + cp.Failure(m_errorMsg); return ret; } - if ((ret = nt.Transact(request, ParserRecv, this)) != st_ok) + if ((ret = m_nt.Transact(request, ParserRecv, this)) != st_ok) { - errorMsg = nt.GetError(); - cp.Failure(errorMsg); + m_errorMsg = m_nt.GetError(); + cp.Failure(m_errorMsg); return ret; } - nt.Disconnect(); + m_nt.Disconnect(); return st_ok; } int ServConf::Impl::RawXML(const std::string& request, RawXML::Callback callback, void* data) { int ret = 0; - if ((ret = nt.Connect()) != st_ok) + if ((ret = m_nt.Connect()) != st_ok) { - errorMsg = nt.GetError(); - callback(false, errorMsg, "", data); + m_errorMsg = m_nt.GetError(); + callback(false, m_errorMsg, "", data); return ret; } std::string response; - if ((ret = nt.Transact(request, SimpleRecv, &response)) != st_ok) + if ((ret = m_nt.Transact(request, SimpleRecv, &response)) != st_ok) { - errorMsg = nt.GetError(); - callback(false, errorMsg, "", data); + m_errorMsg = m_nt.GetError(); + callback(false, m_errorMsg, "", data); return ret; } - nt.Disconnect(); + m_nt.Disconnect(); callback(true, "", response, data); return st_ok; } diff --git a/projects/sgauth/web.cpp b/projects/sgauth/web.cpp index a162acc4..5d259559 100644 --- a/projects/sgauth/web.cpp +++ b/projects/sgauth/web.cpp @@ -59,22 +59,22 @@ return NULL; } //--------------------------------------------------------------------------- WEB::WEB() - : res(0), - listenSocket(0), - outerSocket(0), - refreshPeriod(0), - listenWebAddr(0) + : m_res(0), + m_listenSocket(0), + m_outerSocket(0), + m_refreshPeriod(0), + m_listenWebAddr(0) { #ifdef WIN32 -res = WSAStartup(MAKEWORD(2,0), &wsaData); +m_res = WSAStartup(MAKEWORD(2,0), &m_wsaData); #endif for (int i = 0; i < DIR_NUM; i++) - dirName[i] = "-"; + m_dirName[i] = "-"; -refreshPeriod = 5; +m_refreshPeriod = 5; -memset(&ls, 0, sizeof(ls)); +memset(&m_ls, 0, sizeof(m_ls)); } //--------------------------------------------------------------------------- void WEB::Start() @@ -90,22 +90,22 @@ CreateThread( &pt // pointer to returned thread identifier ); #else -pthread_create(&thread, NULL, RunWeb, NULL); +pthread_create(&m_thread, NULL, RunWeb, NULL); #endif } //--------------------------------------------------------------------------- void WEB::PrepareNet() { -listenSocket = socket(PF_INET, SOCK_STREAM, 0); +m_listenSocket = socket(PF_INET, SOCK_STREAM, 0); struct sockaddr_in listenAddr; listenAddr.sin_family = AF_INET; listenAddr.sin_port = htons(LISTEN_PORT); -listenAddr.sin_addr.s_addr = listenWebAddr; +listenAddr.sin_addr.s_addr = m_listenWebAddr; #ifndef WIN32 int lng = 1; -if (0 != setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4)) +if (0 != setsockopt(m_listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4)) { printf("Setsockopt Fail\n"); printf(">>> Error %s\n", strerror(errno)); @@ -115,16 +115,16 @@ if (0 != setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &lng, 4)) #endif -res = bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)); +m_res = bind(m_listenSocket, reinterpret_cast(&listenAddr), sizeof(listenAddr)); -if (res == -1) +if (m_res == -1) { printf("Bind failed.\n"); exit(0); } -res = listen(listenSocket, 0); -if (res == -1) +m_res = listen(m_listenSocket, 0); +if (m_res == -1) { printf("Listen failed.\n"); exit(0); @@ -133,14 +133,14 @@ if (res == -1) //--------------------------------------------------------------------------- void WEB::SetRefreshPagePeriod(int p) { -refreshPeriod = p; -if (refreshPeriod <= 0 || refreshPeriod > 24*3600) - refreshPeriod = 5; +m_refreshPeriod = p; +if (m_refreshPeriod <= 0 || m_refreshPeriod > 24*3600) + m_refreshPeriod = 5; } //--------------------------------------------------------------------------- void WEB::SetListenAddr(uint32_t ip) { -listenWebAddr = ip; +m_listenWebAddr = ip; } //--------------------------------------------------------------------------- void WEB::Run() @@ -157,13 +157,13 @@ while (1) int outerAddrLen = sizeof(outerAddr); #endif - outerSocket = accept(listenSocket, (struct sockaddr*)&outerAddr, &outerAddrLen); - if (outerSocket == -1) + m_outerSocket = accept(m_listenSocket, reinterpret_cast(&outerAddr), &outerAddrLen); + if (m_outerSocket == -1) { printf(">>> Error %s\n", strerror(errno)); continue; } - recv(outerSocket, recvBuffer, sizeof(recvBuffer), 0); + recv(m_outerSocket, recvBuffer, sizeof(recvBuffer), 0); if (strncmp(recvBuffer, "GET /sgauth.css", strlen("GET /sgauth.css")) == 0) { @@ -201,9 +201,9 @@ while (1) } #ifdef WIN32 - closesocket(outerSocket); + closesocket(m_outerSocket); #else - close(outerSocket); + close(m_outerSocket); #endif } } @@ -224,7 +224,7 @@ const char * redirect = char buff[2000]; sprintf(buff, redirect, url); -send(outerSocket, buff, strlen(buff), 0); +send(m_outerSocket, buff, strlen(buff), 0); return 0; } @@ -251,167 +251,167 @@ const char * replyHeader = const char * replyFooter = "\n\n"; char replyHeaderBuffer[2000]; -sprintf(replyHeaderBuffer, replyHeader, refreshPeriod); +sprintf(replyHeaderBuffer, replyHeader, m_refreshPeriod); -send(outerSocket, replyHeaderBuffer, strlen(replyHeaderBuffer), 0); +send(m_outerSocket, replyHeaderBuffer, strlen(replyHeaderBuffer), 0); char str[512]; int st = clnp->GetAuthorized(); sprintf(str, "%s

\n", gettext("Connect")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, "%s

\n", gettext("Disconnect")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, "%s

\n", gettext("Refresh")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, "%s

\n", gettext("Exit")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, "

%s

\n" , st ? "ConnectionStateOnline":"ConnectionStateOffline", st ? "Online":"Offline"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); -sprintf(str, "

%s: %.3f

\n" , gettext("Cash"), ls.cash / 1000.0); -res = send(outerSocket, str, strlen(str), 0); +sprintf(str, "

%s: %.3f

\n" , gettext("Cash"), m_ls.cash / 1000.0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, "

%s: %s

\n" , gettext("PrepaidTraffic"), - ls.freeMb[0] == 'C' ? ls.freeMb + 1 : ls.freeMb); -res = send(outerSocket, str, strlen(str), 0); + m_ls.freeMb[0] == 'C' ? m_ls.freeMb + 1 : m_ls.freeMb); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, "\n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, " \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str, " \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); rowNum = 0; for (j = 0; j < DIR_NUM; j++) { - if (dirName[j][0] == 0) + if (m_dirName[j][0] == 0) continue; std::string s; - KOIToWin(dirName[j], &s);// +++++++++ sigsegv ========== TODO too long dir name crashes sgauth + KOIToWin(m_dirName[j], &s);// +++++++++ sigsegv ========== TODO too long dir name crashes sgauth sprintf(str, " \n", rowNum++, s.c_str()); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); } sprintf(str," \n"); -send(outerSocket, str, strlen(str), 0); +send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); -send(outerSocket, str, strlen(str), 0); +send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n", gettext("Month Upload")); -send(outerSocket, str, strlen(str), 0); +send(m_outerSocket, str, strlen(str), 0); rowNum = 0; for (j = 0; j < DIR_NUM; j++) { - if (dirName[j][0] == 0) + if (m_dirName[j][0] == 0) continue; - sprintf(str," \n", rowNum++, IntToKMG(ls.mu[j], ST_F)); - res = send(outerSocket, str, strlen(str), 0); + sprintf(str," \n", rowNum++, IntToKMG(m_ls.mu[j], ST_F)); + m_res = send(m_outerSocket, str, strlen(str), 0); } sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n", gettext("Month Download")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); rowNum = 0; for (j = 0; j < DIR_NUM; j++) { - if (dirName[j][0] == 0) + if (m_dirName[j][0] == 0) continue; - sprintf(str," \n", rowNum++, IntToKMG(ls.md[j], ST_F)); - res = send(outerSocket, str, strlen(str), 0); + sprintf(str," \n", rowNum++, IntToKMG(m_ls.md[j], ST_F)); + m_res = send(m_outerSocket, str, strlen(str), 0); } sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n", gettext("Session Upload")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); rowNum = 0; for (j = 0; j < DIR_NUM; j++) { - if (dirName[j][0] == 0) + if (m_dirName[j][0] == 0) continue; - sprintf(str," \n", rowNum++, IntToKMG(ls.su[j], ST_F)); - res = send(outerSocket, str, strlen(str), 0); + sprintf(str," \n", rowNum++, IntToKMG(m_ls.su[j], ST_F)); + m_res = send(m_outerSocket, str, strlen(str), 0); } sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n", gettext("Session Download")); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); for (j = 0; j < DIR_NUM; j++) { - if (dirName[j][0] == 0) + if (m_dirName[j][0] == 0) continue; - sprintf(str," \n", j, IntToKMG(ls.sd[j], ST_F)); - res = send(outerSocket, str, strlen(str), 0); + sprintf(str," \n", j, IntToKMG(m_ls.sd[j], ST_F)); + m_res = send(m_outerSocket, str, strlen(str), 0); } sprintf(str," \n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str,"
 %s
%s%s%s
%s%s%s
%s%s%s
%s%s%s
\n"); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); rowNum = 0; -if (!messages.empty()) +if (!m_messages.empty()) { sprintf(str," \n"); - res = send(outerSocket, str, strlen(str), 0); + m_res = send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); std::list::reverse_iterator it; - it = messages.rbegin(); - while (it != messages.rend()) + it = m_messages.rbegin(); + while (it != m_messages.rend()) { sprintf(str," \n", rowNum); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n", it->recvTime.c_str()); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n", it->msg.c_str()); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); sprintf(str," \n"); - send(outerSocket, str, strlen(str), 0); + send(m_outerSocket, str, strlen(str), 0); ++it; ++rowNum; } sprintf(str,"
DateText
%s%s
\n"); - res = send(outerSocket, str, strlen(str), 0); + m_res = send(m_outerSocket, str, strlen(str), 0); } time_t t = time(NULL); sprintf(str,"Îáíîâëåíî: %s" , ctime(&t)); -res = send(outerSocket, str, strlen(str), 0); +m_res = send(m_outerSocket, str, strlen(str), 0); -send(outerSocket, replyFooter, strlen(replyFooter), 0); +send(m_outerSocket, replyFooter, strlen(replyFooter), 0); return 0; } @@ -425,16 +425,16 @@ const char * replyHeader = const char * replyFooter= "\n\n"; -send(outerSocket, replyHeader, strlen(replyHeader), 0); -send(outerSocket, SGAuth::css, strlen(SGAuth::css), 0); -send(outerSocket, replyFooter, strlen(replyFooter), 0); +send(m_outerSocket, replyHeader, strlen(replyHeader), 0); +send(m_outerSocket, SGAuth::css, strlen(SGAuth::css), 0); +send(m_outerSocket, replyFooter, strlen(replyFooter), 0); return 0; } //--------------------------------------------------------------------------- void WEB::SetDirName(const std::string & dn, int n) { -web->dirName[n] = dn; +web->m_dirName[n] = dn; } //--------------------------------------------------------------------------- void WEB::AddMessage(const std::string & message, int type) @@ -446,16 +446,16 @@ m.msg = message; m.type = type; m.recvTime = ctime(&t); -messages.push_back(m); +m_messages.push_back(m); -if (messages.size() > MAX_MESSAGES) - messages.pop_front(); +if (m_messages.size() > MAX_MESSAGES) + m_messages.pop_front(); } //--------------------------------------------------------------------------- void WEB::UpdateStat(const LOADSTAT & ls) { -memcpy((void*)&(WEB::ls), &ls, sizeof(LOADSTAT)); +memcpy(&m_ls, &ls, sizeof(LOADSTAT)); } //--------------------------------------------------------------------------- diff --git a/projects/sgauth/web.h b/projects/sgauth/web.h index a933230a..d086125c 100644 --- a/projects/sgauth/web.h +++ b/projects/sgauth/web.h @@ -23,6 +23,12 @@ $Date: 2007/12/17 08:39:08 $ */ +#include "stg/const.h" +#include "stg/ia_packets.h" + +#include +#include + #ifndef WIN32 #include #include @@ -36,53 +42,47 @@ #include #endif -#include -#include - -#include "stg/const.h" -#include "stg/ia_packets.h" - #define MAX_MESSAGES (10) //----------------------------------------------------------------------------- struct STG_MESSAGE { -std::string msg; -std::string recvTime; -int type; + std::string msg; + std::string recvTime; + int type; }; //----------------------------------------------------------------------------- class WEB { -public: - WEB(); - void Run(); - void SetDirName(const std::string & dn, int n); - void SetRefreshPagePeriod(int p); - void SetListenAddr(uint32_t ip); - void AddMessage(const std::string & message, int type); - void UpdateStat(const LOADSTAT & ls); - void Start(); -private: - void PrepareNet(); - int SendReply(); - int SendCSS(); - int Redirect(const char * url); + public: + WEB(); + void Run(); + void SetDirName(const std::string & dn, int n); + void SetRefreshPagePeriod(int p); + void SetListenAddr(uint32_t ip); + void AddMessage(const std::string & message, int type); + void UpdateStat(const LOADSTAT & ls); + void Start(); + private: + void PrepareNet(); + int SendReply(); + int SendCSS(); + int Redirect(const char * url); - #ifdef WIN32 - WSADATA wsaData; - #else - pthread_t thread; - #endif + #ifdef WIN32 + WSADATA m_wsaData; + #else + pthread_t m_thread; + #endif - std::string dirName[DIR_NUM]; - int res; - int listenSocket; - int outerSocket; - int refreshPeriod; + std::string m_dirName[DIR_NUM]; + int m_res; + int m_listenSocket; + int m_outerSocket; + int m_refreshPeriod; - uint32_t listenWebAddr; - LOADSTAT ls; + uint32_t m_listenWebAddr; + LOADSTAT m_ls; - std::list messages; + std::list m_messages; }; //----------------------------------------------------------------------------- diff --git a/projects/sgconf/options.cpp b/projects/sgconf/options.cpp index 06378d1c..1f02fd98 100644 --- a/projects/sgconf/options.cpp +++ b/projects/sgconf/options.cpp @@ -37,7 +37,7 @@ namespace { template -void ReadConfigFile(const std::string & filePath, void (C::* callback)(const std::string&, const std::string&), C * obj) +void ReadConfigFile(const std::string& filePath, void (C::* callback)(const std::string&, const std::string&), C* obj) { std::ifstream stream(filePath.c_str()); std::string line; @@ -70,10 +70,10 @@ using SGCONF::OPTION_BLOCKS; using SGCONF::ACTION; using SGCONF::PARSER_STATE; -OPTION::OPTION(const std::string & shortName, - const std::string & longName, +OPTION::OPTION(const std::string& shortName, + const std::string& longName, std::unique_ptr action, - const std::string & description) + const std::string& description) : m_shortName(shortName), m_longName(longName), m_action(std::move(action)), @@ -81,9 +81,9 @@ OPTION::OPTION(const std::string & shortName, { } -OPTION::OPTION(const std::string & longName, +OPTION::OPTION(const std::string& longName, std::unique_ptr action, - const std::string & description) + const std::string& description) : m_longName(longName), m_action(std::move(action)), m_description(description) @@ -103,7 +103,7 @@ void OPTION::Help(size_t level) const m_action->Suboptions().Help(level); } -bool OPTION::Check(const char * arg) const +bool OPTION::Check(const char* arg) const { if (arg == NULL) return false; @@ -117,7 +117,7 @@ bool OPTION::Check(const char * arg) const return m_shortName == arg; } -PARSER_STATE OPTION::Parse(int argc, char ** argv, void * data) +PARSER_STATE OPTION::Parse(int argc, char** argv, void* data) { if (!m_action) throw ERROR("Option is not defined."); @@ -125,7 +125,7 @@ PARSER_STATE OPTION::Parse(int argc, char ** argv, void * data) { return m_action->Parse(argc, argv, data); } - catch (const ACTION::ERROR & ex) + catch (const ACTION::ERROR& ex) { if (m_longName.empty()) throw ERROR("-" + m_shortName + ": " + ex.what()); @@ -135,7 +135,7 @@ PARSER_STATE OPTION::Parse(int argc, char ** argv, void * data) } } -void OPTION::ParseValue(const std::string & value) +void OPTION::ParseValue(const std::string& value) { if (!m_action) throw ERROR("Option is not defined."); @@ -143,24 +143,24 @@ void OPTION::ParseValue(const std::string & value) { return m_action->ParseValue(value); } - catch (const ACTION::ERROR & ex) + catch (const ACTION::ERROR& ex) { throw ERROR(m_longName + ": " + ex.what()); } } -OPTION_BLOCK & OPTION_BLOCK::Add(const std::string & shortName, - const std::string & longName, - std::unique_ptr action, - const std::string & description) +OPTION_BLOCK& OPTION_BLOCK::Add(const std::string& shortName, + const std::string& longName, + std::unique_ptr action, + const std::string& description) { m_options.emplace_back(shortName, longName, std::move(action), description); return *this; } -OPTION_BLOCK & OPTION_BLOCK::Add(const std::string & longName, - std::unique_ptr action, - const std::string & description) +OPTION_BLOCK& OPTION_BLOCK::Add(const std::string& longName, + std::unique_ptr action, + const std::string& description) { m_options.emplace_back(longName, std::move(action), description); return *this; @@ -176,7 +176,7 @@ void OPTION_BLOCK::Help(size_t level) const option.Help(level + 1); } -PARSER_STATE OPTION_BLOCK::Parse(int argc, char ** argv, void * data) +PARSER_STATE OPTION_BLOCK::Parse(int argc, char** argv, void* data) { PARSER_STATE state(false, argc, argv); if (state.argc == 0) @@ -192,14 +192,14 @@ PARSER_STATE OPTION_BLOCK::Parse(int argc, char ** argv, void * data) return state; } -void OPTION_BLOCK::ParseFile(const std::string & filePath) +void OPTION_BLOCK::ParseFile(const std::string& filePath) { if (access(filePath.c_str(), R_OK)) throw ERROR("File '" + filePath + "' does not exists."); ReadConfigFile(filePath, &OPTION_BLOCK::OptionCallback, this); } -void OPTION_BLOCK::OptionCallback(const std::string & key, const std::string & value) +void OPTION_BLOCK::OptionCallback(const std::string& key, const std::string& value) { for (auto& option : m_options) if (option.Name() == key) @@ -215,7 +215,7 @@ void OPTION_BLOCKS::Help(size_t level) const } } -PARSER_STATE OPTION_BLOCKS::Parse(int argc, char ** argv) +PARSER_STATE OPTION_BLOCKS::Parse(int argc, char** argv) { PARSER_STATE state(false, argc, argv); auto it = m_blocks.begin(); diff --git a/projects/sgconf/options.h b/projects/sgconf/options.h index 012b5167..f2f0a0eb 100644 --- a/projects/sgconf/options.h +++ b/projects/sgconf/options.h @@ -36,26 +36,26 @@ struct PARSER_STATE; class OPTION { public: - OPTION(const std::string & shortName, - const std::string & longName, + OPTION(const std::string& shortName, + const std::string& longName, std::unique_ptr action, - const std::string & description); - OPTION(const std::string & longName, + const std::string& description); + OPTION(const std::string& longName, std::unique_ptr action, - const std::string & description); + const std::string& description); OPTION(OPTION&& rhs) = default; - OPTION& operator=(OPTION& rhs) = default; + OPTION& operator=(OPTION&& rhs) = default; void Help(size_t level = 0) const; - PARSER_STATE Parse(int argc, char ** argv, void * data); + PARSER_STATE Parse(int argc, char** argv, void* data); void ParseValue(const std::string & value); - bool Check(const char * arg) const; - const std::string & Name() const { return m_longName; } + bool Check(const char* arg) const; + const std::string& Name() const { return m_longName; } struct ERROR : std::runtime_error { - explicit ERROR(const std::string & message) + explicit ERROR(const std::string & message) noexcept : std::runtime_error(message.c_str()) {} }; @@ -70,28 +70,28 @@ class OPTION_BLOCK { public: OPTION_BLOCK() {} - explicit OPTION_BLOCK(const std::string & description) + explicit OPTION_BLOCK(const std::string& description) : m_description(description) {} OPTION_BLOCK(OPTION_BLOCK&&) = default; OPTION_BLOCK& operator=(OPTION_BLOCK&&) = default; - OPTION_BLOCK & Add(const std::string & shortName, - const std::string & longName, - std::unique_ptr action, - const std::string & description); - OPTION_BLOCK & Add(const std::string & longName, - std::unique_ptr action, - const std::string & description); + OPTION_BLOCK& Add(const std::string& shortName, + const std::string& longName, + std::unique_ptr action, + const std::string& description); + OPTION_BLOCK& Add(const std::string& longName, + std::unique_ptr action, + const std::string& description); void Help(size_t level) const; - PARSER_STATE Parse(int argc, char ** argv, void * data = NULL); - void ParseFile(const std::string & filePath); + PARSER_STATE Parse(int argc, char** argv, void* data = NULL); + void ParseFile(const std::string& filePath); struct ERROR : std::runtime_error { - explicit ERROR(const std::string & message) + explicit ERROR(const std::string & message) noexcept : std::runtime_error(message.c_str()) {} }; @@ -99,17 +99,17 @@ class OPTION_BLOCK std::vector