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();
103 assert(h && "USERS::OpenSearch is always correct");
106 while (users->SearchNext(h, &u) == 0)
110 users->CloseSearch(h);
113 if (pthread_create(&thread, NULL, Run, this))
115 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
116 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
121 //-----------------------------------------------------------------------------
122 int TRAFFCOUNTER_IMPL::Stop()
129 int h = users->OpenSearch();
130 assert(h && "USERS::OpenSearch is always correct");
133 while (users->SearchNext(h, &u) == 0)
135 UnSetUserNotifiers(u);
137 users->CloseSearch(h);
139 //5 seconds to thread stops itself
140 struct timespec ts = {0, 200000000};
141 for (int i = 0; i < 25 && !stopped; i++)
143 nanosleep(&ts, NULL);
146 //after 5 seconds waiting thread still running. now kill it
149 printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
150 if (pthread_kill(thread, SIGINT))
154 printfd(__FILE__, "TRAFFCOUNTER killed\n");
156 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
160 //-----------------------------------------------------------------------------
161 void * TRAFFCOUNTER_IMPL::Run(void * data)
163 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
167 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
168 struct timespec ts = {0, 500000000};
174 tc->FlushAndRemove();
178 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
180 std::string monFile(tc->monitorDir + "/traffcounter_r");
181 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
183 TouchFile(monFile.c_str());
186 if (++c % FLUSH_TIME == 0)
187 tc->FlushAndRemove();
193 //-----------------------------------------------------------------------------
194 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
199 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
201 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
203 static std::string monFile = monitorDir + "/traffcounter_p";
204 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
206 TouchFile(monFile.c_str());
209 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
211 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
212 //TODO replace find with lower_bound.
214 // Searching a new packet in a tree.
215 pp_iter pi = packets.find(rawPacket);
217 // Packet found - update length and time
218 if (pi != packets.end())
220 pi->second.lenU += rawPacket.GetLen();
221 pi->second.lenD += rawPacket.GetLen();
222 pi->second.updateTime = stgTime;
223 /*printfd(__FILE__, "=============================\n");
224 printfd(__FILE__, "Packet found!\n");
225 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
226 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
227 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
228 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
229 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
230 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
231 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
232 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
233 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
234 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
235 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
236 printfd(__FILE__, "=============================\n");*/
240 PACKET_EXTRA_DATA ed;
242 // Packet not found - add new packet
244 ed.updateTime = stgTime;
245 ed.flushTime = stgTime;
248 userU is that whose user_ip == packet_ip_src
249 userD is that whose user_ip == packet_ip_dst
252 uint32_t ipU = rawPacket.GetSrcIP();
253 uint32_t ipD = rawPacket.GetDstIP();
255 // Searching users with such IP
256 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
258 ed.userUPresent = true;
261 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
263 ed.userDPresent = true;
266 if (ed.userUPresent ||
269 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
271 ed.lenD = ed.lenU = rawPacket.GetLen();
273 //TODO use result of lower_bound to inserting new record
275 // Adding packet to a tree.
276 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
277 pp_iter newPacket = insertResult.first;
279 // Adding packet reference to an IP index.
280 ip2packets.insert(std::make_pair(ipU, newPacket));
281 ip2packets.insert(std::make_pair(ipD, newPacket));
284 //-----------------------------------------------------------------------------
285 void TRAFFCOUNTER_IMPL::FlushAndRemove()
287 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
289 int oldPacketsSize = packets.size();
290 int oldIp2packetsSize = ip2packets.size();
293 pi = packets.begin();
294 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
295 ip2packets.erase(ip2packets.begin(), ip2packets.end());
296 while (pi != packets.end())
299 if (stgTime - pi->second.flushTime > FLUSH_TIME)
301 if (pi->second.userUPresent)
303 //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);
306 if (pi->second.dirU < DIR_NUM)
308 #ifdef TRAFF_STAT_WITH_PORTS
309 pi->second.userU->AddTraffStatU(pi->second.dirU,
310 pi->first.GetDstIP(),
311 pi->first.GetDstPort(),
314 pi->second.userU->AddTraffStatU(pi->second.dirU,
315 pi->first.GetDstIP(),
321 pi->second.flushTime = stgTime;
324 if (pi->second.userDPresent)
326 //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);
329 if (pi->second.dirD < DIR_NUM)
331 #ifdef TRAFF_STAT_WITH_PORTS
332 pi->second.userD->AddTraffStatD(pi->second.dirD,
333 pi->first.GetSrcIP(),
334 pi->first.GetSrcPort(),
337 pi->second.userD->AddTraffStatD(pi->second.dirD,
338 pi->first.GetSrcIP(),
344 pi->second.flushTime = stgTime;
348 if (stgTime - pi->second.updateTime < REMOVE_TIME)
350 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
353 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
354 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
359 swap(packets, newPackets);
360 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
362 oldPacketsSize - packets.size(),
364 oldIp2packetsSize - ip2packets.size());
367 //-----------------------------------------------------------------------------
368 void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user)
370 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
371 uint32_t uip = user->GetCurrIP();
372 std::pair<ip2p_iter, ip2p_iter> pi;
374 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
375 // Find all packets with IP belongs to this user
376 pi = ip2packets.equal_range(uip);
378 while (pi.first != pi.second)
380 if (pi.first->second->first.GetSrcIP() == uip)
382 assert((!pi.first->second->second.userUPresent ||
383 pi.first->second->second.userU == user) &&
384 "U user present but it's not current user");
386 pi.first->second->second.lenU = 0;
387 pi.first->second->second.userU = user;
388 pi.first->second->second.userUPresent = true;
391 if (pi.first->second->first.GetDstIP() == uip)
393 assert((!pi.first->second->second.userDPresent ||
394 pi.first->second->second.userD == user) &&
395 "D user present but it's not current user");
397 pi.first->second->second.lenD = 0;
398 pi.first->second->second.userD = user;
399 pi.first->second->second.userDPresent = true;
405 //-----------------------------------------------------------------------------
406 void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
408 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
409 std::pair<ip2p_iter, ip2p_iter> pi;
411 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
412 pi = ip2packets.equal_range(uip);
414 while (pi.first != pi.second)
416 if (pi.first->second->first.GetSrcIP() == uip)
418 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
420 #ifdef TRAFF_STAT_WITH_PORTS
421 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
422 pi.first->second->first.GetDstIP(),
423 pi.first->second->first.GetDstPort(),
424 pi.first->second->second.lenU);
426 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
427 pi.first->second->first.GetDstIP(),
428 pi.first->second->second.lenU);
431 pi.first->second->second.userUPresent = false;
434 if (pi.first->second->first.GetDstIP() == uip)
436 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
438 #ifdef TRAFF_STAT_WITH_PORTS
439 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
440 pi.first->second->first.GetSrcIP(),
441 pi.first->second->first.GetSrcPort(),
442 pi.first->second->second.lenD);
444 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
445 pi.first->second->first.GetSrcIP(),
446 pi.first->second->second.lenD);
450 pi.first->second->second.userDPresent = false;
456 ip2packets.erase(pi.first, pi.second);
458 //-----------------------------------------------------------------------------
459 void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user)
461 // Adding user. Adding notifiers to user.
462 TRF_IP_BEFORE ipBNotifier(*this, user);
463 ipBeforeNotifiers.push_front(ipBNotifier);
464 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
466 TRF_IP_AFTER ipANotifier(*this, user);
467 ipAfterNotifiers.push_front(ipANotifier);
468 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
470 //-----------------------------------------------------------------------------
471 void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
473 // Removing user. Removing notifiers from user.
474 std::list<TRF_IP_BEFORE>::iterator bi;
475 std::list<TRF_IP_AFTER>::iterator ai;
477 bi = ipBeforeNotifiers.begin();
478 while (bi != ipBeforeNotifiers.end())
480 if (user->GetLogin() == bi->GetUser()->GetLogin())
482 user->DelCurrIPBeforeNotifier(&(*bi));
483 ipBeforeNotifiers.erase(bi);
489 ai = ipAfterNotifiers.begin();
490 while (ai != ipAfterNotifiers.end())
492 if (user->GetLogin() == ai->GetUser()->GetLogin())
494 user->DelCurrIPAfterNotifier(&(*ai));
495 ipAfterNotifiers.erase(ai);
501 //-----------------------------------------------------------------------------
502 void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
503 int * dirU, // Direction for incoming packet
504 int * dirD) const // Direction for outgoing packet
510 bool foundU = false; // Was rule for U found ?
511 bool foundD = false; // Was rule for D found ?
512 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
514 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
516 std::list<RULE>::const_iterator ln;
519 while (ln != rules.end())
533 portMatchU = (packet.GetProto() == ICMP_RPOTO);
537 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
538 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
542 if (packet.GetProto() == TCP_PROTO)
543 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
547 if (packet.GetProto() == UDP_PROTO)
548 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
552 printfd(__FILE__, "Error! Incorrect rule!\n");
556 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
558 if (!foundU && addrMatchU && portMatchU)
562 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
563 //PrintRule(ln->rule);
580 portMatchD = (packet.GetProto() == ICMP_RPOTO);
584 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
585 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
589 if (packet.GetProto() == TCP_PROTO)
590 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
594 if (packet.GetProto() == UDP_PROTO)
595 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
599 printfd(__FILE__, "Error! Incorrect rule!\n");
603 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
605 if (!foundD && addrMatchD && portMatchD)
609 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
610 //PrintRule(ln->rule);
615 } //while (ln != rules.end())
625 //-----------------------------------------------------------------------------
626 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
630 //-----------------------------------------------------------------------------
631 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
633 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
638 char tp[100]; // protocol
639 char ta[100]; // address
640 char td[100]; // target direction
643 f = fopen(rulesFileName.c_str(), "rt");
647 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
648 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
652 while (fgets(str, 1023, f))
655 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
660 r = sscanf(str,"%s %s %s", tp, ta, td);
663 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
664 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
672 for (int i = 0; i < PROTOMAX; i++)
674 if (strcasecmp(tp, protoName[i]) == 0)
678 for (int i = 0; i < DIR_NUM + 1; i++)
680 if (td == dirName[i])
684 if (rul.dir == 0xff || rul.proto == 0xff)
686 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
687 WriteServLog("Error in file %s. Line %d.",
688 rulesFileName.c_str(), lineNumber);
693 if (ParseAddress(ta, &rul) != 0)
695 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
696 WriteServLog("Error in file %s. Error in adress. Line %d.",
697 rulesFileName.c_str(), lineNumber);
702 rules.push_back(rul);
708 // Adding lastest rule: ALL 0.0.0.0/0 NULL
709 rul.dir = DIR_NUM; //NULL
710 rul.ip = 0; //0.0.0.0
717 rules.push_back(rul);
723 //-----------------------------------------------------------------------------
724 int TRAFFCOUNTER_IMPL::Reload()
726 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
730 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
731 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
737 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reload rules successfull.\n");
738 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
741 //-----------------------------------------------------------------------------
742 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
744 char addr[50], mask[20], port1[20], port2[20], ports[40];
746 int len = strlen(ta);
749 memset(addr, 0, sizeof(addr));
750 for (i = 0; i < len; i++)
752 if (ta[i] == '/' || ta[i] == ':')
790 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
792 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
793 WriteServLog("No ports specified for this protocol.");
798 ports[i - p] = ta[i];
804 strcpy(ports, "0-65535");
811 if ((sss = strchr(ports, '-')) != NULL)
813 strncpy(port1, ports, int(sss-ports));
814 port1[int(sss - ports)] = 0;
815 strcpy(port2, sss + 1);
819 strcpy(port1, ports);
820 strcpy(port2, ports);
823 // Convert strings to mask, ports and IP
828 msk = strtol(mask, &res, 10);
832 prt1 = strtol(port1, &res, 10);
836 prt2 = strtol(port2, &res, 10);
840 int r = inet_aton(addr, (struct in_addr*)&ip);
845 rule->mask = CalcMask(msk);
847 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
849 if ((ip & rule->mask) != ip)
851 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
852 WriteServLog("Address does'n match mask.");
861 //-----------------------------------------------------------------------------
862 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
864 if (msk >= 32) return 0xFFffFFff;
865 if (msk == 0) return 0;
866 return htonl(0xFFffFFff << (32 - msk));
868 //---------------------------------------------------------------------------
869 void TRAFFCOUNTER_IMPL::FreeRules()
873 //-----------------------------------------------------------------------------
874 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
876 printf("%15s ", inet_ntostring(rule.ip).c_str());
877 printf("mask=%08X ", rule.mask);
878 printf("port1=%5d ", rule.port1);
879 printf("port2=%5d ", rule.port2);
898 printf("dir=%d \n", rule.dir);
901 //-----------------------------------------------------------------------------
902 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
904 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
905 monitoring = (monitorDir != "");
907 //-----------------------------------------------------------------------------