]> git.stg.codes - stg.git/commitdiff
Use std::jthread and C++17.
authorMaksym Mamontov <madf@madf.info>
Tue, 12 Jul 2022 20:23:44 +0000 (23:23 +0300)
committerMaksym Mamontov <madf@madf.info>
Tue, 12 Jul 2022 20:23:44 +0000 (23:23 +0300)
51 files changed:
.gitmodules [new file with mode: 0644]
3rdparty/jthread [new submodule]
CMakeLists.txt
libs/CMakeLists.txt
projects/CMakeLists.txt
projects/stargazer/CMakeLists.txt
projects/stargazer/actions.h
projects/stargazer/actions.inl.h
projects/stargazer/main.cpp
projects/stargazer/plugins/CMakeLists.txt
projects/stargazer/plugins/configuration/sgconfig/configproto.cpp
projects/stargazer/plugins/configuration/sgconfig/configproto.h
projects/stargazer/plugins/configuration/sgconfig/conn.cpp
projects/stargazer/plugins/configuration/sgconfig/conn.h
projects/stargazer/plugins/configuration/sgconfig/parser_admins.h
projects/stargazer/plugins/configuration/sgconfig/parser_auth_by.h
projects/stargazer/plugins/configuration/sgconfig/parser_message.h
projects/stargazer/plugins/configuration/sgconfig/parser_server_info.h
projects/stargazer/plugins/configuration/sgconfig/parser_services.h
projects/stargazer/plugins/configuration/sgconfig/parser_tariffs.cpp
projects/stargazer/plugins/configuration/sgconfig/parser_tariffs.h
projects/stargazer/plugins/configuration/sgconfig/parser_user_info.h
projects/stargazer/plugins/configuration/sgconfig/parser_users.cpp
projects/stargazer/plugins/configuration/sgconfig/parser_users.h
projects/stargazer/plugins/configuration/sgconfig/stgconfig.cpp
projects/stargazer/plugins/configuration/sgconfig/stgconfig.h
projects/stargazer/plugins/other/ping/ping.cpp
projects/stargazer/plugins/other/ping/ping.h
projects/stargazer/plugins/other/rscript/rscript.cpp
projects/stargazer/plugins/other/rscript/rscript.h
projects/stargazer/plugins/other/rscript/send_functor.h [deleted file]
projects/stargazer/plugins/other/smux/smux.cpp
projects/stargazer/plugins/other/smux/smux.h
projects/stargazer/plugins/other/smux/tables.h
projects/stargazer/plugins/other/smux/types.cpp
projects/stargazer/plugins/store/firebird/firebird_store_admins.cpp
projects/stargazer/plugins/store/firebird/firebird_store_corporations.cpp
projects/stargazer/plugins/store/firebird/firebird_store_services.cpp
projects/stargazer/plugins/store/firebird/firebird_store_tariffs.cpp
projects/stargazer/plugins/store/firebird/firebird_store_users.cpp
projects/stargazer/plugins/store/mysql/mysql_store.cpp
projects/stargazer/settings_impl.cpp
projects/stargazer/tariffs_impl.cpp
projects/stargazer/traffcounter_impl.cpp
projects/stargazer/traffcounter_impl.h
projects/stargazer/user_impl.cpp
projects/stargazer/users_impl.cpp
projects/stargazer/users_impl.h
tests/CMakeLists.txt
tests/test_filter_params_log.cpp
tests/test_reconnect_on_tariff_change.cpp

diff --git a/.gitmodules b/.gitmodules
new file mode 100644 (file)
index 0000000..67d282a
--- /dev/null
@@ -0,0 +1,3 @@
+[submodule "3rdparty/jthread"]
+       path = 3rdparty/jthread
+       url = https://github.com/josuttis/jthread.git
diff --git a/3rdparty/jthread b/3rdparty/jthread
new file mode 160000 (submodule)
index 0000000..0fa8d39
--- /dev/null
@@ -0,0 +1 @@
+Subproject commit 0fa8d394254886c555d6faccd0a3de819b7d47f8
index 100f9c00981a4a02e2e5949c9b4bd2ca585fccf5..6263a2434d1686d2e0ebc5c6b52323f2f43ff440 100644 (file)
@@ -4,10 +4,6 @@ project ( Stargazer )
 
 set ( CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules )
 
-if ( CMAKE_COMPILER_IS_GNUCC AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.5 )
-    message ( FATAL_ERROR "Require at least gcc-6.5" )
-endif( CMAKE_COMPILER_IS_GNUCC AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 6.5 )
-
 option ( BUILD_STG "Build Stargazer server." OFF )
 option ( BUILD_SGCONF "Build SGConf client." OFF )
 option ( BUILD_RSCRIPTD "Build RScriptD server." OFF )
@@ -106,7 +102,7 @@ if ( BUILD_MOD_SMUX OR BUILD_ALL_LIBS )
 endif ( BUILD_MOD_SMUX OR BUILD_ALL_LIBS )
 
 enable_language (CXX)
-set (CMAKE_CXX_STANDARD 14)
+set (CMAKE_CXX_STANDARD 17)
 set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -W -Wall -Wextra -Wshadow -Wno-long-long -Wold-style-cast -Wstrict-aliasing -pedantic")
 
 if ( CMAKE_COMPILER_IS_GNUCC )
@@ -141,10 +137,12 @@ else ()
 endif ()
 
 include_directories ( include )
+include_directories ( 3rdparty/jthread/source )
 
 add_subdirectory ( libs )
 add_subdirectory ( projects )
 
 if ( BUILD_TESTS )
+    enable_testing ()
     add_subdirectory ( tests )
 endif ( BUILD_TESTS )
index d6e8494181bdd045035d9c1bce336cbb61c40e6e..7d9713156a6e146f3dd214fca539a8e8847319a5 100644 (file)
@@ -28,11 +28,11 @@ if ( BUILD_LIB_IA )
     target_link_libraries ( ia crypto common )
 endif ( BUILD_LIB_IA )
 
-if ( BUILD_LIB_IBPP )
-    add_library ( ibpp STATIC ibpp/all_in_one.cpp )
-    target_include_directories ( ibpp PUBLIC ibpp/include )
-    target_compile_options ( ibpp PRIVATE -Wno-old-style-cast $<$<CXX_COMPILER_ID:GNU>:-Wno-useless-cast> )
-endif ( BUILD_LIB_IBPP )
+#if ( BUILD_LIB_IBPP )
+#    add_library ( ibpp STATIC ibpp/all_in_one.cpp )
+#    target_include_directories ( ibpp PUBLIC ibpp/include )
+#    target_compile_options ( ibpp PRIVATE -Wno-old-style-cast $<$<CXX_COMPILER_ID:GNU>:-Wno-useless-cast> )
+#endif ( BUILD_LIB_IBPP )
 
 if ( BUILD_LIB_LOGGER )
     add_library ( logger STATIC logger/logger.cpp )
index fda001c66c36255b0316991513a00f97f4a80f37..3fec99f1ca474b1dae0378e75b4227f7204d32bb 100644 (file)
@@ -14,4 +14,4 @@ if ( BUILD_STG )
     add_subdirectory ( stargazer )
 endif ( BUILD_STG )
 
-add_custom_target (cppcheck COMMAND cppcheck --enable=all --std=c++14 ${CMAKE_SOURCE_DIR}/rscriptd ${CMAKE_SOURCE_DIR}/sgauth ${CMAKE_SOURCE_DIR}/sgconf ${CMAKE_SOURCE_DIR}/stargazer)
+add_custom_target (cppcheck COMMAND /usr/bin/cppcheck --enable=all --std=c++14 ${CMAKE_SOURCE_DIR}/libs ${CMAKE_SOURCE_DIR}/projects/rscriptd ${CMAKE_SOURCE_DIR}/projects/sgauth ${CMAKE_SOURCE_DIR}/projects/sgconf ${CMAKE_SOURCE_DIR}/projects/stargazer)
index 1670de26cbb1c82c3ff93ec419d1d1e4075286d0..073c71652f4cf4bc73e3159e1d3938a0eb75eb7f 100644 (file)
@@ -12,7 +12,6 @@ set ( CPP_FILES main.cpp
                 plugin_mgr.cpp
                 settings_impl.cpp
                 stg_timer.cpp
-                timer_impl.cpp
                 store_loader.cpp
                 traffcounter_impl.cpp
                 user_property.cpp )
index eea72b77aa7357b456b955c35f1b3d33aa18a62f..33c9a8fdb4b57e282ddb832f4d075cbddf727e1c 100644 (file)
@@ -13,9 +13,9 @@
 //
 // actionsList.InvokeAll();
 
-#include <pthread.h>
 #include <vector>
 #include <functional>
+#include <mutex>
 
 // Generalized actor type - a method of some class with one argument
 template <class ACTIVE_CLASS, typename DATA_TYPE>
@@ -42,7 +42,7 @@ public:
            typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
            DATA_TYPE d)
         : activeClass(ac), actor(a), data(d) {}
-    void Invoke();
+    void Invoke() override;
 private:
     ACTION(const ACTION<ACTIVE_CLASS, DATA_TYPE> & rvalue);
     ACTION<ACTIVE_CLASS, DATA_TYPE> & operator=(const ACTION<ACTIVE_CLASS, DATA_TYPE> & rvalue);
@@ -82,7 +82,7 @@ public:
     // Invoke all actions in the list
     void InvokeAll();
 private:
-    mutable pthread_mutex_t mutex;
+    mutable std::mutex m_mutex;
 };
 
 #include "actions.inl.h"
index 1b713f1d94e39b7cca999f78cd14a4d55fe4e7a8..7a0bac35158ecee058712a490628753ae0ed0c48 100644 (file)
@@ -15,75 +15,66 @@ void ACTION<ACTIVE_CLASS, DATA_TYPE>::Invoke()
 
 inline
 ACTIONS_LIST::ACTIONS_LIST()
-    : mutex()
 {
-pthread_mutex_init(&mutex, NULL);
 }
 
 // Delete all actions before deleting list
 inline
 ACTIONS_LIST::~ACTIONS_LIST()
 {
+std::lock_guard lock(m_mutex);
 
-    {
-    STG_LOCKER lock(&mutex);
-
-    parent::iterator it(parent::begin());
-    while (it != parent::end())
-        {
-        delete *it++;
-        }
-    }
-
-pthread_mutex_destroy(&mutex);
+parent::iterator it(parent::begin());
+while (it != parent::end())
+    delete *it++;
 }
 
 inline
 ACTIONS_LIST::parent::iterator ACTIONS_LIST::begin()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 return parent::begin();
 }
 
 inline
 ACTIONS_LIST::parent::iterator ACTIONS_LIST::end()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 return parent::end();
 }
 
 inline
 ACTIONS_LIST::parent::const_iterator ACTIONS_LIST::begin() const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 return parent::begin();
 }
 
 inline
 ACTIONS_LIST::parent::const_iterator ACTIONS_LIST::end() const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 return parent::end();
 }
 
 inline
 bool ACTIONS_LIST::empty() const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 return parent::empty();
 }
 
 inline
 size_t ACTIONS_LIST::size() const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 return parent::size();
 }
 
 inline
 void ACTIONS_LIST::swap(ACTIONS_LIST & list)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 parent::swap(list);
 }
 
@@ -93,14 +84,14 @@ void ACTIONS_LIST::Enqueue(ACTIVE_CLASS & ac,
                            typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
                            DATA_TYPE d)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 push_back(new ACTION<ACTIVE_CLASS, DATA_TYPE>(ac, a, d));
 }
 
 inline
 void ACTIONS_LIST::InvokeAll()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 std::for_each(
         parent::begin(),
         parent::end(),
index 825cba582e344faf7dfc5df230b5b192d7b7b043..d70f50a3d0af0a4515c0e5056238a47ae76098d0 100644 (file)
@@ -304,6 +304,7 @@ int main(int argc, char* argv[])
 
     AdminsImpl admins(store);
     TariffsImpl tariffs(&store);
+    tariffs.ReadTariffs();
     ServicesImpl services(&store);
     CorporationsImpl corps(&store);
     UsersImpl users(&settings, &store, &tariffs, services, admins.sysAdmin());
index a8958c4304f84225f45b368aac4c21c7fd0e3834..9f16024be565e16b1945429a7577bbc8040b1a36 100644 (file)
@@ -121,19 +121,19 @@ if ( BUILD_MOD_STORE_FILES )
     set_target_properties ( mod_store_files PROPERTIES PREFIX "" )
 endif ( BUILD_MOD_STORE_FILES )
 
-if ( BUILD_MOD_STORE_FIREBIRD )
-    find_package ( FBClient REQUIRED )
-    add_library ( mod_store_firebird MODULE store/firebird/firebird_store.cpp
-                                            store/firebird/firebird_store_admins.cpp
-                                            store/firebird/firebird_store_corporations.cpp
-                                            store/firebird/firebird_store_messages.cpp
-                                            store/firebird/firebird_store_services.cpp
-                                            store/firebird/firebird_store_tariffs.cpp
-                                            store/firebird/firebird_store_users.cpp
-                                            store/firebird/firebird_store_utils.cpp )
-    target_link_libraries ( mod_store_firebird crypto common logger ibpp FBClient::FBClient )
-    set_target_properties ( mod_store_firebird PROPERTIES PREFIX "" )
-endif ( BUILD_MOD_STORE_FIREBIRD )
+#if ( BUILD_MOD_STORE_FIREBIRD )
+#    find_package ( FBClient REQUIRED )
+#    add_library ( mod_store_firebird MODULE store/firebird/firebird_store.cpp
+#                                            store/firebird/firebird_store_admins.cpp
+#                                            store/firebird/firebird_store_corporations.cpp
+#                                            store/firebird/firebird_store_messages.cpp
+#                                            store/firebird/firebird_store_services.cpp
+#                                            store/firebird/firebird_store_tariffs.cpp
+#                                            store/firebird/firebird_store_users.cpp
+#                                            store/firebird/firebird_store_utils.cpp )
+#    target_link_libraries ( mod_store_firebird crypto common logger ibpp FBClient::FBClient )
+#    set_target_properties ( mod_store_firebird PROPERTIES PREFIX "" )
+#endif ( BUILD_MOD_STORE_FIREBIRD )
 
 if ( BUILD_MOD_STORE_MYSQL )
     find_package ( MySQLConnector REQUIRED )
index 011979046169a6f51592694d8edee410abd83a65..5c176f4568fd6fc5cb76f04dd2518b43d598390f 100644 (file)
@@ -60,7 +60,6 @@ CONFIGPROTO::CONFIGPROTO(STG::PluginLogger & l)
       m_store(NULL),
       m_port(0),
       m_bindAddress("0.0.0.0"),
-      m_running(false),
       m_stopped(true),
       m_logger(l),
       m_listenSocket(-1)
@@ -120,14 +119,12 @@ int CONFIGPROTO::Prepare()
 
     RegisterParsers();
 
-    m_running = true;
     m_stopped = false;
     return 0;
 }
 
 int CONFIGPROTO::Stop()
 {
-    m_running = false;
     for (int i = 0; i < 5 && !m_stopped; ++i)
     {
         struct timespec ts = {0, 200000000};
@@ -146,9 +143,9 @@ int CONFIGPROTO::Stop()
     return 0;
 }
 
-void CONFIGPROTO::Run()
+void CONFIGPROTO::Run(std::stop_token token)
 {
-    while (m_running)
+    while (!token.stop_requested())
     {
         fd_set fds;
 
@@ -166,7 +163,7 @@ void CONFIGPROTO::Run()
             m_logger(m_errorStr);
             break;
         }
-        if (!m_running)
+        if (token.stop_requested())
             break;
         if (res > 0)
             HandleEvents(fds);
index 77219385b595c8fbb949f6361e8e20aad32d44f1..c5ddd579f4e71db9f24d2d75a75b0285e32d0915 100644 (file)
 
 #include <string>
 #include <deque>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 #include <cstdint>
 
 #include <sys/select.h>
@@ -67,7 +71,7 @@ public:
     int Prepare();
     int Stop();
     const std::string & GetStrError() const { return m_errorStr; }
-    void Run();
+    void Run(std::stop_token token);
 
 private:
     CONFIGPROTO(const CONFIGPROTO & rvalue);
@@ -83,7 +87,6 @@ private:
 
     uint16_t         m_port;
     std::string      m_bindAddress;
-    bool             m_running;
     bool             m_stopped;
     STG::PluginLogger &   m_logger;
     int              m_listenSocket;
index 92d74796bb180e87072a0ec2f855cb0b50de7e5d..513218e29ae20283ff5ca25a4eee154a6177f00b 100644 (file)
@@ -225,7 +225,7 @@ bool Conn::DataCallback(const void * block, size_t size, void * data)
         printfd(__FILE__, "XML parse error at line %d, %d: %s. Is final: %d\n",
                   static_cast<int>(XML_GetCurrentLineNumber(state.conn.m_xmlParser)),
                   static_cast<int>(XML_GetCurrentColumnNumber(state.conn.m_xmlParser)),
-                  XML_ErrorString(XML_GetErrorCode(state.conn.m_xmlParser)), (int)state.final);
+                  XML_ErrorString(XML_GetErrorCode(state.conn.m_xmlParser)), static_cast<int>(state.final));
         printfd(__FILE__, "Data block: '%s' of size %d\n", xml, length);
         state.conn.m_state = ERROR;
         return false;
index c96be90b8eac0be0d6d089700c960cb6df9b14b3..a98e593bb6263bfeaca69c8352f384364fe6b0f4 100644 (file)
@@ -60,7 +60,7 @@ class Conn
         ~Conn();
 
         int Sock() const { return m_sock; }
-        uint32_t IP() const { return *(uint32_t *)(&m_addr.sin_addr); }
+        uint32_t IP() const { return *reinterpret_cast<const uint32_t *>(&m_addr.sin_addr); }
         uint16_t Port() const { return ntohs(m_addr.sin_port); }
 
         std::string endpoint() const { return inet_ntostring(IP()) + ":" + std::to_string(Port()); }
index 423ac3cdb56beff356b2ed96447d25fcd403a076..efad0d63d7510144835fe87fadb739002b5e0aad 100644 (file)
@@ -44,7 +44,7 @@ class GET_ADMINS: public BASE_PARSER
         {
             public:
                 explicit FACTORY(const Admins & admins) : m_admins(admins) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_ADMINS(admin, m_admins); }
+                BASE_PARSER * create(const Admin & admin) override { return new GET_ADMINS(admin, m_admins); }
                 static void Register(REGISTRY & registry, const Admins & admins)
                 { registry[ToLower(tag)] = new FACTORY(admins); }
             private:
@@ -59,7 +59,7 @@ class GET_ADMINS: public BASE_PARSER
     private:
         const Admins & m_admins;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class ADD_ADMIN: public BASE_PARSER
@@ -69,7 +69,7 @@ class ADD_ADMIN: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Admins & admins) : m_admins(admins) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new ADD_ADMIN(admin, m_admins); }
+                BASE_PARSER * create(const Admin & admin) override { return new ADD_ADMIN(admin, m_admins); }
                 static void Register(REGISTRY & registry, Admins & admins)
                 { registry[ToLower(tag)] = new FACTORY(admins); }
             private:
@@ -80,13 +80,13 @@ class ADD_ADMIN: public BASE_PARSER
 
         ADD_ADMIN(const Admin & admin, Admins & admins)
             : BASE_PARSER(admin, tag), m_admins(admins) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string m_admin;
         Admins & m_admins;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class DEL_ADMIN: public BASE_PARSER
@@ -96,7 +96,7 @@ class DEL_ADMIN: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Admins & admins) : m_admins(admins) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new DEL_ADMIN(admin, m_admins); }
+                BASE_PARSER * create(const Admin & admin) override { return new DEL_ADMIN(admin, m_admins); }
                 static void Register(REGISTRY & registry, Admins & admins)
                 { registry[ToLower(tag)] = new FACTORY(admins); }
             private:
@@ -107,13 +107,13 @@ class DEL_ADMIN: public BASE_PARSER
 
         DEL_ADMIN(const Admin & admin, Admins & admins)
             : BASE_PARSER(admin, tag), m_admins(admins) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string m_admin;
         Admins & m_admins;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class CHG_ADMIN: public BASE_PARSER
@@ -123,7 +123,7 @@ class CHG_ADMIN: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Admins & admins) : m_admins(admins) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new CHG_ADMIN(admin, m_admins); }
+                BASE_PARSER * create(const Admin & admin) override { return new CHG_ADMIN(admin, m_admins); }
                 static void Register(REGISTRY & registry, Admins & admins)
                 { registry[ToLower(tag)] = new FACTORY(admins); }
             private:
@@ -134,7 +134,7 @@ class CHG_ADMIN: public BASE_PARSER
 
         CHG_ADMIN(const Admin & admin, Admins & admins)
             : BASE_PARSER(admin, tag), m_admins(admins) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string login;
@@ -142,7 +142,7 @@ class CHG_ADMIN: public BASE_PARSER
         Optional<std::string> privAsString;
         Admins & m_admins;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 } // namespace PARSER
index 50164748adcf1b577d774c55bd59e9829c28575a..a8d35d04f8299680b154eefcfb715e771754ea95 100644 (file)
@@ -42,7 +42,7 @@ class AUTH_BY : public BASE_PARSER
         {
             public:
                 explicit FACTORY(const Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new AUTH_BY(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new AUTH_BY(admin, m_users); }
                 static void Register(REGISTRY & registry, const Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -53,13 +53,13 @@ class AUTH_BY : public BASE_PARSER
 
         AUTH_BY(const Admin & admin, const Users & users)
             : BASE_PARSER(admin, tag), m_users(users) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         const Users & m_users;
         std::string m_login;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 } // namespace PARSER
index 3f75993a9dda441be24bd66c22126df832a94852..379c2b706173f37b80fe572c8025a3ecd531f50a 100644 (file)
@@ -45,7 +45,7 @@ class SEND_MESSAGE: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new SEND_MESSAGE(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new SEND_MESSAGE(admin, m_users); }
                 static void Register(REGISTRY & registry, Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -56,8 +56,8 @@ class SEND_MESSAGE: public BASE_PARSER
 
         SEND_MESSAGE(const Admin & admin, Users & users)
             : BASE_PARSER(admin, tag), m_users(users), m_result(res_ok), m_user(NULL) {}
-        int Start(void *data, const char *el, const char **attr);
-        int End(void *data, const char *el);
+        int Start(void *data, const char *el, const char **attr) override;
+        int End(void *data, const char *el) override;
 
     private:
         Users & m_users;
@@ -67,7 +67,7 @@ class SEND_MESSAGE: public BASE_PARSER
         User * m_user;
 
         int ParseLogins(const char * logins);
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 } // namespace PARSER
index fad241293ef40b14f4a63332ef5cee7571a9317b..fc4c838cd70db29ec406cebb0c7dbda5f32ffa5b 100644 (file)
@@ -43,7 +43,7 @@ class GET_SERVER_INFO: public BASE_PARSER {
             public:
                 FACTORY(const Settings & settings, const Users & users, const Tariffs & tariffs)
                     : m_settings(settings), m_users(users), m_tariffs(tariffs) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_SERVER_INFO(admin, m_settings, m_users, m_tariffs); }
+                BASE_PARSER * create(const Admin & admin) override { return new GET_SERVER_INFO(admin, m_settings, m_users, m_tariffs); }
                 static void Register(REGISTRY & registry, const Settings & settings, const Users & users, const Tariffs & tariffs)
                 { registry[ToLower(tag)] = new FACTORY(settings, users, tariffs); }
             private:
@@ -69,7 +69,7 @@ class GET_SERVER_INFO: public BASE_PARSER {
         const Users & m_users;
         const Tariffs & m_tariffs;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 }
index 6eb67e0f90bcf18cc7a1de6cd97a3618fe5d2f78..27dbb4c8ef325ada846e98bf8901248451cbe2d0 100644 (file)
@@ -42,8 +42,8 @@ class GET_SERVICES: public BASE_PARSER
         class FACTORY : public BASE_PARSER::FACTORY
         {
             public:
-                FACTORY(const Services & services) : m_services(services) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_SERVICES(admin, m_services); }
+                explicit FACTORY(const Services & services) : m_services(services) {}
+                BASE_PARSER * create(const Admin & admin) override { return new GET_SERVICES(admin, m_services); }
                 static void Register(REGISTRY & registry, const Services & services)
                 { registry[ToLower(tag)] = new FACTORY(services); }
             private:
@@ -58,7 +58,7 @@ class GET_SERVICES: public BASE_PARSER
     private:
         const Services & m_services;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class GET_SERVICE: public BASE_PARSER
@@ -67,8 +67,8 @@ class GET_SERVICE: public BASE_PARSER
         class FACTORY : public BASE_PARSER::FACTORY
         {
             public:
-                FACTORY(const Services & services) : m_services(services) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_SERVICE(admin, m_services); }
+                explicit FACTORY(const Services & services) : m_services(services) {}
+                BASE_PARSER * create(const Admin & admin) override { return new GET_SERVICE(admin, m_services); }
                 static void Register(REGISTRY & registry, Services & services)
                 { registry[ToLower(tag)] = new FACTORY(services); }
             private:
@@ -79,13 +79,13 @@ class GET_SERVICE: public BASE_PARSER
 
         GET_SERVICE(const Admin & admin, const Services & services)
             : BASE_PARSER(admin, tag), m_services(services) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string m_name;
         const Services & m_services;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class ADD_SERVICE: public BASE_PARSER
@@ -94,8 +94,8 @@ class ADD_SERVICE: public BASE_PARSER
         class FACTORY : public BASE_PARSER::FACTORY
         {
             public:
-                FACTORY(Services & services) : m_services(services) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new ADD_SERVICE(admin, m_services); }
+                explicit FACTORY(Services & services) : m_services(services) {}
+                BASE_PARSER * create(const Admin & admin) override { return new ADD_SERVICE(admin, m_services); }
                 static void Register(REGISTRY & registry, Services & services)
                 { registry[ToLower(tag)] = new FACTORY(services); }
             private:
@@ -106,13 +106,13 @@ class ADD_SERVICE: public BASE_PARSER
 
         ADD_SERVICE(const Admin & admin, Services & services)
             : BASE_PARSER(admin, tag), m_services(services) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string m_name;
         Services & m_services;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class DEL_SERVICE: public BASE_PARSER
@@ -121,8 +121,8 @@ class DEL_SERVICE: public BASE_PARSER
         class FACTORY : public BASE_PARSER::FACTORY
         {
             public:
-                FACTORY(Services & services) : m_services(services) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new DEL_SERVICE(admin, m_services); }
+                explicit FACTORY(Services & services) : m_services(services) {}
+                BASE_PARSER * create(const Admin & admin) override { return new DEL_SERVICE(admin, m_services); }
                 static void Register(REGISTRY & registry, Services & services)
                 { registry[ToLower(tag)] = new FACTORY(services); }
             private:
@@ -133,13 +133,13 @@ class DEL_SERVICE: public BASE_PARSER
 
         DEL_SERVICE(const Admin & admin, Services & services)
             : BASE_PARSER(admin, tag), m_services(services) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string m_name;
         Services & m_services;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class CHG_SERVICE: public BASE_PARSER
@@ -148,8 +148,8 @@ class CHG_SERVICE: public BASE_PARSER
         class FACTORY : public BASE_PARSER::FACTORY
         {
             public:
-                FACTORY(Services & services) : m_services(services) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new CHG_SERVICE(admin, m_services); }
+                explicit FACTORY(Services & services) : m_services(services) {}
+                BASE_PARSER * create(const Admin & admin) override { return new CHG_SERVICE(admin, m_services); }
                 static void Register(REGISTRY & registry, Services & services)
                 { registry[ToLower(tag)] = new FACTORY(services); }
             private:
@@ -160,13 +160,13 @@ class CHG_SERVICE: public BASE_PARSER
 
         CHG_SERVICE(const Admin & admin, Services & services)
             : BASE_PARSER(admin, tag), m_services(services) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         ServiceConfOpt m_service;
         Services & m_services;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 } // namespace PARSER
index 8f8e8db5ab2db571bb84595ee839c072873bd9cf..3ed22113e12d6d0f89f1733087acbefddd536139 100644 (file)
@@ -305,7 +305,7 @@ int CHG_TARIFF::Start(void *, const char * el, const char ** attr)
         {
             int64_t policyTime = 0;
             if (str2x(attr[1], policyTime) == 0)
-                td.tariffConf.changePolicyTimeout = (time_t)policyTime;
+                td.tariffConf.changePolicyTimeout = policyTime;
             return 0;
         }
     }
index 9f9c50316e87c635a112e3e168274038ee41e2e3..ad9987c1be6a1195b04028dad2b89b3d2e727100 100644 (file)
@@ -45,7 +45,7 @@ class GET_TARIFFS: public BASE_PARSER
         {
             public:
                 explicit FACTORY(const Tariffs & tariffs) : m_tariffs(tariffs) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_TARIFFS(admin, m_tariffs); }
+                BASE_PARSER * create(const Admin & admin) override { return new GET_TARIFFS(admin, m_tariffs); }
                 static void Register(REGISTRY & registry, const Tariffs & tariffs)
                 { registry[ToLower(tag)] = new FACTORY(tariffs); }
             private:
@@ -60,7 +60,7 @@ class GET_TARIFFS: public BASE_PARSER
     private:
         const Tariffs & m_tariffs;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class ADD_TARIFF: public BASE_PARSER
@@ -70,7 +70,7 @@ class ADD_TARIFF: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Tariffs & tariffs) : m_tariffs(tariffs) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new ADD_TARIFF(admin, m_tariffs); }
+                BASE_PARSER * create(const Admin & admin) override { return new ADD_TARIFF(admin, m_tariffs); }
                 static void Register(REGISTRY & registry, Tariffs & tariffs)
                 { registry[ToLower(tag)] = new FACTORY(tariffs); }
             private:
@@ -81,13 +81,13 @@ class ADD_TARIFF: public BASE_PARSER
 
         ADD_TARIFF(const Admin & admin, Tariffs & tariffs)
             : BASE_PARSER(admin, tag), m_tariffs(tariffs) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string tariff;
         Tariffs & m_tariffs;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class DEL_TARIFF: public BASE_PARSER
@@ -97,7 +97,7 @@ class DEL_TARIFF: public BASE_PARSER
         {
             public:
                 FACTORY(Tariffs & tariffs, const Users & users) : m_tariffs(tariffs), m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new DEL_TARIFF(admin, m_users, m_tariffs); }
+                BASE_PARSER * create(const Admin & admin) override { return new DEL_TARIFF(admin, m_users, m_tariffs); }
                 static void Register(REGISTRY & registry, Tariffs & tariffs, const Users & users)
                 { registry[ToLower(tag)] = new FACTORY(tariffs, users); }
             private:
@@ -109,14 +109,14 @@ class DEL_TARIFF: public BASE_PARSER
 
         DEL_TARIFF(const Admin & admin, const Users & users, Tariffs & tariffs)
             : BASE_PARSER(admin, tag), m_users(users), m_tariffs(tariffs) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         std::string tariff;
         const Users & m_users;
         Tariffs & m_tariffs;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class CHG_TARIFF: public BASE_PARSER
@@ -126,7 +126,7 @@ class CHG_TARIFF: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Tariffs & tariffs) : m_tariffs(tariffs) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new CHG_TARIFF(admin, m_tariffs); }
+                BASE_PARSER * create(const Admin & admin) override { return new CHG_TARIFF(admin, m_tariffs); }
                 static void Register(REGISTRY & registry, Tariffs & tariffs)
                 { registry[ToLower(tag)] = new FACTORY(tariffs); }
             private:
@@ -137,14 +137,14 @@ class CHG_TARIFF: public BASE_PARSER
 
         CHG_TARIFF(const Admin & admin, Tariffs & tariffs)
             : BASE_PARSER(admin, tag), m_tariffs(tariffs) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         TariffDataOpt td;
         Tariffs & m_tariffs;
 
         int CheckTariffData();
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 } // namespace PARSER
index 50f31017b669b97ab47494b731b70db7be0c5961..04fe16c67771f711b291603922b441b30bbe0d33 100644 (file)
@@ -40,8 +40,8 @@ class USER_INFO : public BASE_PARSER
         class FACTORY : public BASE_PARSER::FACTORY
         {
             public:
-                FACTORY(const Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new USER_INFO(admin, m_users); }
+                explicit FACTORY(const Users & users) : m_users(users) {}
+                BASE_PARSER * create(const Admin & admin) override { return new USER_INFO(admin, m_users); }
                 static void Register(REGISTRY & registry, const Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -52,13 +52,13 @@ class USER_INFO : public BASE_PARSER
 
         USER_INFO(const Admin & admin, const Users & users)
             : BASE_PARSER(admin, tag), m_users(users) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         const Users & m_users;
         std::string m_login;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 } // namespace PARSER
index e371e45a61964d198d55d75d73a38172cd6a3b03..809afec62ce709878fe000acc77b980e597c795d 100644 (file)
@@ -327,7 +327,7 @@ int CHG_USER::Start(void *, const char * el, const char ** attr)
         {
             long int creditExpire = 0;
             if (str2x(attr[1], creditExpire) == 0)
-                m_ucr.creditExpire = (time_t)creditExpire;
+                m_ucr.creditExpire = creditExpire;
 
             return 0;
         }
@@ -558,7 +558,7 @@ int CHG_USER::ApplyChanges()
     userdata.push_back(u->GetProperties().userdata8.GetPointer());
     userdata.push_back(u->GetProperties().userdata9.GetPointer());
 
-    for (int i = 0; i < (int)userdata.size(); i++)
+    for (size_t i = 0; i < userdata.size(); i++)
         if (!m_ucr.userdata[i].empty())
             if(!userdata[i]->Set(m_ucr.userdata[i].const_data(), m_currAdmin, m_login, m_store))
                 return -1;
index cdef451ed90f8ed7608322eb37e2ac2a4f0c0266..b9d5fce464392d42a21e4fb60b37111d1b4298c0 100644 (file)
@@ -49,7 +49,7 @@ class GET_USERS: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_USERS(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new GET_USERS(admin, m_users); }
                 static void Register(REGISTRY & registry, Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -61,13 +61,13 @@ class GET_USERS: public BASE_PARSER
         GET_USERS(const Admin & admin, Users & users)
             : BASE_PARSER(admin, tag), m_users(users),
               m_lastUserUpdateTime(0) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         Users & m_users;
         time_t m_lastUserUpdateTime;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class GET_USER: public BASE_PARSER
@@ -77,7 +77,7 @@ class GET_USER: public BASE_PARSER
         {
             public:
                 explicit FACTORY(const Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new GET_USER(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new GET_USER(admin, m_users); }
                 static void Register(REGISTRY & registry, const Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -88,13 +88,13 @@ class GET_USER: public BASE_PARSER
 
         GET_USER(const Admin & admin, const Users & users)
             : BASE_PARSER(admin, tag), m_users(users) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         const Users & m_users;
         std::string m_login;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class ADD_USER: public BASE_PARSER
@@ -104,7 +104,7 @@ class ADD_USER: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new ADD_USER(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new ADD_USER(admin, m_users); }
                 static void Register(REGISTRY & registry, Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -115,13 +115,13 @@ class ADD_USER: public BASE_PARSER
 
         ADD_USER(const Admin & admin, Users & users)
             : BASE_PARSER(admin, tag), m_users(users) {}
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         Users & m_users;
         std::string m_login;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class CHG_USER: public BASE_PARSER
@@ -133,7 +133,7 @@ class CHG_USER: public BASE_PARSER
                 FACTORY(Users & users, Store & store, const Tariffs & tariffs)
                     : m_users(users), m_store(store), m_tariffs(tariffs)
                 {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new CHG_USER(admin, m_users, m_store, m_tariffs); }
+                BASE_PARSER * create(const Admin & admin) override { return new CHG_USER(admin, m_users, m_store, m_tariffs); }
                 static void Register(REGISTRY & registry, Users & users, Store & store, const Tariffs & tariffs)
                 { registry[ToLower(tag)] = new FACTORY(users, store, tariffs); }
             private:
@@ -152,7 +152,7 @@ class CHG_USER: public BASE_PARSER
               m_tariffs(tariffs),
               m_cashMustBeAdded(false) {}
 
-        int Start(void * data, const char * el, const char ** attr);
+        int Start(void * data, const char * el, const char ** attr) override;
 
     private:
         Users & m_users;
@@ -167,7 +167,7 @@ class CHG_USER: public BASE_PARSER
         bool m_cashMustBeAdded;
 
         int ApplyChanges();
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class DEL_USER: public BASE_PARSER
@@ -177,7 +177,7 @@ class DEL_USER: public BASE_PARSER
         {
             public:
                 explicit FACTORY(Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new DEL_USER(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new DEL_USER(admin, m_users); }
                 static void Register(REGISTRY & registry, Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -188,15 +188,15 @@ class DEL_USER: public BASE_PARSER
 
         DEL_USER(const Admin & admin, Users & users)
             : BASE_PARSER(admin, tag), m_users(users), res(0), u(NULL) {}
-        int Start(void * data, const char * el, const char ** attr);
-        int End(void * data, const char * el);
+        int Start(void * data, const char * el, const char ** attr) override;
+        int End(void * data, const char * el) override;
 
     private:
         Users & m_users;
         int res;
         User * u;
 
-        void CreateAnswer();
+        void CreateAnswer() override;
 };
 
 class CHECK_USER: public BASE_PARSER
@@ -206,7 +206,7 @@ class CHECK_USER: public BASE_PARSER
         {
             public:
                 explicit FACTORY(const Users & users) : m_users(users) {}
-                virtual BASE_PARSER * create(const Admin & admin) { return new CHECK_USER(admin, m_users); }
+                BASE_PARSER * create(const Admin & admin) override { return new CHECK_USER(admin, m_users); }
                 static void Register(REGISTRY & registry, const Users & users)
                 { registry[ToLower(tag)] = new FACTORY(users); }
             private:
@@ -217,14 +217,14 @@ class CHECK_USER: public BASE_PARSER
 
         CHECK_USER(const Admin & admin, const Users & users)
             : BASE_PARSER(admin, tag), m_users(users) {}
-        int Start(void * data, const char * el, const char ** attr);
-        int End(void * data, const char * el);
+        int Start(void * data, const char * el, const char ** attr) override;
+        int End(void * data, const char * el) override;
 
     private:
         const Users & m_users;
 
         void CreateAnswer(const char * error);
-        void CreateAnswer() {} // dummy
+        void CreateAnswer() override {} // dummy
 };
 
 } // namespace PARSER
index 3f47f24b87bb0f5e7ef30ae35e473e9c43cd472f..a63478bd714435ba3aa185cebc88baf61b674e0e 100644 (file)
@@ -102,13 +102,7 @@ int STG_CONFIG::Start()
         return -1;
     }
 
-    if (pthread_create(&thread, NULL, Run, this))
-    {
-        errorStr = std::string("Cannot create thread: '") + strerror(errno) + "'.";
-        printfd(__FILE__, "%s\n", errorStr.c_str());
-        logger(errorStr);
-        return -1;
-    }
+    m_thread = std::jthread([this](auto token){ Run(token); });
 
     return 0;
 }
@@ -119,6 +113,7 @@ int STG_CONFIG::Stop()
         return 0;
 
     config.Stop();
+    m_thread.request_stop();
 
     //5 seconds to thread stops itself
     for (size_t i = 0; i < 25; ++i)
@@ -131,23 +126,20 @@ int STG_CONFIG::Stop()
     }
 
     if (isRunning)
-        return -1;
+        m_thread.detach();
 
     return 0;
 }
 //-----------------------------------------------------------------------------
-void * STG_CONFIG::Run(void * d)
+void STG_CONFIG::Run(std::stop_token token)
 {
     sigset_t signalSet;
     sigfillset(&signalSet);
     pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
-    STG_CONFIG & stgConf = *static_cast<STG_CONFIG *>(d);
-    stgConf.isRunning = true;
-
-    stgConf.config.Run();
+    isRunning = true;
 
-    stgConf.isRunning = false;
+    config.Run(token);
 
-    return NULL;
+    isRunning = false;
 }
index b7684e3390909e79cfcf6d0d8be99aaedb384cbe..f4f94ee8391aa354973a83c5c703f2639279d610 100644 (file)
 #include "stg/logger.h"
 
 #include <string>
-
-#include <pthread.h>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 
 class STG_CONFIG_SETTINGS
 {
@@ -72,11 +74,11 @@ class STG_CONFIG : public STG::Plugin
         STG_CONFIG(const STG_CONFIG & rvalue);
         STG_CONFIG & operator=(const STG_CONFIG & rvalue);
 
-        static void *       Run(void *);
+        void                Run(std::stop_token token);
 
         mutable std::string errorStr;
         STG_CONFIG_SETTINGS stgConfigSettings;
-        pthread_t           thread;
+        std::jthread        m_thread;
         bool                nonstop;
         bool                isRunning;
         STG::PluginLogger   logger;
index 147ef68ce341da4a140ab01582180aad978c0789..a8dda2a680ee510474c9e7169d86a9659119feb5 100644 (file)
@@ -62,18 +62,15 @@ return 0;
 //-----------------------------------------------------------------------------
 PING::PING()
     : users(NULL),
-      nonstop(false),
       isRunning(false),
       onAddUserNotifier(*this),
       onDelUserNotifier(*this),
       logger(STG::PluginLogger::get("ping"))
 {
-pthread_mutex_init(&mutex, NULL);
 }
 //-----------------------------------------------------------------------------
 PING::~PING()
 {
-pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
 int PING::ParseSettings()
@@ -91,31 +88,23 @@ GetUsers();
 users->AddNotifierUserAdd(&onAddUserNotifier);
 users->AddNotifierUserDel(&onDelUserNotifier);
 
-nonstop = true;
-
 pinger.SetDelayTime(pingSettings.GetPingDelay());
 pinger.Start();
 
-if (pthread_create(&thread, NULL, Run, this))
-    {
-    errorStr = "Cannot start thread.";
-    logger("Cannot create thread.");
-    printfd(__FILE__, "Cannot start thread\n");
-    return -1;
-    }
+m_thread = std::jthread([this](auto token){ Run(token); });
 
 return 0;
 }
 //-----------------------------------------------------------------------------
 int PING::Stop()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 
-if (!isRunning)
+if (!m_thread.joinable())
     return 0;
 
 pinger.Stop();
-nonstop = false;
+m_thread.request_stop();
 //5 seconds to thread stops itself
 struct timespec ts = {0, 200000000};
 for (int i = 0; i < 25; i++)
@@ -138,7 +127,7 @@ while (users_iter != usersList.end())
     }
 
 if (isRunning)
-    return -1;
+    m_thread.detach();
 
 return 0;
 }
@@ -148,29 +137,28 @@ bool PING::IsRunning()
 return isRunning;
 }
 //-----------------------------------------------------------------------------
-void * PING::Run(void * d)
+void PING::Run(std::stop_token token)
 {
 sigset_t signalSet;
 sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
-PING * ping = static_cast<PING *>(d);
-ping->isRunning = true;
+isRunning = true;
 
-long delay = (10000000 * ping->pingSettings.GetPingDelay()) / 3 + 50000000;
+long delay = (10000000 * pingSettings.GetPingDelay()) / 3 + 50000000;
 
-while (ping->nonstop)
+while (!token.stop_requested())
     {
-    std::list<UserPtr>::iterator iter = ping->usersList.begin();
+    std::list<UserPtr>::iterator iter = usersList.begin();
         {
-        STG_LOCKER lock(&ping->mutex);
-        while (iter != ping->usersList.end())
+        std::lock_guard lock(m_mutex);
+        while (iter != usersList.end())
             {
             if ((*iter)->GetProperties().ips.ConstData().onlyOneIP())
                 {
                 uint32_t ip = (*iter)->GetProperties().ips.ConstData()[0].ip;
                 time_t t;
-                if (ping->pinger.GetIPTime(ip, &t) == 0)
+                if (pinger.GetIPTime(ip, &t) == 0)
                     {
                     if (t)
                         (*iter)->UpdatePingTime(t);
@@ -182,7 +170,7 @@ while (ping->nonstop)
                 if (ip)
                     {
                     time_t t;
-                    if (ping->pinger.GetIPTime(ip, &t) == 0)
+                    if (pinger.GetIPTime(ip, &t) == 0)
                         {
                         if (t)
                             (*iter)->UpdatePingTime(t);
@@ -195,15 +183,14 @@ while (ping->nonstop)
     struct timespec ts = {delay / 1000000000, delay % 1000000000};
     for (int i = 0; i < 100; i++)
         {
-        if (ping->nonstop)
+        if (!token.stop_requested())
             {
             nanosleep(&ts, NULL);
             }
         }
     }
 
-ping->isRunning = false;
-return NULL;
+isRunning = false;
 }
 //-----------------------------------------------------------------------------
 void PING::SetUserNotifiers(UserPtr u)
@@ -253,7 +240,7 @@ if (IPIter != ChgIPNotifierList.end())
 //-----------------------------------------------------------------------------
 void PING::GetUsers()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 
 UserPtr u;
 int h = users->OpenSearch();
@@ -280,7 +267,7 @@ users->CloseSearch(h);
 //-----------------------------------------------------------------------------
 void PING::AddUser(UserPtr u)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 
 SetUserNotifiers(u);
 usersList.push_back(u);
@@ -288,7 +275,7 @@ usersList.push_back(u);
 //-----------------------------------------------------------------------------
 void PING::DelUser(UserPtr u)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 
 UnSetUserNotifiers(u);
 
index 9986be39ff75f493a70d166c3639ce9986c93af0..23874e37623da45d03fd35fb30a0919d1889af80 100644 (file)
 
 #include <string>
 #include <list>
+#include <mutex>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 #include <cstdint>
 
-#include <pthread.h>
-
 class PING;
 
 namespace STG
@@ -118,7 +121,7 @@ private:
     void GetUsers();
     void SetUserNotifiers(UserPtr u);
     void UnSetUserNotifiers(UserPtr u);
-    static void * Run(void * d);
+    void Run(std::stop_token token);
 
     mutable std::string errorStr;
     PING_SETTINGS pingSettings;
@@ -126,9 +129,8 @@ private:
     STG::Users * users;
     std::list<UserPtr> usersList;
 
-    pthread_t thread;
-    pthread_mutex_t mutex;
-    bool nonstop;
+    std::jthread m_thread;
+    std::mutex m_mutex;
     bool isRunning;
     mutable STG_PINGER pinger;
 
index 764e536eea9b5876bb8235721bcc1994ade5c7e1..8b0e2054a984154961eeb1e31dffbd54ff6fe96e 100644 (file)
@@ -22,7 +22,6 @@
 #include "rscript.h"
 
 #include "ur_functor.h"
-#include "send_functor.h"
 
 #include "stg/common.h"
 #include "stg/locker.h"
@@ -163,7 +162,6 @@ return 0;
 REMOTE_SCRIPT::REMOTE_SCRIPT()
     : sendPeriod(15),
       halfPeriod(8),
-      nonstop(false),
       isRunning(false),
       users(NULL),
       sock(0),
@@ -171,32 +169,27 @@ REMOTE_SCRIPT::REMOTE_SCRIPT()
       onDelUserNotifier(*this),
       logger(STG::PluginLogger::get("rscript"))
 {
-pthread_mutex_init(&mutex, NULL);
 }
 //-----------------------------------------------------------------------------
 REMOTE_SCRIPT::~REMOTE_SCRIPT()
 {
-pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
-void * REMOTE_SCRIPT::Run(void * d)
+void REMOTE_SCRIPT::Run(std::stop_token token)
 {
 sigset_t signalSet;
 sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
-REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
+isRunning = true;
 
-rs->isRunning = true;
-
-while (rs->nonstop)
+while (!token.stop_requested())
     {
-    rs->PeriodicSend();
+    PeriodicSend();
     sleep(2);
     }
 
-rs->isRunning = false;
-return NULL;
+isRunning = false;
 }
 //-----------------------------------------------------------------------------
 int REMOTE_SCRIPT::ParseSettings()
@@ -215,13 +208,11 @@ int REMOTE_SCRIPT::Start()
 {
 netRouters = rsSettings.GetSubnetsMap();
 
-InitEncrypt(&ctx, rsSettings.GetPassword());
+InitEncrypt(rsSettings.GetPassword());
 
 users->AddNotifierUserAdd(&onAddUserNotifier);
 users->AddNotifierUserDel(&onDelUserNotifier);
 
-nonstop = true;
-
 if (GetUsers())
     {
     return -1;
@@ -234,13 +225,7 @@ if (PrepareNet())
 
 if (!isRunning)
     {
-    if (pthread_create(&thread, NULL, Run, this))
-        {
-        errorStr = "Cannot create thread.";
-        logger("Cannot create thread.");
-        printfd(__FILE__, "Cannot create thread\n");
-        return -1;
-        }
+    m_thread = std::jthread([this](auto token){ Run(token); });
     }
 
 errorStr = "";
@@ -252,7 +237,7 @@ int REMOTE_SCRIPT::Stop()
 if (!IsRunning())
     return 0;
 
-nonstop = false;
+m_thread.request_stop();
 
 std::for_each(
         authorizedUsers.begin(),
@@ -278,7 +263,7 @@ users->DelNotifierUserAdd(&onAddUserNotifier);
 if (isRunning)
     {
     logger("Cannot stop thread.");
-    return -1;
+    m_thread.detach();
     }
 
 return 0;
@@ -296,7 +281,7 @@ if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
     }
 
     {
-    STG_LOCKER lock(&mutex);
+    std::lock_guard lock(m_mutex);
 
     printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
 
@@ -336,7 +321,7 @@ return false;
 //-----------------------------------------------------------------------------
 void REMOTE_SCRIPT::PeriodicSend()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 
 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
 while (it != authorizedUsers.end())
@@ -358,7 +343,7 @@ bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bo
 RS::PACKET_HEADER packetHead;
 
 memset(packetHead.padding, 0, sizeof(packetHead.padding));
-strcpy((char*)packetHead.magic, RS_ID);
+memcpy(packetHead.magic, RS_ID, sizeof(RS_ID));
 packetHead.protoVer[0] = '0';
 packetHead.protoVer[1] = '2';
 if (forceDisconnect)
@@ -392,7 +377,7 @@ rsu.lastSentTime = stgTime;
 
 packetHead.ip = htonl(rsu.ip);
 packetHead.id = htonl(rsu.user->GetID());
-strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
+strncpy(reinterpret_cast<char*>(packetHead.login), rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
 packetHead.login[RS_LOGIN_LEN - 1] = 0;
 
 memcpy(buf, &packetHead, sizeof(packetHead));
@@ -405,7 +390,7 @@ if (packetHead.packetType == RS_ALIVE_PACKET)
 RS::PACKET_TAIL packetTail;
 
 memset(packetTail.padding, 0, sizeof(packetTail.padding));
-strcpy((char*)packetTail.magic, RS_ID);
+memcpy(packetTail.magic, RS_ID, sizeof(RS_ID));
 std::vector<std::string>::const_iterator it;
 std::string params;
 for(it = rsSettings.GetUserParams().begin();
@@ -420,12 +405,12 @@ for(it = rsSettings.GetUserParams().begin();
     }
     params += parameter + " ";
     }
-strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
+strncpy(reinterpret_cast<char*>(packetTail.params), params.c_str(), RS_PARAMS_LEN);
 packetTail.params[RS_PARAMS_LEN - 1] = 0;
 
 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
 
-Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
+Encrypt(buf + sizeof(packetHead), reinterpret_cast<char *>(&packetTail), sizeof(packetTail) / 8);
 
 return false;
 }
@@ -442,11 +427,16 @@ if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
     return true;
     }
 
-std::for_each(
-        rsu.routers.begin(),
-        rsu.routers.end(),
-        PacketSender(sock, buffer, sizeof(buffer), static_cast<uint16_t>(htons(rsSettings.GetPort())))
-        );
+for (const auto& ip : rsu.routers)
+{
+    struct sockaddr_in sendAddr;
+
+    sendAddr.sin_family = AF_INET;
+    sendAddr.sin_port = htons(rsSettings.GetPort());
+    sendAddr.sin_addr.s_addr = ip;
+
+    return sendto(sock, buffer, sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&sendAddr), sizeof(sendAddr));
+}
 
 return false;
 }
@@ -464,10 +454,10 @@ if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
 struct sockaddr_in sendAddr;
 
 sendAddr.sin_family = AF_INET;
-sendAddr.sin_port = static_cast<uint16_t>(htons(rsSettings.GetPort()));
+sendAddr.sin_port = htons(rsSettings.GetPort());
 sendAddr.sin_addr.s_addr = routerIP;
 
-ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
+ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, reinterpret_cast<struct sockaddr *>(&sendAddr), sizeof(sendAddr));
 
 if (res < 0)
     logger("sendto error: %s", strerror(errno));
@@ -493,7 +483,7 @@ return false;
 //-----------------------------------------------------------------------------
 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 for (size_t i = 0; i < netRouters.size(); ++i)
     {
     if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
@@ -528,13 +518,13 @@ void REMOTE_SCRIPT::AddRSU(UserPtr user)
 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
 Send(rsu);
 
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
 }
 //-----------------------------------------------------------------------------
 void REMOTE_SCRIPT::DelRSU(UserPtr user)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard lock(m_mutex);
 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
 while (it != authorizedUsers.end())
     {
@@ -572,19 +562,19 @@ else
     rs.DelRSU(user);
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const
+void REMOTE_SCRIPT::InitEncrypt(const std::string & password) const
 {
 unsigned char keyL[PASSWD_LEN];  // Пароль для шифровки
 memset(keyL, 0, PASSWD_LEN);
-strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
-Blowfish_Init(ctx, keyL, PASSWD_LEN);
+strncpy(reinterpret_cast<char*>(keyL), password.c_str(), PASSWD_LEN);
+Blowfish_Init(&ctx, keyL, PASSWD_LEN);
 }
 //-----------------------------------------------------------------------------
-void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const
+void REMOTE_SCRIPT::Encrypt(void * dst, const void * src, size_t len8) const
 {
 if (dst != src)
     memcpy(dst, src, len8 * 8);
 for (size_t i = 0; i < len8; ++i)
-    Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
+    Blowfish_Encrypt(&ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
 }
 //-----------------------------------------------------------------------------
index e734227c48e67d50b72fd985abe1eed248ef0e3f..80fc86517e073efc09b149b9eb4ca023574433db 100644 (file)
 #include <map>
 #include <functional>
 #include <utility>
+#include <mutex>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 #include <cstdint>
 
-#include <pthread.h>
-
 namespace STG
 {
 struct Settings;
@@ -200,7 +203,7 @@ private:
     REMOTE_SCRIPT(const REMOTE_SCRIPT & rhs);
     REMOTE_SCRIPT & operator=(const REMOTE_SCRIPT & rhs);
 
-    static void *       Run(void *);
+    void                Run(std::stop_token token);
     bool                PrepareNet();
     bool                FinalizeNet();
 
@@ -215,8 +218,8 @@ private:
     void                SetUserNotifiers(UserPtr u);
     void                UnSetUserNotifiers(UserPtr u);
 
-    void                InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const;
-    void                Encrypt(BLOWFISH_CTX * ctx, 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;
 
@@ -230,15 +233,14 @@ private:
     int                 sendPeriod;
     int                 halfPeriod;
 
-    bool                nonstop;
     bool                isRunning;
 
     STG::Users *             users;
 
     std::vector<NET_ROUTER> netRouters;
 
-    pthread_t           thread;
-    pthread_mutex_t     mutex;
+    std::jthread        m_thread;
+    std::mutex          m_mutex;
 
     int                 sock;
 
diff --git a/projects/stargazer/plugins/other/rscript/send_functor.h b/projects/stargazer/plugins/other/rscript/send_functor.h
deleted file mode 100644 (file)
index fbe6d3b..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- *    This program is free software; you can redistribute it and/or modify
- *    it under the terms of the GNU General Public License as published by
- *    the Free Software Foundation; either version 2 of the License, or
- *    (at your option) any later version.
- *
- *    This program is distributed in the hope that it will be useful,
- *    but WITHOUT ANY WARRANTY; without even the implied warranty of
- *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *    GNU General Public License for more details.
- *
- *    You should have received a copy of the GNU General Public License
- *    along with this program; if not, write to the Free Software
- *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- */
-
-/*
- *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
- */
-
-/*
- $Revision: 1.2 $
- $Date: 2010/03/04 12:11:09 $
- $Author: faust $
-*/
-
-#ifndef __SEND_FUNCTOR_H__
-#define __SEND_FUNCTOR_H__
-
-#include <functional>
-#include <cstdint>
-
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/ip.h>
-
-class PacketSender : public std::unary_function<uint32_t, ssize_t> {
-    public:
-        PacketSender(int s, char * b, size_t l, uint16_t p)
-            : sock(s),
-              buffer(b),
-              length(l),
-              port(p) {}
-        ssize_t operator() (uint32_t ip)
-        {
-        struct sockaddr_in sendAddr;
-
-        sendAddr.sin_family = AF_INET;
-        sendAddr.sin_port = port;
-        sendAddr.sin_addr.s_addr = ip;
-
-        return sendto(sock, buffer, length, 0, (struct sockaddr*)&sendAddr, sizeof(sendAddr));
-        }
-    private:
-        int sock;
-        char * buffer;
-        size_t length;
-        uint16_t port;
-};
-
-#endif
index c74aeae982727bed08dba8f79d15bcb0067d5194..77df934800f77bc93a8b53cff6ca280bcb9f938a 100644 (file)
@@ -98,7 +98,6 @@ SMUX::SMUX()
       services(NULL),
       corporations(NULL),
       traffcounter(NULL),
-      running(false),
       stopped(true),
       needReconnect(false),
       lastReconnectTry(0),
@@ -109,8 +108,6 @@ SMUX::SMUX()
       addDelTariffNotifier(*this),
       logger(STG::PluginLogger::get("smux"))
 {
-pthread_mutex_init(&mutex, NULL);
-
 smuxHandlers[SMUX_PDUs_PR_close] = &SMUX::CloseHandler;
 smuxHandlers[SMUX_PDUs_PR_registerResponse] = &SMUX::RegisterResponseHandler;
 smuxHandlers[SMUX_PDUs_PR_pdus] = &SMUX::PDUsRequestHandler;
@@ -134,7 +131,6 @@ SMUX::~SMUX()
         delete it->second;
     }
 printfd(__FILE__, "SMUX::~SMUX()\n");
-pthread_mutex_destroy(&mutex);
 }
 
 int SMUX::ParseSettings()
@@ -195,16 +191,8 @@ while (it != sensors.end())
     }
 #endif
 
-if (!running)
-    {
-    if (pthread_create(&thread, NULL, Runner, this))
-        {
-        errorStr = "Cannot create thread.";
-       logger("Cannot create thread.");
-        printfd(__FILE__, "Cannot create thread\n");
-        return -1;
-        }
-    }
+if (!m_thread.joinable())
+    m_thread = std::jthread([this](auto token){ Run(token); });
 
 return 0;
 }
@@ -212,7 +200,7 @@ return 0;
 int SMUX::Stop()
 {
 printfd(__FILE__, "SMUX::Stop() - Before\n");
-running = false;
+m_thread.request_stop();
 
 if (!stopped)
     {
@@ -224,8 +212,8 @@ if (!stopped)
         }
     }
 
-if (stopped)
-    pthread_join(thread, NULL);
+if (!stopped)
+    m_thread.detach();
 
 ResetNotifiers();
 
@@ -247,7 +235,6 @@ close(sock);
 
 if (!stopped)
     {
-    running = true;
     return -1;
     }
 
@@ -269,30 +256,16 @@ if (!needReconnect)
 return 0;
 }
 
-void * SMUX::Runner(void * d)
-{
-sigset_t signalSet;
-sigfillset(&signalSet);
-pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
-
-SMUX * smux = static_cast<SMUX *>(d);
-
-smux->Run();
-
-return NULL;
-}
-
-void SMUX::Run()
+void SMUX::Run(std::stop_token token)
 {
 stopped = true;
 if (!SendOpenPDU(sock))
     needReconnect = true;
 if (!SendRReqPDU(sock))
     needReconnect = true;
-running = true;
 stopped = false;
 
-while(running)
+while (!token.stop_requested())
     {
     if (WaitPackets(sock) && !needReconnect)
         {
@@ -302,12 +275,12 @@ while(running)
             DispatchPDUs(pdus);
             ASN_STRUCT_FREE(asn_DEF_SMUX_PDUs, pdus);
             }
-        else if (running)
+        else if (!token.stop_requested())
             Reconnect();
         }
-    else if (running && needReconnect)
+    else if (!token.stop_requested() && needReconnect)
         Reconnect();
-    if (!running)
+    if (token.stop_requested())
         break;
     }
 SendClosePDU(sock);
@@ -423,11 +396,11 @@ while (it != tables.end())
     }
 if (!done)
     {
-    Sensors::iterator it(newSensors.begin());
-    while (it != newSensors.end())
+    Sensors::iterator sit(newSensors.begin());
+    while (sit != newSensors.end())
         {
-        delete it->second;
-        ++it;
+        delete sit->second;
+        ++sit;
         }
     return false;
     }
index 4954bd093663eeb11f9fe70bafeedeebc6740af8..808679042046ef3526007f55eb614194ca868d0d 100644 (file)
@@ -1,11 +1,14 @@
 #ifndef __SMUX_H__
 #define __SMUX_H__
 
-#include <pthread.h>
-
 #include <string>
 #include <map>
 #include <list>
+#include <mutex>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 #include <cstdint>
 
 #include "stg/SMUX-PDUs.h"
@@ -123,7 +126,7 @@ public:
     int Start();
     int Stop();
     int Reload(const STG::ModuleSettings & ms);
-    bool IsRunning() { return running && !stopped; }
+    bool IsRunning() { return m_thread.joinable() && !stopped; }
 
     const std::string & GetStrError() const { return errorStr; }
     std::string GetVersion() const { return "Stg SMUX Plugin 1.1"; }
@@ -139,8 +142,7 @@ private:
     SMUX(const SMUX & rvalue);
     SMUX & operator=(const SMUX & rvalue);
 
-    static void * Runner(void * d);
-    void Run();
+    void Run(std::stop_token token);
     bool PrepareNet();
     bool Reconnect();
 
@@ -169,9 +171,8 @@ private:
     SMUX_SETTINGS smuxSettings;
     STG::ModuleSettings settings;
 
-    pthread_t thread;
-    pthread_mutex_t mutex;
-    bool running;
+    std::jthread m_thread;
+    std::mutex m_mutex;
     bool stopped;
     bool needReconnect;
 
index edfe4377326a9d47d7e765021b3cf8a0a2eb0a2e..1e27b326c30d17fa78c54bf1f2b43b20e05806d7 100644 (file)
@@ -33,9 +33,8 @@ class TariffUsersTable : public TableSensor {
               tariffs(t),
               users(u)
         {}
-        virtual ~TariffUsersTable() {}
 
-        void UpdateSensors(Sensors & sensors) const;
+        void UpdateSensors(Sensors & sensors) const override;
 
     private:
         STG::Tariffs & tariffs;
index 4e54749287110f740fa264db4590a63fd23028b9..af9d355b477a84d004cd8cdd7daa2f38c76e414f 100644 (file)
@@ -22,14 +22,14 @@ if (*left == '.')
 size_t arcPos = 0;
 while ((left - str) < length)
     {
-    char * pos = NULL;
-    unsigned arc = static_cast<unsigned int>(strtoul(left, &pos, 10));
-    if (pos == left)
+    char * p = NULL;
+    unsigned arc = static_cast<unsigned int>(strtoul(left, &p, 10));
+    if (p == left)
         return false;
     a[arcPos++] = arc;
     if (arcPos >= 1024)
         return false;
-    left = pos + 1;
+    left = p + 1;
     }
 *pos = arcPos;
 return true;
index bb0bc0f425848622dbe7036efe2513131864be53..a6369acca8480ce424d1ae89898b957b74114c2c 100644 (file)
@@ -46,14 +46,13 @@ STG_LOCKER lock(&mutex);
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-std::string login;
-
 try
     {
     tr->Start();
     st->Execute("select login from tb_admins");
     while (st->Fetch())
         {
+        std::string login;
         st->Get(1, login);
         adminsList->push_back(login);
         }
index 3b9ad7855be42541e1b3e37bebb93154eecfd857..0d088759dca26b0f28aa255c9cce8e379943bdc9 100644 (file)
@@ -40,14 +40,13 @@ STG_LOCKER lock(&mutex);
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-std::string name;
-
 try
     {
     tr->Start();
     st->Execute("select name from tb_corporations");
     while (st->Fetch())
         {
+        std::string name;
         st->Get(1, name);
         corpsList->push_back(name);
         }
index 0056879ed24a45ccbbd37e7ffe55c3b14cba691f..539fcf73d31868d848705cdc86ef92bc93aea9d5 100644 (file)
@@ -41,14 +41,13 @@ STG_LOCKER lock(&mutex);
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-std::string name;
-
 try
     {
     tr->Start();
     st->Execute("select name from tb_services");
     while (st->Fetch())
         {
+        std::string name;
         st->Get(1, name);
         servicesList->push_back(name);
         }
index 10c45ab9b6a79698185aa6b47eb558ad8e07a0c9..58b571395cbee6c471bd322da8bd66de3df969f3 100644 (file)
@@ -50,14 +50,13 @@ STG_LOCKER lock(&mutex);
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-std::string name;
-
 try
     {
     tr->Start();
     st->Execute("select name from tb_tariffs");
     while (st->Fetch())
         {
+        std::string name;
         st->Get(1, name);
         tariffsList->push_back(name);
         }
index ad28af3a557fa3cf8e6a2f21d1ff3ec1eba6ca9c..bf6e9e9faa4dbd29b8edd51aae1461db0fab6691 100644 (file)
@@ -44,14 +44,13 @@ STG_LOCKER lock(&mutex);
 IBPP::Transaction tr = IBPP::TransactionFactory(db, IBPP::amRead, til, tlr);
 IBPP::Statement st = IBPP::StatementFactory(db, tr);
 
-std::string name;
-
 try
     {
     tr->Start();
     st->Execute("select name from tb_users");
     while (st->Fetch())
         {
+        std::string name;
         st->Get(1, name);
         usersList->push_back(name);
         }
@@ -337,11 +336,11 @@ try
     st->Execute();
 
     st->Prepare("insert into tb_allowed_ip (fk_user, ip, mask) values (?, ?, ?)");
-    for(size_t i = 0; i < conf.ips.count(); i++)
+    for(size_t j = 0; i < conf.ips.count(); j++)
         {
         st->Set(1, uid);
-        st->Set(2, (int32_t)conf.ips[i].ip);
-        st->Set(3, (int32_t)conf.ips[i].mask);
+        st->Set(2, (int32_t)conf.ips[j].ip);
+        st->Set(3, (int32_t)conf.ips[j].mask);
         st->Execute();
         }
     tr->Commit();
index c441a7081ae658d96f3b4428774bc925e583ebdb..a4ee430930b95b9b4a9602ea3747edcb7ce12252 100644 (file)
@@ -265,7 +265,7 @@ if (!(result=mysql_list_tables(sock,str.c_str() )))
     errorStr = "Couldn't get tables list With error:\n";
     errorStr += mysql_error(sock);
     mysql_close(sock);
-    return -1;
+    return false;
 }
 
 my_ulonglong num_rows =  mysql_num_rows(result);
index 656198f4bedc71d6a226f9427ed1568814611ce1..e85a08862c780eded802e77661ab2e79c32f304d 100644 (file)
@@ -37,7 +37,7 @@ namespace
 
 struct Error : public std::runtime_error
 {
-    Error(const std::string& message) : runtime_error(message) {}
+    explicit Error(const std::string& message) : runtime_error(message) {}
 };
 
 std::vector<std::string> toValues(const DOTCONFDocumentNode& node)
index 9cc829ddb4114fd07ead7f5d916aa6e30e697b98..81f582b20f1e7b0f713d94dba14d4217d2d83365 100644 (file)
@@ -47,7 +47,6 @@ TariffsImpl::TariffsImpl(Store * st)
       WriteServLog(Logger::get()),
       noTariff(NO_TARIFF_NAME)
 {
-ReadTariffs();
 }
 //-----------------------------------------------------------------------------
 int TariffsImpl::ReadTariffs()
index 0897d6bfaa103b2c6610aa3429d1074eba0f7a13..e61be9665b626fefbb5703543a24b749da388324 100644 (file)
@@ -66,7 +66,6 @@ TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn)
       monitoring(false),
       touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
       users(u),
-      running(false),
       stopped(true),
       addUserNotifier(*this),
       delUserNotifier(*this)
@@ -78,18 +77,15 @@ dirName[DIR_NUM] = "NULL";
 
 users->AddNotifierUserAdd(&addUserNotifier);
 users->AddNotifierUserDel(&delUserNotifier);
-
-pthread_mutex_init(&mutex, NULL);
 }
 //-----------------------------------------------------------------------------
 TraffCounterImpl::~TraffCounterImpl()
 {
-pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
 int TraffCounterImpl::Start()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 if (!stopped)
     return 0;
@@ -110,13 +106,7 @@ while (users->SearchNext(h, &u) == 0)
     SetUserNotifiers(u);
 users->CloseSearch(h);
 
-running = true;
-if (pthread_create(&thread, NULL, Run, this))
-    {
-    printfd(__FILE__, "TraffCounterImpl::Start() - Cannot start thread\n");
-    WriteServLog("TraffCounter: Error: Cannot start thread.");
-    return -1;
-    }
+m_thread = std::jthread([this](auto token){ Run(token); });
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -125,7 +115,7 @@ int TraffCounterImpl::Stop()
 if (stopped)
     return 0;
 
-running = false;
+m_thread.request_stop();
 
 int h = users->OpenSearch();
 assert(h && "USERS::OpenSearch is always correct");
@@ -143,55 +133,53 @@ for (int i = 0; i < 25 && !stopped; i++)
     }
 
 if (!stopped)
+{
+    m_thread.detach();
     return -1;
+}
 
 printfd(__FILE__, "TraffCounter::Stop()\n");
 
 return 0;
 }
 //-----------------------------------------------------------------------------
-void * TraffCounterImpl::Run(void * data)
+void TraffCounterImpl::Run(std::stop_token token)
 {
 sigset_t signalSet;
 sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
-TraffCounterImpl * tc = static_cast<TraffCounterImpl *>(data);
-tc->stopped = false;
+stopped = false;
 int c = 0;
 
 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
 struct timespec ts = {0, 500000000};
-while (tc->running)
+while (!token.stop_requested())
     {
     nanosleep(&ts, 0);
-    if (!tc->running)
+    if (token.stop_requested())
         {
-        tc->FlushAndRemove();
+        FlushAndRemove();
         break;
         }
 
-    if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
+    if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
         {
-        std::string monFile(tc->monitorDir + "/traffcounter_r");
-        printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", tc->monitoring, monFile.c_str());
+        std::string monFile(monitorDir + "/traffcounter_r");
+        printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
         touchTime = stgTime;
         TouchFile(monFile);
         }
 
     if (++c % FLUSH_TIME == 0)
-        tc->FlushAndRemove();
+        FlushAndRemove();
     }
 
-tc->stopped = true;
-return NULL;
+stopped = true;
 }
 //-----------------------------------------------------------------------------
 void TraffCounterImpl::process(const RawPacket & rawPacket)
 {
-if (!running)
-    return;
-
 if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
     {
     std::string monFile = monitorDir + "/traffcounter_p";
@@ -200,7 +188,7 @@ if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
     TouchFile(monFile);
     }
 
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 //printfd(__FILE__, "TraffCounter::Process()\n");
 //TODO replace find with lower_bound.
@@ -278,7 +266,7 @@ if (ed.userUPresent ||
 //-----------------------------------------------------------------------------
 void TraffCounterImpl::FlushAndRemove()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 Packets::size_type oldPacketsSize = packets.size();
 Index::size_type oldIp2packetsSize = ip2packets.size();
@@ -365,7 +353,7 @@ printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
 uint32_t uip = user->GetCurrIP();
 std::pair<ip2p_iter, ip2p_iter> pi;
 
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 // Find all packets with IP belongs to this user
 pi = ip2packets.equal_range(uip);
 
@@ -402,7 +390,7 @@ void TraffCounterImpl::DelUser(uint32_t uip)
 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
 std::pair<ip2p_iter, ip2p_iter> pi;
 
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 pi = ip2packets.equal_range(uip);
 
 while (pi.first != pi.second)
@@ -703,7 +691,7 @@ return false;
 //-----------------------------------------------------------------------------
 int TraffCounterImpl::Reload()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 if (ReadRules(true))
     {
index 78027cb57d3d7d5eb8b08448b3b4e81843c9d65a..42774bf9f2be1b92d7ea9b5881032bef1228fc97 100644 (file)
 #include <list>
 #include <map>
 #include <string>
+#include <mutex>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 #include <cstdint>
 
-#include <pthread.h>
-
 #define PROTOMAX    (5)
 
 namespace STG
@@ -185,7 +188,7 @@ class TraffCounterImpl : public TraffCounter {
         void        FreeRules();
         bool        ReadRules(bool test = false);
 
-        static void * Run(void * data);
+        void        Run(std::stop_token token);
 
         void        DeterminateDir(const RawPacket & packet,
                                    int * dirU, // Direction for upload
@@ -223,10 +226,9 @@ class TraffCounterImpl : public TraffCounter {
 
         UsersImpl *             users;
 
-        bool                     running;
         bool                     stopped;
-        pthread_mutex_t          mutex;
-        pthread_t                thread;
+        std::mutex               m_mutex;
+        std::jthread             m_thread;
 
         std::list<TRF_IP_BEFORE> ipBeforeNotifiers;
         std::list<TRF_IP_AFTER>  ipAfterNotifiers;
index 2b7cc3a9d750187d32770d9d85112847be0d1495..f5f4c4b4bcf4c47b8a93a90883fcd213dd00d7e7 100644 (file)
@@ -47,6 +47,7 @@
 
 #include <algorithm>
 #include <functional>
+#include <array>
 
 #include <cassert>
 #include <cstdlib>
@@ -641,7 +642,7 @@ void UserImpl::Run()
 {
 STG_LOCKER lock(&mutex);
 
-if (stgTime > static_cast<time_t>(lastWriteStat + settings->GetStatWritePeriod()))
+if (stgTime > lastWriteStat + settings->GetStatWritePeriod())
     {
     printfd(__FILE__, "UserImpl::WriteStat user=%s\n", GetLogin().c_str());
     WriteStat();
@@ -1046,8 +1047,7 @@ double UserImpl::GetPassiveTimePart() const
 {
 STG_LOCKER lock(&mutex);
 
-static int daysInMonth[12] =
-{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
+static const std::array<unsigned, 12> daysInMonth{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
 
 struct tm tms;
 time_t t = stgTime;
index ca8f681fbbebb227a65e9266d4620ffed1a61c12..2e40f03e90f2bd3d5f2efffdb14d7048d7855ff9 100644 (file)
@@ -51,19 +51,13 @@ UsersImpl::UsersImpl(SettingsImpl * s, Store * st,
       store(st),
       sysAdmin(sa),
       WriteServLog(Logger::get()),
-      nonstop(false),
       isRunning(false),
       handle(0)
 {
-pthread_mutexattr_t attr;
-pthread_mutexattr_init(&attr);
-pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
-pthread_mutex_init(&mutex, &attr);
 }
 //-----------------------------------------------------------------------------
 UsersImpl::~UsersImpl()
 {
-pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
 int UsersImpl::FindByNameNonLock(const std::string & login, user_iter * user)
@@ -88,7 +82,7 @@ return 0;
 //-----------------------------------------------------------------------------
 int UsersImpl::FindByName(const std::string & login, UserPtr * user)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 user_iter u;
 if (FindByNameNonLock(login, &u))
     return -1;
@@ -98,7 +92,7 @@ return 0;
 //-----------------------------------------------------------------------------
 int UsersImpl::FindByName(const std::string & login, ConstUserPtr * user) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 const_user_iter u;
 if (FindByNameNonLock(login, &u))
     return -1;
@@ -108,14 +102,14 @@ return 0;
 //-----------------------------------------------------------------------------
 bool UsersImpl::Exists(const std::string & login) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 const std::map<std::string, user_iter>::const_iterator iter(loginIndex.find(login));
 return iter != loginIndex.end();
 }
 //-----------------------------------------------------------------------------
 bool UsersImpl::TariffInUse(const std::string & tariffName) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 std::list<UserImpl>::const_iterator iter;
 iter = users.begin();
 while (iter != users.end())
@@ -129,7 +123,7 @@ return false;
 //-----------------------------------------------------------------------------
 int UsersImpl::Add(const std::string & login, const Admin * admin)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 const auto& priv = admin->priv();
 
 if (!priv.userAddDel)
@@ -197,7 +191,7 @@ if (!priv.userAddDel)
 
 
     {
-    STG_LOCKER lock(&mutex);
+    std::lock_guard<std::mutex> lock(m_mutex);
 
     if (FindByNameNonLock(login, &u))
         {
@@ -229,7 +223,7 @@ if (!priv.userAddDel)
     }
 
     {
-    STG_LOCKER lock(&mutex);
+    std::lock_guard<std::mutex> lock(m_mutex);
 
     u->OnDelete();
 
@@ -250,7 +244,7 @@ bool UsersImpl::Authorize(const std::string & login, uint32_t ip,
                            uint32_t enabledDirs, const Auth * auth)
 {
 user_iter iter;
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 if (FindByNameNonLock(login, &iter))
     {
     WriteServLog("Attempt to authorize non-existant user '%s'", login.c_str());
@@ -283,7 +277,7 @@ bool UsersImpl::Unauthorize(const std::string & login,
                              const std::string & reason)
 {
 user_iter iter;
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 if (FindByNameNonLock(login, &iter))
     {
     WriteServLog("Attempt to unauthorize non-existant user '%s'", login.c_str());
@@ -347,14 +341,13 @@ if (errors > 0)
 return 0;
 }
 //-----------------------------------------------------------------------------
-void * UsersImpl::Run(void * d)
+void UsersImpl::Run(std::stop_token token)
 {
 sigset_t signalSet;
 sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
 printfd(__FILE__, "=====================| pid: %d |===================== \n", getpid());
-UsersImpl * us = static_cast<UsersImpl *>(d);
 
 struct tm t;
 time_t tt = stgTime;
@@ -366,16 +359,16 @@ int day = t.tm_mday;
 printfd(__FILE__,"Day = %d Min = %d\n", day, min);
 
 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
-std::string monFile = us->settings->GetMonitorDir() + "/users_r";
-printfd(__FILE__, "Monitor=%d file USERS %s\n", us->settings->GetMonitoring(), monFile.c_str());
+std::string monFile = settings->GetMonitorDir() + "/users_r";
+printfd(__FILE__, "Monitor=%d file USERS %s\n", settings->GetMonitoring(), monFile.c_str());
 
-us->isRunning = true;
-while (us->nonstop)
+isRunning = true;
+while (!token.stop_requested())
     {
     //printfd(__FILE__,"New Minute. old = %02d current = %02d\n", min, t->tm_min);
     //printfd(__FILE__,"New Day.    old = %2d current = %2d\n", day, t->tm_mday);
 
-    for_each(us->users.begin(), us->users.end(), [](auto& user){ user.Run(); });
+    for_each(users.begin(), users.end(), [](auto& user){ user.Run(); });
 
     tt = stgTime;
     localtime_r(&tt, &t);
@@ -386,7 +379,7 @@ while (us->nonstop)
         printfd(__FILE__,"New Minute. old = %d current = %d\n", min, t.tm_min);
         min = t.tm_min;
 
-        us->NewMinute(t);
+        NewMinute(t);
         }
 
     if (day != t.tm_mday)
@@ -394,10 +387,10 @@ while (us->nonstop)
         printfd(__FILE__,"Sec = %d\n", stgTime);
         printfd(__FILE__,"New Day. old = %d current = %d\n", day, t.tm_mday);
         day = t.tm_mday;
-        us->NewDay(t);
+        NewDay(t);
         }
 
-    if (us->settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
+    if (settings->GetMonitoring() && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
         {
         //printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
         touchTime = stgTime;
@@ -405,19 +398,18 @@ while (us->nonstop)
         }
 
     stgUsleep(100000);
-    } //while (us->nonstop)
+    }
 
-std::list<USER_TO_DEL>::iterator iter(us->usersToDelete.begin());
-while (iter != us->usersToDelete.end())
+std::list<USER_TO_DEL>::iterator iter(usersToDelete.begin());
+while (iter != usersToDelete.end())
     {
     iter->delTime -= 2 * userDeleteDelayTime;
     ++iter;
     }
-us->RealDelUser();
+RealDelUser();
 
-us->isRunning = false;
+isRunning = false;
 
-return NULL;
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::NewMinute(const struct tm & t)
@@ -515,12 +507,7 @@ if (ReadUsers())
     return -1;
     }
 
-nonstop = true;
-if (pthread_create(&thread, NULL, Run, this))
-    {
-    WriteServLog("USERS: Error: Cannot start thread!");
-    return -1;
-    }
+m_thread = std::jthread([this](auto token){ Run(token); });
 return 0;
 }
 //-----------------------------------------------------------------------------
@@ -528,13 +515,7 @@ int UsersImpl::Stop()
 {
 printfd(__FILE__, "USERS::Stop()\n");
 
-if (!isRunning)
-    {
-    //printfd(__FILE__, "Alredy stopped\n");
-    return 0;
-    }
-
-nonstop = false;
+m_thread.request_stop();
 
 //5 seconds to thread stops itself
 struct timespec ts = {0, 200000000};
@@ -549,15 +530,9 @@ for (size_t i = 0; i < 25 * (users.size() / 50 + 1); i++)
 //after 5 seconds waiting thread still running. now kill it
 if (isRunning)
     {
-    printfd(__FILE__, "kill USERS thread.\n");
+    printfd(__FILE__, "Detach USERS thread.\n");
     //TODO pthread_cancel()
-    if (pthread_kill(thread, SIGINT))
-        {
-        //errorStr = "Cannot kill USERS thread.";
-        //printfd(__FILE__, "Cannot kill USERS thread.\n");
-        //return 0;
-        }
-    printfd(__FILE__, "USERS killed\n");
+    m_thread.detach();
     }
 
 printfd(__FILE__, "Before USERS::Run()\n");
@@ -578,7 +553,7 @@ return 0;
 //-----------------------------------------------------------------------------
 void UsersImpl::RealDelUser()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 printfd(__FILE__, "RealDelUser() users to del: %d\n", usersToDelete.size());
 
@@ -613,7 +588,7 @@ uint32_t ip = user->GetCurrIP();
 if (!ip)
     return; // User has disconnected
 
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 const std::map<uint32_t, user_iter>::iterator it(
         ipIndex.lower_bound(ip)
@@ -629,7 +604,7 @@ void UsersImpl::DelFromIPIdx(uint32_t ip)
 printfd(__FILE__, "USERS: Del IP Idx\n");
 assert(ip && "User has non-null ip");
 
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 const std::map<uint32_t, user_iter>::iterator it(
         ipIndex.find(ip)
@@ -652,7 +627,7 @@ return true;
 //-----------------------------------------------------------------------------
 int UsersImpl::FindByIPIdx(uint32_t ip, UserPtr * usr) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 user_iter iter;
 if (FindByIPIdx(ip, iter))
@@ -666,7 +641,7 @@ return -1;
 //-----------------------------------------------------------------------------
 int UsersImpl::FindByIPIdx(uint32_t ip, UserImpl ** usr) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 user_iter iter;
 if (FindByIPIdx(ip, iter))
@@ -680,7 +655,7 @@ return -1;
 //-----------------------------------------------------------------------------
 bool UsersImpl::IsIPInIndex(uint32_t ip) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 std::map<uint32_t, user_iter>::const_iterator it(ipIndex.find(ip));
 
@@ -689,7 +664,7 @@ return it != ipIndex.end();
 //-----------------------------------------------------------------------------
 bool UsersImpl::IsIPInUse(uint32_t ip, const std::string & login, ConstUserPtr * user) const
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 std::list<UserImpl>::const_iterator iter;
 iter = users.begin();
 while (iter != users.end())
@@ -709,55 +684,55 @@ return false;
 //-----------------------------------------------------------------------------
 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onAddNotifiers.insert(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onAddNotifiers.erase(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::AddNotifierUserDel(NotifierBase<UserPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onDelNotifiers.insert(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::DelNotifierUserDel(NotifierBase<UserPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onDelNotifiers.erase(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::AddNotifierUserAdd(NotifierBase<UserImplPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onAddNotifiersImpl.insert(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::DelNotifierUserAdd(NotifierBase<UserImplPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onAddNotifiersImpl.erase(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::AddNotifierUserDel(NotifierBase<UserImplPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onDelNotifiersImpl.insert(n);
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::DelNotifierUserDel(NotifierBase<UserImplPtr> * n)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 onDelNotifiersImpl.erase(n);
 }
 //-----------------------------------------------------------------------------
 int UsersImpl::OpenSearch()
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 handle++;
 searchDescriptors[handle] = users.begin();
 return handle;
@@ -774,7 +749,7 @@ int UsersImpl::SearchNext(int h, UserPtr * user)
 //-----------------------------------------------------------------------------
 int UsersImpl::SearchNext(int h, UserImpl ** user)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 if (searchDescriptors.find(h) == searchDescriptors.end())
     {
@@ -803,7 +778,7 @@ return 0;
 //-----------------------------------------------------------------------------
 int UsersImpl::CloseSearch(int h)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 if (searchDescriptors.find(h) != searchDescriptors.end())
     {
     searchDescriptors.erase(searchDescriptors.find(h));
@@ -816,13 +791,13 @@ return -1;
 //-----------------------------------------------------------------------------
 void UsersImpl::AddUserIntoIndexes(user_iter user)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 loginIndex.insert(make_pair(user->GetLogin(), user));
 }
 //-----------------------------------------------------------------------------
 void UsersImpl::DelUserFromIndexes(user_iter user)
 {
-STG_LOCKER lock(&mutex);
+std::lock_guard<std::mutex> lock(m_mutex);
 loginIndex.erase(user->GetLogin());
 }
 //-----------------------------------------------------------------------------
index ef5ee0ec767ff2404575a2e0fa926c03591b4e48..5aa2a494a6e85f75d37117324a7edebc8647703c 100644 (file)
 #include <map>
 #include <list>
 #include <set>
+#include <mutex>
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wshadow"
+#include <jthread.hpp>
+#pragma GCC diagnostic pop
 #include <ctime>
 #include <cstdint>
 
@@ -133,7 +138,7 @@ private:
     void            AddUserIntoIndexes(user_iter user);
     void            DelUserFromIndexes(user_iter user);
 
-    static void *   Run(void *);
+    void            Run(std::stop_token token);
     void            NewMinute(const struct tm & t);
     void            NewDay(const struct tm & t);
     void            DayResetTraff(const struct tm & t);
@@ -153,11 +158,10 @@ private:
     const Admin&       sysAdmin;
     Logger &        WriteServLog;
 
-    bool                nonstop;
     bool                isRunning;
 
-    mutable pthread_mutex_t mutex;
-    pthread_t               thread;
+    mutable std::mutex      m_mutex;
+    std::jthread            m_thread;
     mutable unsigned int    handle;
 
     mutable std::map<int, user_iter>  searchDescriptors;
index 226b9b22d0296869bdf0c4a2ef2bd5be963431f2..cedaaebd03879514e9032330e4c82032ce06616b 100644 (file)
@@ -23,3 +23,5 @@ add_executable ( tests ${CPP_FILES} )
 target_link_libraries ( tests conffiles crypto logger scriptexecuter common Threads::Threads )
 
 target_include_directories ( tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ../projects/stargazer )
+
+add_test ( tests tests )
index 3223df83d988b4e466589034fbccd865887c9392..430005fcb7ed6e849d048092be3d9a60a7e8e024 100644 (file)
@@ -65,6 +65,7 @@ namespace tut
         TEST_SETTINGS_LOCAL settings;
         settings.addFilter("*"); // Allow everything by default.
         TEST_TARIFFS tariffs;
+        tariffs.ReadTariffs();
         STG::Admin admin(STG::Priv(0xFFFF), {}, {});
         TEST_STORE_LOCAL store;
         TEST_AUTH auth;
index b2e2aa022ba9c4f561704a7efd32d3aa1e00dacc..60e36ffa64df3d0c15836d8dc7b7fb125741a786 100644 (file)
@@ -63,6 +63,7 @@ namespace tut
 
         TEST_SETTINGS_LOCAL settings(false);
         TEST_TARIFFS tariffs;
+        tariffs.ReadTariffs();
         STG::Admin admin(STG::Priv(0xFFFF), {}, {});
         TEST_STORE store;
         TEST_AUTH auth;