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 "traffcounter_impl.h"
45 #include "stg_timer.h"
46 #include "users_impl.h"
48 #define FLUSH_TIME (10)
49 #define REMOVE_TIME (31)
51 const char protoName[PROTOMAX][8] =
52 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
56 tcp = 0, udp, icmp, tcp_udp, all
59 //-----------------------------------------------------------------------------
60 TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
62 WriteServLog(GetStgLogger()),
68 addUserNotifier(*this),
69 delUserNotifier(*this)
71 for (int i = 0; i < DIR_NUM; i++)
72 strprintf(&dirName[i], "DIR%d", i);
74 dirName[DIR_NUM] = "NULL";
76 users->AddNotifierUserAdd(&addUserNotifier);
77 users->AddNotifierUserDel(&delUserNotifier);
79 pthread_mutex_init(&mutex, NULL);
81 //-----------------------------------------------------------------------------
82 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
84 pthread_mutex_destroy(&mutex);
86 //-----------------------------------------------------------------------------
87 int TRAFFCOUNTER_IMPL::Start()
89 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
96 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
97 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
101 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
102 int h = users->OpenSearch();
106 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot get users\n");
107 WriteServLog("TRAFFCOUNTER: Cannot get users.");
111 while (users->SearchNext(h, &u) == 0)
115 users->CloseSearch(h);
118 if (pthread_create(&thread, NULL, Run, this))
120 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
121 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
126 //-----------------------------------------------------------------------------
127 int TRAFFCOUNTER_IMPL::Stop()
134 int h = users->OpenSearch();
137 WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
142 while (users->SearchNext(h, &u) == 0)
144 UnSetUserNotifiers(u);
146 users->CloseSearch(h);
148 //5 seconds to thread stops itself
149 struct timespec ts = {0, 200000000};
150 for (int i = 0; i < 25 && !stopped; i++)
152 nanosleep(&ts, NULL);
155 //after 5 seconds waiting thread still running. now kill it
158 printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
159 if (pthread_kill(thread, SIGINT))
163 printfd(__FILE__, "TRAFFCOUNTER killed\n");
165 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
169 //-----------------------------------------------------------------------------
170 void * TRAFFCOUNTER_IMPL::Run(void * data)
172 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
176 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
177 struct timespec ts = {0, 500000000};
183 tc->FlushAndRemove();
187 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
189 std::string monFile(tc->monitorDir + "/traffcounter_r");
190 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
192 TouchFile(monFile.c_str());
195 if (++c % FLUSH_TIME == 0)
196 tc->FlushAndRemove();
202 //-----------------------------------------------------------------------------
203 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
208 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
210 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
212 static std::string monFile = monitorDir + "/traffcounter_p";
213 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
215 TouchFile(monFile.c_str());
218 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
220 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
221 //TODO replace find with lower_bound.
223 // Searching a new packet in a tree.
224 pp_iter pi = packets.find(rawPacket);
226 // Packet found - update length and time
227 if (pi != packets.end())
229 pi->second.lenU += rawPacket.GetLen();
230 pi->second.lenD += rawPacket.GetLen();
231 pi->second.updateTime = stgTime;
232 /*printfd(__FILE__, "=============================\n");
233 printfd(__FILE__, "Packet found!\n");
234 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
235 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
236 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
237 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
238 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
239 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
240 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
241 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
242 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
243 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
244 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
245 printfd(__FILE__, "=============================\n");*/
249 PACKET_EXTRA_DATA ed;
251 // Packet not found - add new packet
253 ed.updateTime = stgTime;
254 ed.flushTime = stgTime;
257 userU is that whose user_ip == packet_ip_src
258 userD is that whose user_ip == packet_ip_dst
261 uint32_t ipU = rawPacket.GetSrcIP();
262 uint32_t ipD = rawPacket.GetDstIP();
264 // Searching users with such IP
265 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
267 ed.userUPresent = true;
270 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
272 ed.userDPresent = true;
275 if (ed.userUPresent ||
278 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
280 ed.lenD = ed.lenU = rawPacket.GetLen();
282 //TODO use result of lower_bound to inserting new record
284 // Adding packet to a tree.
285 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
286 pp_iter newPacket = insertResult.first;
288 // Adding packet reference to an IP index.
289 ip2packets.insert(std::make_pair(ipU, newPacket));
290 ip2packets.insert(std::make_pair(ipD, newPacket));
293 //-----------------------------------------------------------------------------
294 void TRAFFCOUNTER_IMPL::FlushAndRemove()
296 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
298 int oldPacketsSize = packets.size();
299 int oldIp2packetsSize = ip2packets.size();
302 pi = packets.begin();
303 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
304 ip2packets.erase(ip2packets.begin(), ip2packets.end());
305 while (pi != packets.end())
308 if (stgTime - pi->second.flushTime > FLUSH_TIME)
310 if (pi->second.userUPresent)
312 //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);
315 if (pi->second.dirU < DIR_NUM)
317 #ifdef TRAFF_STAT_WITH_PORTS
318 pi->second.userU->AddTraffStatU(pi->second.dirU,
319 pi->first.GetDstIP(),
320 pi->first.GetDstPort(),
323 pi->second.userU->AddTraffStatU(pi->second.dirU,
324 pi->first.GetDstIP(),
330 pi->second.flushTime = stgTime;
333 if (pi->second.userDPresent)
335 //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);
338 if (pi->second.dirD < DIR_NUM)
340 #ifdef TRAFF_STAT_WITH_PORTS
341 pi->second.userD->AddTraffStatD(pi->second.dirD,
342 pi->first.GetSrcIP(),
343 pi->first.GetSrcPort(),
346 pi->second.userD->AddTraffStatD(pi->second.dirD,
347 pi->first.GetSrcIP(),
353 pi->second.flushTime = stgTime;
357 if (stgTime - pi->second.updateTime < REMOVE_TIME)
359 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
362 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
363 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
368 swap(packets, newPackets);
369 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
371 oldPacketsSize - packets.size(),
373 oldIp2packetsSize - ip2packets.size());
376 //-----------------------------------------------------------------------------
377 void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user)
379 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
380 uint32_t uip = user->GetCurrIP();
381 std::pair<ip2p_iter, ip2p_iter> pi;
383 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
384 // Find all packets with IP belongs to this user
385 pi = ip2packets.equal_range(uip);
387 while (pi.first != pi.second)
389 if (pi.first->second->first.GetSrcIP() == uip)
391 assert((!pi.first->second->second.userUPresent ||
392 pi.first->second->second.userU == user) &&
393 "U user present but it's not current user");
395 pi.first->second->second.lenU = 0;
396 pi.first->second->second.userU = user;
397 pi.first->second->second.userUPresent = true;
400 if (pi.first->second->first.GetDstIP() == uip)
402 assert((!pi.first->second->second.userDPresent ||
403 pi.first->second->second.userD == user) &&
404 "D user present but it's not current user");
406 pi.first->second->second.lenD = 0;
407 pi.first->second->second.userD = user;
408 pi.first->second->second.userDPresent = true;
414 //-----------------------------------------------------------------------------
415 void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
417 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
418 std::pair<ip2p_iter, ip2p_iter> pi;
420 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
421 pi = ip2packets.equal_range(uip);
423 while (pi.first != pi.second)
425 if (pi.first->second->first.GetSrcIP() == uip)
427 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
429 #ifdef TRAFF_STAT_WITH_PORTS
430 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
431 pi.first->second->first.GetDstIP(),
432 pi.first->second->first.GetDstPort(),
433 pi.first->second->second.lenU);
435 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
436 pi.first->second->first.GetDstIP(),
437 pi.first->second->second.lenU);
440 pi.first->second->second.userUPresent = false;
443 if (pi.first->second->first.GetDstIP() == uip)
445 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
447 #ifdef TRAFF_STAT_WITH_PORTS
448 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
449 pi.first->second->first.GetSrcIP(),
450 pi.first->second->first.GetSrcPort(),
451 pi.first->second->second.lenD);
453 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
454 pi.first->second->first.GetSrcIP(),
455 pi.first->second->second.lenD);
459 pi.first->second->second.userDPresent = false;
465 ip2packets.erase(pi.first, pi.second);
467 //-----------------------------------------------------------------------------
468 void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user)
470 // Adding user. Adding notifiers to user.
471 TRF_IP_BEFORE ipBNotifier(*this, user);
472 ipBeforeNotifiers.push_front(ipBNotifier);
473 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
475 TRF_IP_AFTER ipANotifier(*this, user);
476 ipAfterNotifiers.push_front(ipANotifier);
477 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
479 //-----------------------------------------------------------------------------
480 void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
482 // Removing user. Removing notifiers from user.
483 std::list<TRF_IP_BEFORE>::iterator bi;
484 std::list<TRF_IP_AFTER>::iterator ai;
486 bi = ipBeforeNotifiers.begin();
487 while (bi != ipBeforeNotifiers.end())
489 if (user->GetLogin() == bi->GetUser()->GetLogin())
491 user->DelCurrIPBeforeNotifier(&(*bi));
492 ipBeforeNotifiers.erase(bi);
498 ai = ipAfterNotifiers.begin();
499 while (ai != ipAfterNotifiers.end())
501 if (user->GetLogin() == ai->GetUser()->GetLogin())
503 user->DelCurrIPAfterNotifier(&(*ai));
504 ipAfterNotifiers.erase(ai);
510 //-----------------------------------------------------------------------------
511 void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
512 int * dirU, // Direction for incoming packet
513 int * dirD) const // Direction for outgoing packet
519 bool foundU = false; // Was rule for U found ?
520 bool foundD = false; // Was rule for D found ?
521 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
523 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
525 std::list<RULE>::const_iterator ln;
528 while (ln != rules.end())
542 portMatchU = (packet.GetProto() == ICMP_RPOTO);
546 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
547 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
551 if (packet.GetProto() == TCP_PROTO)
552 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
556 if (packet.GetProto() == UDP_PROTO)
557 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
561 printfd(__FILE__, "Error! Incorrect rule!\n");
565 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
567 if (!foundU && addrMatchU && portMatchU)
571 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
572 //PrintRule(ln->rule);
589 portMatchD = (packet.GetProto() == ICMP_RPOTO);
593 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
594 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
598 if (packet.GetProto() == TCP_PROTO)
599 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
603 if (packet.GetProto() == UDP_PROTO)
604 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
608 printfd(__FILE__, "Error! Incorrect rule!\n");
612 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
614 if (!foundD && addrMatchD && portMatchD)
618 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
619 //PrintRule(ln->rule);
624 } //while (ln != rules.end())
634 //-----------------------------------------------------------------------------
635 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
639 //-----------------------------------------------------------------------------
640 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
642 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
647 char tp[100]; // protocol
648 char ta[100]; // address
649 char td[100]; // target direction
652 f = fopen(rulesFileName.c_str(), "rt");
656 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
657 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
661 while (fgets(str, 1023, f))
664 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
669 r = sscanf(str,"%s %s %s", tp, ta, td);
672 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
673 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
681 for (int i = 0; i < PROTOMAX; i++)
683 if (strcasecmp(tp, protoName[i]) == 0)
687 for (int i = 0; i < DIR_NUM + 1; i++)
689 if (td == dirName[i])
693 if (rul.dir == 0xff || rul.proto == 0xff)
695 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
696 WriteServLog("Error in file %s. Line %d.",
697 rulesFileName.c_str(), lineNumber);
702 if (ParseAddress(ta, &rul) != 0)
704 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
705 WriteServLog("Error in file %s. Error in adress. Line %d.",
706 rulesFileName.c_str(), lineNumber);
711 rules.push_back(rul);
717 // Adding lastest rule: ALL 0.0.0.0/0 NULL
718 rul.dir = DIR_NUM; //NULL
719 rul.ip = 0; //0.0.0.0
726 rules.push_back(rul);
732 //-----------------------------------------------------------------------------
733 int TRAFFCOUNTER_IMPL::Reload()
735 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
739 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
740 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
746 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reload rules successfull.\n");
747 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
750 //-----------------------------------------------------------------------------
751 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
753 char addr[50], mask[20], port1[20], port2[20], ports[40];
755 int len = strlen(ta);
758 memset(addr, 0, sizeof(addr));
759 for (i = 0; i < len; i++)
761 if (ta[i] == '/' || ta[i] == ':')
799 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
801 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
802 WriteServLog("No ports specified for this protocol.");
807 ports[i - p] = ta[i];
813 strcpy(ports, "0-65535");
820 if ((sss = strchr(ports, '-')) != NULL)
822 strncpy(port1, ports, int(sss-ports));
823 port1[int(sss - ports)] = 0;
824 strcpy(port2, sss + 1);
828 strcpy(port1, ports);
829 strcpy(port2, ports);
832 // Convert strings to mask, ports and IP
837 msk = strtol(mask, &res, 10);
841 prt1 = strtol(port1, &res, 10);
845 prt2 = strtol(port2, &res, 10);
849 int r = inet_aton(addr, (struct in_addr*)&ip);
854 rule->mask = CalcMask(msk);
856 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
858 if ((ip & rule->mask) != ip)
860 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
861 WriteServLog("Address does'n match mask.");
870 //-----------------------------------------------------------------------------
871 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
873 if (msk >= 32) return 0xFFffFFff;
874 if (msk == 0) return 0;
875 return htonl(0xFFffFFff << (32 - msk));
877 //---------------------------------------------------------------------------
878 void TRAFFCOUNTER_IMPL::FreeRules()
882 //-----------------------------------------------------------------------------
883 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
885 printf("%15s ", inet_ntostring(rule.ip).c_str());
886 printf("mask=%08X ", rule.mask);
887 printf("port1=%5d ", rule.port1);
888 printf("port2=%5d ", rule.port2);
907 printf("dir=%d \n", rule.dir);
910 //-----------------------------------------------------------------------------
911 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
913 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
914 monitoring = (monitorDir != "");
916 //-----------------------------------------------------------------------------