]> git.stg.codes - stg.git/blobdiff - projects/stargazer/traffcounter_impl.cpp
More subscriptions, less notifiers.
[stg.git] / projects / stargazer / traffcounter_impl.cpp
index 83c699f8ed9ac7d4b760f78fa822dfd1838a617e..44f2e5580ff8ec431655326b9cc57815d753a84a 100644 (file)
 #include "traffcounter_impl.h"
 #include "stg_timer.h"
 #include "users_impl.h"
+#include "async_pool.h"
 
 #define FLUSH_TIME  (10)
 #define REMOVE_TIME  (31)
 
+using STG::TraffCounterImpl;
+using STG::TRF_IP_BEFORE;
+using STG::TRF_IP_AFTER;
+
+namespace AsyncPoolST = STG::AsyncPoolST;
+
 const char protoName[PROTOMAX][8] =
 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
 
@@ -58,163 +65,140 @@ tcp = 0, udp, icmp, tcp_udp, all
 };
 
 //-----------------------------------------------------------------------------
-TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
-    : TRAFFCOUNTER(),
-      rules(),
-      packets(),
-      ip2packets(),
-      dirName(),
-      WriteServLog(GetStgLogger()),
+TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn)
+    : WriteServLog(Logger::get()),
       rulesFileName(fn),
-      monitorDir(),
       monitoring(false),
       touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
       users(u),
-      running(false),
-      stopped(true),
-      mutex(),
-      thread(),
-      ipBeforeNotifiers(),
-      ipAfterNotifiers(),
-      addUserNotifier(*this),
-      delUserNotifier(*this)
+      stopped(true)
 {
 for (int i = 0; i < DIR_NUM; i++)
     strprintf(&dirName[i], "DIR%d", i);
 
 dirName[DIR_NUM] = "NULL";
 
-users->AddNotifierUserAdd(&addUserNotifier);
-users->AddNotifierUserDel(&delUserNotifier);
-
-pthread_mutex_init(&mutex, NULL);
+m_onAddUserConn = users->onImplAdd([this](auto user){
+    AsyncPoolST::enqueue([this, user](){ SetUserNotifiers(user); });
+});
+m_onDelUserConn = users->onImplDel([this](auto user){
+    AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); });
+    AsyncPoolST::enqueue([this, user](){ DelUser(user->GetCurrIP()); });
+});
 }
 //-----------------------------------------------------------------------------
-TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
+TraffCounterImpl::~TraffCounterImpl()
 {
-pthread_mutex_destroy(&mutex);
 }
 //-----------------------------------------------------------------------------
-int TRAFFCOUNTER_IMPL::Start()
+int TraffCounterImpl::Start()
 {
-STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 if (!stopped)
     return 0;
 
 if (ReadRules())
     {
-    printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
-    WriteServLog("TRAFFCOUNTER: Cannot read rules.");
+    printfd(__FILE__, "TraffCounterImpl::Start() - Cannot read rules\n");
+    WriteServLog("TraffCounter: Cannot read rules.");
     return -1;
     }
 
-printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
+printfd(__FILE__, "TraffCounter::Start()\n");
 int h = users->OpenSearch();
 assert(h && "USERS::OpenSearch is always correct");
-USER_IMPL * u;
+UserImpl * u;
 
 while (users->SearchNext(h, &u) == 0)
-    {
     SetUserNotifiers(u);
-    }
 users->CloseSearch(h);
 
-running = true;
-if (pthread_create(&thread, NULL, Run, this))
-    {
-    printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
-    WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
-    return -1;
-    }
+m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
 return 0;
 }
 //-----------------------------------------------------------------------------
-int TRAFFCOUNTER_IMPL::Stop()
+int TraffCounterImpl::Stop()
 {
 if (stopped)
     return 0;
 
-running = false;
+m_thread.request_stop();
 
 int h = users->OpenSearch();
 assert(h && "USERS::OpenSearch is always correct");
 
-USER_IMPL * u;
+UserImpl * u;
 while (users->SearchNext(h, &u) == 0)
-    {
     UnSetUserNotifiers(u);
-    }
 users->CloseSearch(h);
 
 //5 seconds to thread stops itself
 struct timespec ts = {0, 200000000};
 for (int i = 0; i < 25 && !stopped; i++)
-    {
     nanosleep(&ts, NULL);
-    }
 
 if (!stopped)
+{
+    m_thread.detach();
     return -1;
+}
 
-printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
+m_thread.join();
+
+printfd(__FILE__, "TraffCounter::Stop()\n");
 
 return 0;
 }
 //-----------------------------------------------------------------------------
-void * TRAFFCOUNTER_IMPL::Run(void * data)
+void TraffCounterImpl::Run(std::stop_token token)
 {
 sigset_t signalSet;
 sigfillset(&signalSet);
 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
 
-TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(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.c_str());
+        TouchFile(monFile);
         }
 
     if (++c % FLUSH_TIME == 0)
-        tc->FlushAndRemove();
+        FlushAndRemove();
     }
 
-tc->stopped = true;
-return NULL;
+stopped = true;
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
+void TraffCounterImpl::process(const RawPacket & rawPacket)
 {
-if (!running)
-    return;
-
 if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
     {
     std::string monFile = monitorDir + "/traffcounter_p";
-    printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
+    printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
     touchTimeP = stgTime;
-    TouchFile(monFile.c_str());
+    TouchFile(monFile);
     }
 
-STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::lock_guard<std::mutex> lock(m_mutex);
 
-//printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
+//printfd(__FILE__, "TraffCounter::Process()\n");
 //TODO replace find with lower_bound.
 
 // Searching a new packet in a tree.
@@ -243,7 +227,7 @@ if (pi != packets.end())
     return;
     }
 
-PACKET_EXTRA_DATA ed;
+PacketExtraData ed;
 
 // Packet not found - add new packet
 
@@ -288,9 +272,9 @@ if (ed.userUPresent ||
     }
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::FlushAndRemove()
+void TraffCounterImpl::FlushAndRemove()
 {
-STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 Packets::size_type oldPacketsSize = packets.size();
 Index::size_type oldIp2packetsSize = ip2packets.size();
@@ -371,13 +355,13 @@ printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n
 
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user)
+void TraffCounterImpl::AddUser(UserImpl * user)
 {
 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, __FILE__, __LINE__);
+std::lock_guard<std::mutex> lock(m_mutex);
 // Find all packets with IP belongs to this user
 pi = ip2packets.equal_range(uip);
 
@@ -385,7 +369,7 @@ while (pi.first != pi.second)
     {
     if (pi.first->second->first.GetSrcIP() == uip)
         {
-        assert((!pi.first->second->second.userUPresent || 
+        assert((!pi.first->second->second.userUPresent ||
                  pi.first->second->second.userU == user) &&
                "U user present but it's not current user");
 
@@ -396,7 +380,7 @@ while (pi.first != pi.second)
 
     if (pi.first->second->first.GetDstIP() == uip)
         {
-        assert((!pi.first->second->second.userDPresent || 
+        assert((!pi.first->second->second.userDPresent ||
                  pi.first->second->second.userD == user) &&
                "D user present but it's not current user");
 
@@ -409,12 +393,12 @@ while (pi.first != pi.second)
     }
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
+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, __FILE__, __LINE__);
+std::lock_guard<std::mutex> lock(m_mutex);
 pi = ip2packets.equal_range(uip);
 
 while (pi.first != pi.second)
@@ -462,7 +446,7 @@ while (pi.first != pi.second)
 ip2packets.erase(pi.first, pi.second);
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user)
+void TraffCounterImpl::SetUserNotifiers(UserImpl * user)
 {
 // Adding user. Adding notifiers to user.
 TRF_IP_BEFORE ipBNotifier(*this, user);
@@ -474,7 +458,7 @@ ipAfterNotifiers.push_front(ipANotifier);
 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
+void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user)
 {
 // Removing user. Removing notifiers from user.
 std::list<TRF_IP_BEFORE>::iterator bi;
@@ -505,28 +489,27 @@ while (ai != ipAfterNotifiers.end())
     }
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
+void TraffCounterImpl::DeterminateDir(const RawPacket & packet,
                                        int * dirU, // Direction for incoming packet
                                        int * dirD) const // Direction for outgoing packet
 {
-bool addrMatchU;
-bool portMatchU;
-bool addrMatchD;
-bool portMatchD;
+bool addrMatchU = false;
+bool portMatchU = false;
+bool addrMatchD = false;
+bool portMatchD = false;
 bool foundU = false; // Was rule for U found ?
 bool foundD = false; // Was rule for D found ?
 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
 
 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
 
-std::list<RULE>::const_iterator ln;
+std::list<Rule>::const_iterator ln;
 ln = rules.begin();
 
 while (ln != rules.end())
     {
     if (!foundU)
         {
-        addrMatchU = false;
         portMatchU = false;
 
         switch (ln->proto)
@@ -572,7 +555,6 @@ while (ln != rules.end())
 
     if (!foundD)
         {
-        addrMatchD = false;
         portMatchD = false;
 
         switch (ln->proto)
@@ -625,11 +607,11 @@ if (!foundD)
     *dirD = DIR_NUM;
 }
 //-----------------------------------------------------------------------------
-bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
+bool TraffCounterImpl::ReadRules(bool test)
 {
-//printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
+//printfd(__FILE__, "TraffCounter::ReadRules()\n");
 
-RULE rul;
+Rule rul;
 FILE * f;
 char str[1024];
 char tp[100];   // protocol
@@ -641,7 +623,7 @@ f = fopen(rulesFileName.c_str(), "rt");
 
 if (!f)
     {
-    printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
+    printfd(__FILE__, "TraffCounterImpl::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
     return true;
     }
@@ -654,10 +636,10 @@ while (fgets(str, 1023, f))
         continue;
         }
 
-    r = sscanf(str,"%s %s %s", tp, ta, td);
+    r = sscanf(str,"%99s %99s %99s", tp, ta, td);
     if (r != 3)
         {
-        printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
+        printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
         fclose(f);
         return true;
@@ -680,7 +662,7 @@ while (fgets(str, 1023, f))
 
     if (rul.dir == 0xff || rul.proto == 0xff)
         {
-        printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
+        printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
         WriteServLog("Error in file %s. Line %d.",
                      rulesFileName.c_str(), lineNumber);
         fclose(f);
@@ -689,7 +671,7 @@ while (fgets(str, 1023, f))
 
     if (ParseAddress(ta, &rul) != 0)
         {
-        printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
+        printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
         WriteServLog("Error in file %s. Error in adress. Line %d.",
                      rulesFileName.c_str(), lineNumber);
         fclose(f);
@@ -715,25 +697,25 @@ if (!test)
 return false;
 }
 //-----------------------------------------------------------------------------
-int TRAFFCOUNTER_IMPL::Reload()
+int TraffCounterImpl::Reload()
 {
-STG_LOCKER lock(&mutex, __FILE__, __LINE__);
+std::lock_guard<std::mutex> lock(m_mutex);
 
 if (ReadRules(true))
     {
-    printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
-    WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
+    printfd(__FILE__, "TraffCounterImpl::Reload() - Failed to reload rules.\n");
+    WriteServLog("TraffCounter: Cannot reload rules. Errors found.");
     return -1;
     }
 
 FreeRules();
 ReadRules();
-printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reloaded rules successfully.\n");
-WriteServLog("TRAFFCOUNTER: Reloaded rules successfully.");
+printfd(__FILE__, "TraffCounterImpl::Reload() -  Reloaded rules successfully.\n");
+WriteServLog("TraffCounter: Reloaded rules successfully.");
 return 0;
 }
 //-----------------------------------------------------------------------------
-bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
+bool TraffCounterImpl::ParseAddress(const char * ta, Rule * rule) const
 {
 char addr[50], mask[20], port1[20], port2[20], ports[40];
 
@@ -783,7 +765,7 @@ if (n == ':')
     // port
     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
         {
-        printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
+        printfd(__FILE__, "TraffCounterImpl::ParseAddress() - No ports specified for this protocol.\n");
         WriteServLog("No ports specified for this protocol.");
         return true;
         }
@@ -837,12 +819,10 @@ if (r == 0)
 
 rule->ip = ipaddr.s_addr;
 rule->mask = CalcMask(msk);
-//msk = 1;
-//printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
 
 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
     {
-    printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
+    printfd(__FILE__, "TraffCounterImpl::ParseAddress() - Address does'n match mask.\n");
     WriteServLog("Address does'n match mask.");
     return true;
     }
@@ -853,21 +833,39 @@ rule->port2 = prt2;
 return false;
 }
 //-----------------------------------------------------------------------------
-uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
+uint32_t TraffCounterImpl::CalcMask(uint32_t msk) const
 {
 if (msk >= 32) return 0xFFffFFff;
 if (msk == 0) return 0;
 return htonl(0xFFffFFff << (32 - msk));
 }
 //---------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::FreeRules()
+void TraffCounterImpl::FreeRules()
 {
 rules.clear();
 }
 //-----------------------------------------------------------------------------
-void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir)
+void TraffCounterImpl::SetMonitorDir(const std::string & dir)
 {
 monitorDir = dir;
 monitoring = !monitorDir.empty();
 }
 //-----------------------------------------------------------------------------
+void TRF_IP_BEFORE::notify(const uint32_t & oldValue, const uint32_t &)
+{
+// User changes his address. Remove old IP
+if (!oldValue)
+    return;
+
+AsyncPoolST::enqueue([this, oldValue](){ traffCnt.DelUser(oldValue); });
+}
+//-----------------------------------------------------------------------------
+void TRF_IP_AFTER::notify(const uint32_t &, const uint32_t & newValue)
+{
+// User changes his address. Add new IP
+if (!newValue)
+    return;
+
+AsyncPoolST::enqueue([this](){ traffCnt.AddUser(user); });
+}
+//-----------------------------------------------------------------------------