2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or
5 * (at your option) any later version.
7 * This program is distributed in the hope that it will be useful,
8 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 * GNU General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
27 $Date: 2010/11/03 11:28:07 $
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
39 #include <cstdio> // fopen and similar
40 #include <cstdlib> // strtol
42 #include "stg/common.h"
43 #include "stg/const.h" // MONITOR_TIME_DELAY_SEC
44 #include "traffcounter_impl.h"
45 #include "stg_timer.h"
46 #include "users_impl.h"
47 #include "async_pool.h"
49 #define FLUSH_TIME (10)
50 #define REMOVE_TIME (31)
52 using STG::TraffCounterImpl;
54 namespace AsyncPoolST = STG::AsyncPoolST;
56 const char protoName[PROTOMAX][8] =
57 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
61 tcp = 0, udp, icmp, tcp_udp, all
64 //-----------------------------------------------------------------------------
65 TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn)
66 : WriteServLog(Logger::get()),
69 touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
73 for (int i = 0; i < DIR_NUM; i++)
74 strprintf(&dirName[i], "DIR%d", i);
76 dirName[DIR_NUM] = "NULL";
78 m_onAddUserConn = users->onImplAdd([this](auto user){
79 AsyncPoolST::enqueue([this, user](){ SetUserNotifiers(user); });
81 m_onDelUserConn = users->onImplDel([this](auto user){
82 AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); DelUser(user->GetCurrIP()); });
85 //-----------------------------------------------------------------------------
86 TraffCounterImpl::~TraffCounterImpl()
89 //-----------------------------------------------------------------------------
90 int TraffCounterImpl::Start()
92 std::lock_guard<std::mutex> lock(m_mutex);
99 printfd(__FILE__, "TraffCounterImpl::Start() - Cannot read rules\n");
100 WriteServLog("TraffCounter: Cannot read rules.");
104 printfd(__FILE__, "TraffCounter::Start()\n");
105 int h = users->OpenSearch();
106 assert(h && "USERS::OpenSearch is always correct");
109 while (users->SearchNext(h, &u) == 0)
111 users->CloseSearch(h);
113 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
116 //-----------------------------------------------------------------------------
117 int TraffCounterImpl::Stop()
122 m_thread.request_stop();
124 int h = users->OpenSearch();
125 assert(h && "USERS::OpenSearch is always correct");
129 //5 seconds to thread stops itself
130 for (int i = 0; i < 25 && !stopped; i++)
131 std::this_thread::sleep_for(std::chrono::milliseconds(200));
141 printfd(__FILE__, "TraffCounter::Stop()\n");
145 //-----------------------------------------------------------------------------
146 void TraffCounterImpl::Run(std::stop_token token)
149 sigfillset(&signalSet);
150 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
155 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
156 while (!token.stop_requested())
158 std::this_thread::sleep_for(std::chrono::milliseconds(500));
159 if (token.stop_requested())
165 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
167 std::string monFile(monitorDir + "/traffcounter_r");
168 printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
173 if (++c % FLUSH_TIME == 0)
179 //-----------------------------------------------------------------------------
180 void TraffCounterImpl::process(const RawPacket & rawPacket)
182 if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
184 std::string monFile = monitorDir + "/traffcounter_p";
185 printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
186 touchTimeP = stgTime;
190 std::lock_guard<std::mutex> lock(m_mutex);
192 //printfd(__FILE__, "TraffCounter::Process()\n");
193 //TODO replace find with lower_bound.
195 // Searching a new packet in a tree.
196 pp_iter pi = packets.find(rawPacket);
198 // Packet found - update length and time
199 if (pi != packets.end())
201 pi->second.lenU += rawPacket.GetLen();
202 pi->second.lenD += rawPacket.GetLen();
203 pi->second.updateTime = stgTime;
204 /*printfd(__FILE__, "=============================\n");
205 printfd(__FILE__, "Packet found!\n");
206 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
207 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
208 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
209 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
210 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
211 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
212 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
213 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
214 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
215 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
216 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
217 printfd(__FILE__, "=============================\n");*/
223 // Packet not found - add new packet
225 ed.updateTime = stgTime;
226 ed.flushTime = stgTime;
229 userU is that whose user_ip == packet_ip_src
230 userD is that whose user_ip == packet_ip_dst
233 uint32_t ipU = rawPacket.GetSrcIP();
234 uint32_t ipD = rawPacket.GetDstIP();
236 // Searching users with such IP
237 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
239 ed.userUPresent = true;
242 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
244 ed.userDPresent = true;
247 if (ed.userUPresent ||
250 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
252 ed.lenD = ed.lenU = rawPacket.GetLen();
254 //TODO use result of lower_bound to inserting new record
256 // Adding packet to a tree.
257 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
258 pp_iter newPacket = insertResult.first;
260 // Adding packet reference to an IP index.
261 ip2packets.insert(std::make_pair(ipU, newPacket));
262 ip2packets.insert(std::make_pair(ipD, newPacket));
265 //-----------------------------------------------------------------------------
266 void TraffCounterImpl::FlushAndRemove()
268 std::lock_guard<std::mutex> lock(m_mutex);
270 Packets::size_type oldPacketsSize = packets.size();
271 Index::size_type oldIp2packetsSize = ip2packets.size();
274 pi = packets.begin();
276 ip2packets.erase(ip2packets.begin(), ip2packets.end());
277 while (pi != packets.end())
280 if (stgTime - pi->second.flushTime > FLUSH_TIME)
282 if (pi->second.userUPresent)
284 //printfd(__FILE__, "+++ Flushing U user %s (%s:%d) of length %d\n", pi->second.userU->GetLogin().c_str(), inet_ntostring(pi->first.GetSrcIP()).c_str(), pi->first.GetSrcPort(), pi->second.lenU);
287 if (pi->second.dirU < DIR_NUM)
289 #ifdef TRAFF_STAT_WITH_PORTS
290 pi->second.userU->AddTraffStatU(pi->second.dirU,
291 pi->first.GetDstIP(),
292 pi->first.GetDstPort(),
295 pi->second.userU->AddTraffStatU(pi->second.dirU,
296 pi->first.GetDstIP(),
302 pi->second.flushTime = stgTime;
305 if (pi->second.userDPresent)
307 //printfd(__FILE__, "+++ Flushing D user %s (%s:%d) of length %d\n", pi->second.userD->GetLogin().c_str(), inet_ntostring(pi->first.GetDstIP()).c_str(), pi->first.GetDstPort(), pi->second.lenD);
310 if (pi->second.dirD < DIR_NUM)
312 #ifdef TRAFF_STAT_WITH_PORTS
313 pi->second.userD->AddTraffStatD(pi->second.dirD,
314 pi->first.GetSrcIP(),
315 pi->first.GetSrcPort(),
318 pi->second.userD->AddTraffStatD(pi->second.dirD,
319 pi->first.GetSrcIP(),
325 pi->second.flushTime = stgTime;
329 if (stgTime - pi->second.updateTime < REMOVE_TIME)
331 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
334 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
335 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
340 swap(packets, newPackets);
341 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
343 oldPacketsSize - packets.size(),
345 oldIp2packetsSize - ip2packets.size());
348 //-----------------------------------------------------------------------------
349 void TraffCounterImpl::AddUser(UserImpl * user)
351 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
352 uint32_t uip = user->GetCurrIP();
353 std::pair<ip2p_iter, ip2p_iter> pi;
355 std::lock_guard<std::mutex> lock(m_mutex);
356 // Find all packets with IP belongs to this user
357 pi = ip2packets.equal_range(uip);
359 while (pi.first != pi.second)
361 if (pi.first->second->first.GetSrcIP() == uip)
363 assert((!pi.first->second->second.userUPresent ||
364 pi.first->second->second.userU == user) &&
365 "U user present but it's not current user");
367 pi.first->second->second.lenU = 0;
368 pi.first->second->second.userU = user;
369 pi.first->second->second.userUPresent = true;
372 if (pi.first->second->first.GetDstIP() == uip)
374 assert((!pi.first->second->second.userDPresent ||
375 pi.first->second->second.userD == user) &&
376 "D user present but it's not current user");
378 pi.first->second->second.lenD = 0;
379 pi.first->second->second.userD = user;
380 pi.first->second->second.userDPresent = true;
386 //-----------------------------------------------------------------------------
387 void TraffCounterImpl::DelUser(uint32_t uip)
389 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
390 std::pair<ip2p_iter, ip2p_iter> pi;
392 std::lock_guard<std::mutex> lock(m_mutex);
393 pi = ip2packets.equal_range(uip);
395 while (pi.first != pi.second)
397 if (pi.first->second->first.GetSrcIP() == uip)
399 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
401 #ifdef TRAFF_STAT_WITH_PORTS
402 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
403 pi.first->second->first.GetDstIP(),
404 pi.first->second->first.GetDstPort(),
405 pi.first->second->second.lenU);
407 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
408 pi.first->second->first.GetDstIP(),
409 pi.first->second->second.lenU);
412 pi.first->second->second.userUPresent = false;
415 if (pi.first->second->first.GetDstIP() == uip)
417 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
419 #ifdef TRAFF_STAT_WITH_PORTS
420 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
421 pi.first->second->first.GetSrcIP(),
422 pi.first->second->first.GetSrcPort(),
423 pi.first->second->second.lenD);
425 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
426 pi.first->second->first.GetSrcIP(),
427 pi.first->second->second.lenD);
431 pi.first->second->second.userDPresent = false;
437 ip2packets.erase(pi.first, pi.second);
439 //-----------------------------------------------------------------------------
440 void TraffCounterImpl::SetUserNotifiers(UserImpl* user)
442 // Adding user. Adding notifiers to user.
443 m_onIPConns.emplace_back(
445 user->beforeCurrIPChange([this](auto oldVal, auto /*newVal*/){ beforeIPChange(oldVal); }),
446 user->afterCurrIPChange([this, user](auto /*oldVal*/, auto newVal){ afterIPChange(user, newVal); })
449 //-----------------------------------------------------------------------------
450 void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user)
452 // Removing user. Removing notifiers from user.
453 m_onIPConns.erase(std::remove_if(m_onIPConns.begin(), m_onIPConns.end(),
454 [user](const auto& cs){ return std::get<0>(cs) == user->GetID(); }),
457 //-----------------------------------------------------------------------------
458 void TraffCounterImpl::DeterminateDir(const RawPacket & packet,
459 int * dirU, // Direction for incoming packet
460 int * dirD) const // Direction for outgoing packet
462 bool addrMatchU = false;
463 bool portMatchU = false;
464 bool addrMatchD = false;
465 bool portMatchD = false;
466 bool foundU = false; // Was rule for U found ?
467 bool foundD = false; // Was rule for D found ?
468 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
470 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
472 std::list<Rule>::const_iterator ln;
475 while (ln != rules.end())
488 portMatchU = (packet.GetProto() == ICMP_RPOTO);
492 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
493 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
497 if (packet.GetProto() == TCP_PROTO)
498 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
502 if (packet.GetProto() == UDP_PROTO)
503 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
507 printfd(__FILE__, "Error! Incorrect rule!\n");
511 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
513 if (!foundU && addrMatchU && portMatchU)
517 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
533 portMatchD = (packet.GetProto() == ICMP_RPOTO);
537 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
538 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
542 if (packet.GetProto() == TCP_PROTO)
543 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
547 if (packet.GetProto() == UDP_PROTO)
548 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
552 printfd(__FILE__, "Error! Incorrect rule!\n");
556 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
558 if (!foundD && addrMatchD && portMatchD)
562 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
567 } //while (ln != rules.end())
575 //-----------------------------------------------------------------------------
576 bool TraffCounterImpl::ReadRules(bool test)
578 //printfd(__FILE__, "TraffCounter::ReadRules()\n");
583 char tp[100]; // protocol
584 char ta[100]; // address
585 char td[100]; // target direction
588 f = fopen(rulesFileName.c_str(), "rt");
592 printfd(__FILE__, "TraffCounterImpl::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
593 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
597 while (fgets(str, 1023, f))
600 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
605 r = sscanf(str,"%99s %99s %99s", tp, ta, td);
608 printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
609 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
617 for (uint8_t i = 0; i < PROTOMAX; i++)
619 if (strcasecmp(tp, protoName[i]) == 0)
623 for (uint32_t i = 0; i < DIR_NUM + 1; i++)
625 if (td == dirName[i])
629 if (rul.dir == 0xff || rul.proto == 0xff)
631 printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
632 WriteServLog("Error in file %s. Line %d.",
633 rulesFileName.c_str(), lineNumber);
638 if (ParseAddress(ta, &rul) != 0)
640 printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
641 WriteServLog("Error in file %s. Error in adress. Line %d.",
642 rulesFileName.c_str(), lineNumber);
647 rules.push_back(rul);
652 // Adding lastest rule: ALL 0.0.0.0/0 NULL
653 rul.dir = DIR_NUM; //NULL
654 rul.ip = 0; //0.0.0.0
661 rules.push_back(rul);
665 //-----------------------------------------------------------------------------
666 int TraffCounterImpl::Reload()
668 std::lock_guard<std::mutex> lock(m_mutex);
672 printfd(__FILE__, "TraffCounterImpl::Reload() - Failed to reload rules.\n");
673 WriteServLog("TraffCounter: Cannot reload rules. Errors found.");
679 printfd(__FILE__, "TraffCounterImpl::Reload() - Reloaded rules successfully.\n");
680 WriteServLog("TraffCounter: Reloaded rules successfully.");
683 //-----------------------------------------------------------------------------
684 bool TraffCounterImpl::ParseAddress(const char * ta, Rule * rule) const
686 char addr[50], mask[20], port1[20], port2[20], ports[40];
688 size_t len = strlen(ta);
691 memset(addr, 0, sizeof(addr));
692 for (i = 0; i < len; i++)
694 if (ta[i] == '/' || ta[i] == ':')
732 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
734 printfd(__FILE__, "TraffCounterImpl::ParseAddress() - No ports specified for this protocol.\n");
735 WriteServLog("No ports specified for this protocol.");
740 ports[i - p] = ta[i];
746 strcpy(ports, "0-65535");
753 if ((sss = strchr(ports, '-')) != NULL)
755 strncpy(port1, ports, int(sss-ports));
756 port1[int(sss - ports)] = 0;
757 strcpy(port2, sss + 1);
761 strcpy(port1, ports);
762 strcpy(port2, ports);
765 // Convert strings to mask, ports and IP
766 uint16_t prt1, prt2, msk;
767 struct in_addr ipaddr;
770 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
774 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
778 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
782 int r = inet_aton(addr, &ipaddr);
786 rule->ip = ipaddr.s_addr;
787 rule->mask = CalcMask(msk);
789 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
791 printfd(__FILE__, "TraffCounterImpl::ParseAddress() - Address does'n match mask.\n");
792 WriteServLog("Address does'n match mask.");
801 //-----------------------------------------------------------------------------
802 uint32_t TraffCounterImpl::CalcMask(uint32_t msk) const
804 if (msk >= 32) return 0xFFffFFff;
805 if (msk == 0) return 0;
806 return htonl(0xFFffFFff << (32 - msk));
808 //---------------------------------------------------------------------------
809 void TraffCounterImpl::FreeRules()
813 //-----------------------------------------------------------------------------
814 void TraffCounterImpl::SetMonitorDir(const std::string & dir)
817 monitoring = !monitorDir.empty();
819 //-----------------------------------------------------------------------------
820 void TraffCounterImpl::beforeIPChange(uint32_t oldVal)
822 // User changes his address. Remove old IP
826 AsyncPoolST::enqueue([this, oldVal](){ DelUser(oldVal); });
828 //-----------------------------------------------------------------------------
829 void TraffCounterImpl::afterIPChange(UserImpl* user, uint32_t newVal)
831 // User changes his address. Add new IP
835 AsyncPoolST::enqueue([this, user](){ AddUser(user); });
837 //-----------------------------------------------------------------------------