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/locker.h"
44 #include "stg/const.h" // MONITOR_TIME_DELAY_SEC
45 #include "traffcounter_impl.h"
46 #include "stg_timer.h"
47 #include "users_impl.h"
49 #define FLUSH_TIME (10)
50 #define REMOVE_TIME (31)
52 using STG::TraffCounterImpl;
54 const char protoName[PROTOMAX][8] =
55 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
59 tcp = 0, udp, icmp, tcp_udp, all
62 //-----------------------------------------------------------------------------
63 TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn)
64 : WriteServLog(Logger::get()),
67 touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
70 addUserNotifier(*this),
71 delUserNotifier(*this)
73 for (int i = 0; i < DIR_NUM; i++)
74 strprintf(&dirName[i], "DIR%d", i);
76 dirName[DIR_NUM] = "NULL";
78 users->AddNotifierUserAdd(&addUserNotifier);
79 users->AddNotifierUserDel(&delUserNotifier);
81 //-----------------------------------------------------------------------------
82 TraffCounterImpl::~TraffCounterImpl()
85 //-----------------------------------------------------------------------------
86 int TraffCounterImpl::Start()
88 std::lock_guard<std::mutex> lock(m_mutex);
95 printfd(__FILE__, "TraffCounterImpl::Start() - Cannot read rules\n");
96 WriteServLog("TraffCounter: Cannot read rules.");
100 printfd(__FILE__, "TraffCounter::Start()\n");
101 int h = users->OpenSearch();
102 assert(h && "USERS::OpenSearch is always correct");
105 while (users->SearchNext(h, &u) == 0)
107 users->CloseSearch(h);
109 m_thread = std::jthread([this](auto token){ Run(token); });
112 //-----------------------------------------------------------------------------
113 int TraffCounterImpl::Stop()
118 m_thread.request_stop();
120 int h = users->OpenSearch();
121 assert(h && "USERS::OpenSearch is always correct");
124 while (users->SearchNext(h, &u) == 0)
125 UnSetUserNotifiers(u);
126 users->CloseSearch(h);
128 //5 seconds to thread stops itself
129 struct timespec ts = {0, 200000000};
130 for (int i = 0; i < 25 && !stopped; i++)
132 nanosleep(&ts, NULL);
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 struct timespec ts = {0, 500000000};
157 while (!token.stop_requested())
160 if (token.stop_requested())
166 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
168 std::string monFile(monitorDir + "/traffcounter_r");
169 printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
174 if (++c % FLUSH_TIME == 0)
180 //-----------------------------------------------------------------------------
181 void TraffCounterImpl::process(const RawPacket & rawPacket)
183 if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
185 std::string monFile = monitorDir + "/traffcounter_p";
186 printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
187 touchTimeP = stgTime;
191 std::lock_guard<std::mutex> lock(m_mutex);
193 //printfd(__FILE__, "TraffCounter::Process()\n");
194 //TODO replace find with lower_bound.
196 // Searching a new packet in a tree.
197 pp_iter pi = packets.find(rawPacket);
199 // Packet found - update length and time
200 if (pi != packets.end())
202 pi->second.lenU += rawPacket.GetLen();
203 pi->second.lenD += rawPacket.GetLen();
204 pi->second.updateTime = stgTime;
205 /*printfd(__FILE__, "=============================\n");
206 printfd(__FILE__, "Packet found!\n");
207 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
208 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
209 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
210 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
211 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
212 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
213 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
214 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
215 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
216 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
217 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
218 printfd(__FILE__, "=============================\n");*/
224 // Packet not found - add new packet
226 ed.updateTime = stgTime;
227 ed.flushTime = stgTime;
230 userU is that whose user_ip == packet_ip_src
231 userD is that whose user_ip == packet_ip_dst
234 uint32_t ipU = rawPacket.GetSrcIP();
235 uint32_t ipD = rawPacket.GetDstIP();
237 // Searching users with such IP
238 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
240 ed.userUPresent = true;
243 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
245 ed.userDPresent = true;
248 if (ed.userUPresent ||
251 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
253 ed.lenD = ed.lenU = rawPacket.GetLen();
255 //TODO use result of lower_bound to inserting new record
257 // Adding packet to a tree.
258 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
259 pp_iter newPacket = insertResult.first;
261 // Adding packet reference to an IP index.
262 ip2packets.insert(std::make_pair(ipU, newPacket));
263 ip2packets.insert(std::make_pair(ipD, newPacket));
266 //-----------------------------------------------------------------------------
267 void TraffCounterImpl::FlushAndRemove()
269 std::lock_guard<std::mutex> lock(m_mutex);
271 Packets::size_type oldPacketsSize = packets.size();
272 Index::size_type oldIp2packetsSize = ip2packets.size();
275 pi = packets.begin();
277 ip2packets.erase(ip2packets.begin(), ip2packets.end());
278 while (pi != packets.end())
281 if (stgTime - pi->second.flushTime > FLUSH_TIME)
283 if (pi->second.userUPresent)
285 //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);
288 if (pi->second.dirU < DIR_NUM)
290 #ifdef TRAFF_STAT_WITH_PORTS
291 pi->second.userU->AddTraffStatU(pi->second.dirU,
292 pi->first.GetDstIP(),
293 pi->first.GetDstPort(),
296 pi->second.userU->AddTraffStatU(pi->second.dirU,
297 pi->first.GetDstIP(),
303 pi->second.flushTime = stgTime;
306 if (pi->second.userDPresent)
308 //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);
311 if (pi->second.dirD < DIR_NUM)
313 #ifdef TRAFF_STAT_WITH_PORTS
314 pi->second.userD->AddTraffStatD(pi->second.dirD,
315 pi->first.GetSrcIP(),
316 pi->first.GetSrcPort(),
319 pi->second.userD->AddTraffStatD(pi->second.dirD,
320 pi->first.GetSrcIP(),
326 pi->second.flushTime = stgTime;
330 if (stgTime - pi->second.updateTime < REMOVE_TIME)
332 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
335 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
336 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
341 swap(packets, newPackets);
342 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
344 oldPacketsSize - packets.size(),
346 oldIp2packetsSize - ip2packets.size());
349 //-----------------------------------------------------------------------------
350 void TraffCounterImpl::AddUser(UserImpl * user)
352 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
353 uint32_t uip = user->GetCurrIP();
354 std::pair<ip2p_iter, ip2p_iter> pi;
356 std::lock_guard<std::mutex> lock(m_mutex);
357 // Find all packets with IP belongs to this user
358 pi = ip2packets.equal_range(uip);
360 while (pi.first != pi.second)
362 if (pi.first->second->first.GetSrcIP() == uip)
364 assert((!pi.first->second->second.userUPresent ||
365 pi.first->second->second.userU == user) &&
366 "U user present but it's not current user");
368 pi.first->second->second.lenU = 0;
369 pi.first->second->second.userU = user;
370 pi.first->second->second.userUPresent = true;
373 if (pi.first->second->first.GetDstIP() == uip)
375 assert((!pi.first->second->second.userDPresent ||
376 pi.first->second->second.userD == user) &&
377 "D user present but it's not current user");
379 pi.first->second->second.lenD = 0;
380 pi.first->second->second.userD = user;
381 pi.first->second->second.userDPresent = true;
387 //-----------------------------------------------------------------------------
388 void TraffCounterImpl::DelUser(uint32_t uip)
390 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
391 std::pair<ip2p_iter, ip2p_iter> pi;
393 std::lock_guard<std::mutex> lock(m_mutex);
394 pi = ip2packets.equal_range(uip);
396 while (pi.first != pi.second)
398 if (pi.first->second->first.GetSrcIP() == uip)
400 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
402 #ifdef TRAFF_STAT_WITH_PORTS
403 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
404 pi.first->second->first.GetDstIP(),
405 pi.first->second->first.GetDstPort(),
406 pi.first->second->second.lenU);
408 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
409 pi.first->second->first.GetDstIP(),
410 pi.first->second->second.lenU);
413 pi.first->second->second.userUPresent = false;
416 if (pi.first->second->first.GetDstIP() == uip)
418 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
420 #ifdef TRAFF_STAT_WITH_PORTS
421 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
422 pi.first->second->first.GetSrcIP(),
423 pi.first->second->first.GetSrcPort(),
424 pi.first->second->second.lenD);
426 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
427 pi.first->second->first.GetSrcIP(),
428 pi.first->second->second.lenD);
432 pi.first->second->second.userDPresent = false;
438 ip2packets.erase(pi.first, pi.second);
440 //-----------------------------------------------------------------------------
441 void TraffCounterImpl::SetUserNotifiers(UserImpl * user)
443 // Adding user. Adding notifiers to user.
444 TRF_IP_BEFORE ipBNotifier(*this, user);
445 ipBeforeNotifiers.push_front(ipBNotifier);
446 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
448 TRF_IP_AFTER ipANotifier(*this, user);
449 ipAfterNotifiers.push_front(ipANotifier);
450 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
452 //-----------------------------------------------------------------------------
453 void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user)
455 // Removing user. Removing notifiers from user.
456 std::list<TRF_IP_BEFORE>::iterator bi;
457 std::list<TRF_IP_AFTER>::iterator ai;
459 bi = ipBeforeNotifiers.begin();
460 while (bi != ipBeforeNotifiers.end())
462 if (user->GetLogin() == bi->GetUser()->GetLogin())
464 user->DelCurrIPBeforeNotifier(&(*bi));
465 ipBeforeNotifiers.erase(bi);
471 ai = ipAfterNotifiers.begin();
472 while (ai != ipAfterNotifiers.end())
474 if (user->GetLogin() == ai->GetUser()->GetLogin())
476 user->DelCurrIPAfterNotifier(&(*ai));
477 ipAfterNotifiers.erase(ai);
483 //-----------------------------------------------------------------------------
484 void TraffCounterImpl::DeterminateDir(const RawPacket & packet,
485 int * dirU, // Direction for incoming packet
486 int * dirD) const // Direction for outgoing packet
488 bool addrMatchU = false;
489 bool portMatchU = false;
490 bool addrMatchD = false;
491 bool portMatchD = false;
492 bool foundU = false; // Was rule for U found ?
493 bool foundD = false; // Was rule for D found ?
494 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
496 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
498 std::list<Rule>::const_iterator ln;
501 while (ln != rules.end())
514 portMatchU = (packet.GetProto() == ICMP_RPOTO);
518 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
519 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
523 if (packet.GetProto() == TCP_PROTO)
524 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
528 if (packet.GetProto() == UDP_PROTO)
529 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
533 printfd(__FILE__, "Error! Incorrect rule!\n");
537 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
539 if (!foundU && addrMatchU && portMatchU)
543 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
559 portMatchD = (packet.GetProto() == ICMP_RPOTO);
563 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
564 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
568 if (packet.GetProto() == TCP_PROTO)
569 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
573 if (packet.GetProto() == UDP_PROTO)
574 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
578 printfd(__FILE__, "Error! Incorrect rule!\n");
582 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
584 if (!foundD && addrMatchD && portMatchD)
588 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
593 } //while (ln != rules.end())
601 //-----------------------------------------------------------------------------
602 bool TraffCounterImpl::ReadRules(bool test)
604 //printfd(__FILE__, "TraffCounter::ReadRules()\n");
609 char tp[100]; // protocol
610 char ta[100]; // address
611 char td[100]; // target direction
614 f = fopen(rulesFileName.c_str(), "rt");
618 printfd(__FILE__, "TraffCounterImpl::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
619 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
623 while (fgets(str, 1023, f))
626 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
631 r = sscanf(str,"%99s %99s %99s", tp, ta, td);
634 printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
635 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
643 for (uint8_t i = 0; i < PROTOMAX; i++)
645 if (strcasecmp(tp, protoName[i]) == 0)
649 for (uint32_t i = 0; i < DIR_NUM + 1; i++)
651 if (td == dirName[i])
655 if (rul.dir == 0xff || rul.proto == 0xff)
657 printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
658 WriteServLog("Error in file %s. Line %d.",
659 rulesFileName.c_str(), lineNumber);
664 if (ParseAddress(ta, &rul) != 0)
666 printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
667 WriteServLog("Error in file %s. Error in adress. Line %d.",
668 rulesFileName.c_str(), lineNumber);
673 rules.push_back(rul);
678 // Adding lastest rule: ALL 0.0.0.0/0 NULL
679 rul.dir = DIR_NUM; //NULL
680 rul.ip = 0; //0.0.0.0
687 rules.push_back(rul);
691 //-----------------------------------------------------------------------------
692 int TraffCounterImpl::Reload()
694 std::lock_guard<std::mutex> lock(m_mutex);
698 printfd(__FILE__, "TraffCounterImpl::Reload() - Failed to reload rules.\n");
699 WriteServLog("TraffCounter: Cannot reload rules. Errors found.");
705 printfd(__FILE__, "TraffCounterImpl::Reload() - Reloaded rules successfully.\n");
706 WriteServLog("TraffCounter: Reloaded rules successfully.");
709 //-----------------------------------------------------------------------------
710 bool TraffCounterImpl::ParseAddress(const char * ta, Rule * rule) const
712 char addr[50], mask[20], port1[20], port2[20], ports[40];
714 size_t len = strlen(ta);
717 memset(addr, 0, sizeof(addr));
718 for (i = 0; i < len; i++)
720 if (ta[i] == '/' || ta[i] == ':')
758 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
760 printfd(__FILE__, "TraffCounterImpl::ParseAddress() - No ports specified for this protocol.\n");
761 WriteServLog("No ports specified for this protocol.");
766 ports[i - p] = ta[i];
772 strcpy(ports, "0-65535");
779 if ((sss = strchr(ports, '-')) != NULL)
781 strncpy(port1, ports, int(sss-ports));
782 port1[int(sss - ports)] = 0;
783 strcpy(port2, sss + 1);
787 strcpy(port1, ports);
788 strcpy(port2, ports);
791 // Convert strings to mask, ports and IP
792 uint16_t prt1, prt2, msk;
793 struct in_addr ipaddr;
796 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
800 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
804 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
808 int r = inet_aton(addr, &ipaddr);
812 rule->ip = ipaddr.s_addr;
813 rule->mask = CalcMask(msk);
815 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
817 printfd(__FILE__, "TraffCounterImpl::ParseAddress() - Address does'n match mask.\n");
818 WriteServLog("Address does'n match mask.");
827 //-----------------------------------------------------------------------------
828 uint32_t TraffCounterImpl::CalcMask(uint32_t msk) const
830 if (msk >= 32) return 0xFFffFFff;
831 if (msk == 0) return 0;
832 return htonl(0xFFffFFff << (32 - msk));
834 //---------------------------------------------------------------------------
835 void TraffCounterImpl::FreeRules()
839 //-----------------------------------------------------------------------------
840 void TraffCounterImpl::SetMonitorDir(const std::string & dir)
843 monitoring = !monitorDir.empty();
845 //-----------------------------------------------------------------------------