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 $
33 #include <cstdio> // Functions fopen and similar
35 #include "traffcounter.h"
37 #include "stg_locker.h"
39 #define FLUSH_TIME (10)
40 #define REMOVE_TIME (31)
42 const char protoName[PROTOMAX][8] =
43 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
47 tcp = 0, udp, icmp, tcp_udp, all
50 //-----------------------------------------------------------------------------
51 TRAFFCOUNTER::TRAFFCOUNTER(USERS * u, const TARIFFS *, const string & fn)
52 : WriteServLog(GetStgLogger()),
58 addUserNotifier(*this),
59 delUserNotifier(*this)
61 for (int i = 0; i < DIR_NUM; i++)
62 strprintf(&dirName[i], "DIR%d", i);
64 dirName[DIR_NUM] = "NULL";
66 users->AddNotifierUserAdd(&addUserNotifier);
67 users->AddNotifierUserDel(&delUserNotifier);
69 pthread_mutex_init(&mutex, NULL);
71 //-----------------------------------------------------------------------------
72 TRAFFCOUNTER::~TRAFFCOUNTER()
74 pthread_mutex_destroy(&mutex);
76 //-----------------------------------------------------------------------------
77 int TRAFFCOUNTER::Start()
79 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
86 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
90 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
91 int h = users->OpenSearch();
95 WriteServLog("TRAFFCOUNTER: Cannot get users.");
99 while (users->SearchNext(h, &u) == 0)
103 users->CloseSearch(h);
106 if (pthread_create(&thread, NULL, Run, this))
108 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread!");
113 //-----------------------------------------------------------------------------
114 int TRAFFCOUNTER::Stop()
121 int h = users->OpenSearch();
124 WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
129 while (users->SearchNext(h, &u) == 0)
131 UnSetUserNotifiers(u);
133 users->CloseSearch(h);
135 //5 seconds to thread stops itself
136 for (int i = 0; i < 25 && !stopped; i++)
141 //after 5 seconds waiting thread still running. now kill it
144 printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
145 if (pthread_kill(thread, SIGINT))
149 printfd(__FILE__, "TRAFFCOUNTER killed\n");
151 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
155 //-----------------------------------------------------------------------------
156 void * TRAFFCOUNTER::Run(void * data)
158 TRAFFCOUNTER * tc = static_cast<TRAFFCOUNTER *>(data);
162 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
169 tc->FlushAndRemove();
173 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
175 string monFile(tc->monitorDir + "/traffcounter_r");
176 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
178 TouchFile(monFile.c_str());
181 if (++c % FLUSH_TIME == 0)
182 tc->FlushAndRemove();
188 //-----------------------------------------------------------------------------
189 void TRAFFCOUNTER::Process(const RAW_PACKET & rawPacket)
194 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
196 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
198 static string monFile = monitorDir + "/traffcounter_p";
199 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
201 TouchFile(monFile.c_str());
204 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
206 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
207 //TODO replace find with lower_bound.
209 // Searching a new packet in a tree.
210 pp_iter pi = packets.find(rawPacket);
212 // Packet found - update length and time
213 if (pi != packets.end())
215 pi->second.lenU += rawPacket.GetLen();
216 pi->second.lenD += rawPacket.GetLen();
217 pi->second.updateTime = stgTime;
218 /*printfd(__FILE__, "=============================\n");
219 printfd(__FILE__, "Packet found!\n");
220 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
221 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
222 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
223 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
224 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
225 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
226 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
227 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
228 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
229 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
230 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
231 printfd(__FILE__, "=============================\n");*/
235 PACKET_EXTRA_DATA ed;
237 // Packet not found - add new packet
239 ed.updateTime = stgTime;
240 ed.flushTime = stgTime;
243 userU is that whose user_ip == packet_ip_src
244 userD is that whose user_ip == packet_ip_dst
247 uint32_t ipU = rawPacket.GetSrcIP();
248 uint32_t ipD = rawPacket.GetDstIP();
250 // Searching users with such IP
251 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
253 ed.userUPresent = true;
256 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
258 ed.userDPresent = true;
261 if (ed.userUPresent ||
264 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
266 ed.lenD = ed.lenU = rawPacket.GetLen();
268 //TODO use result of lower_bound to inserting new record
270 // Adding packet to a tree.
271 pair<pp_iter, bool> insertResult = packets.insert(pair<RAW_PACKET,
272 PACKET_EXTRA_DATA>(rawPacket, ed));
273 pp_iter newPacket = insertResult.first;
275 // Adding packet reference to an IP index.
276 ip2packets.insert(pair<uint32_t, pp_iter>(ipU, newPacket));
277 ip2packets.insert(pair<uint32_t, pp_iter>(ipD, newPacket));
280 //-----------------------------------------------------------------------------
281 void TRAFFCOUNTER::FlushAndRemove()
283 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
285 int oldPacketsSize = packets.size();
286 int oldIp2packetsSize = ip2packets.size();
289 pi = packets.begin();
290 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
291 ip2packets.erase(ip2packets.begin(), ip2packets.end());
292 while (pi != packets.end())
295 if (stgTime - pi->second.flushTime > FLUSH_TIME)
297 if (pi->second.userUPresent)
299 //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);
302 if (pi->second.dirU < DIR_NUM)
304 #ifdef TRAFF_STAT_WITH_PORTS
305 pi->second.userU->AddTraffStatU(pi->second.dirU,
306 pi->first.GetDstIP(),
307 pi->first.GetDstPort(),
310 pi->second.userU->AddTraffStatU(pi->second.dirU,
311 pi->first.GetDstIP(),
317 pi->second.flushTime = stgTime;
320 if (pi->second.userDPresent)
322 //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);
325 if (pi->second.dirD < DIR_NUM)
327 #ifdef TRAFF_STAT_WITH_PORTS
328 pi->second.userD->AddTraffStatD(pi->second.dirD,
329 pi->first.GetSrcIP(),
330 pi->first.GetSrcPort(),
333 pi->second.userD->AddTraffStatD(pi->second.dirD,
334 pi->first.GetSrcIP(),
340 pi->second.flushTime = stgTime;
345 if (stgTime - pi->second.updateTime > REMOVE_TIME)
347 // Remove packet and references from ip2packets index
348 //printfd(__FILE__, "+++ Removing +++\n");
349 pair<ip2p_iter, ip2p_iter> be(
350 ip2packets.equal_range(pi->first.GetSrcIP()));
351 while (be.first != be.second)
353 // Have a reference to a packet?
354 if (be.first->second == pi)
356 ip2packets.erase(be.first++);
357 //printfd(__FILE__, "Remove U from ip2packets %s\n", inet_ntostring(pi->first.GetSrcIP()).c_str());
365 //printfd(__FILE__, "-------------------\n");
366 be = ip2packets.equal_range(pi->first.GetDstIP());
367 while (be.first != be.second)
369 // Have a reference to a packet?
370 if (be.first->second == pi)
372 ip2packets.erase(be.first++);
373 //printfd(__FILE__, "Remove D from ip2packets %s\n", inet_ntostring(pi->first.GetDstIP()).c_str());
380 //printfd(__FILE__, "Remove packet\n");
387 if (stgTime - pi->second.updateTime < REMOVE_TIME)
389 pair<pp_iter, bool> res = newPackets.insert(*pi);
392 ip2packets.insert(make_pair(pi->first.GetSrcIP(), res.first));
393 ip2packets.insert(make_pair(pi->first.GetDstIP(), res.first));
398 swap(packets, newPackets);
399 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
401 oldPacketsSize - packets.size(),
403 oldIp2packetsSize - ip2packets.size());
406 //-----------------------------------------------------------------------------
407 void TRAFFCOUNTER::AddUser(user_iter user)
409 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
410 uint32_t uip = user->GetCurrIP();
411 pair<ip2p_iter, ip2p_iter> pi;
413 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
414 // Find all packets with IP belongs to this user
415 pi = ip2packets.equal_range(uip);
417 while (pi.first != pi.second)
419 if (pi.first->second->first.GetSrcIP() == uip)
421 assert((!pi.first->second->second.userUPresent ||
422 pi.first->second->second.userU == user) &&
423 "U user present but it's not current user");
425 pi.first->second->second.lenU = 0;
426 pi.first->second->second.userU = user;
427 pi.first->second->second.userUPresent = true;
430 if (pi.first->second->first.GetDstIP() == uip)
432 assert((!pi.first->second->second.userDPresent ||
433 pi.first->second->second.userD == user) &&
434 "D user present but it's not current user");
436 pi.first->second->second.lenD = 0;
437 pi.first->second->second.userD = user;
438 pi.first->second->second.userDPresent = true;
444 //-----------------------------------------------------------------------------
445 void TRAFFCOUNTER::DelUser(uint32_t uip)
447 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
448 pair<ip2p_iter, ip2p_iter> pi;
450 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
451 pi = ip2packets.equal_range(uip);
453 while (pi.first != pi.second)
455 if (pi.first->second->first.GetSrcIP() == uip)
457 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
459 #ifdef TRAFF_STAT_WITH_PORTS
460 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
461 pi.first->second->first.GetDstIP(),
462 pi.first->second->first.GetDstPort(),
463 pi.first->second->second.lenU);
465 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
466 pi.first->second->first.GetDstIP(),
467 pi.first->second->second.lenU);
470 pi.first->second->second.userUPresent = false;
473 if (pi.first->second->first.GetDstIP() == uip)
475 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
477 #ifdef TRAFF_STAT_WITH_PORTS
478 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
479 pi.first->second->first.GetSrcIP(),
480 pi.first->second->first.GetSrcPort(),
481 pi.first->second->second.lenD);
483 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
484 pi.first->second->first.GetSrcIP(),
485 pi.first->second->second.lenD);
489 pi.first->second->second.userDPresent = false;
495 ip2packets.erase(pi.first, pi.second);
497 //-----------------------------------------------------------------------------
498 void TRAFFCOUNTER::SetUserNotifiers(user_iter user)
500 // Adding user. Adding notifiers to user.
501 TRF_IP_BEFORE ipBNotifier(*this, user);
502 ipBeforeNotifiers.push_front(ipBNotifier);
503 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
505 TRF_IP_AFTER ipANotifier(*this, user);
506 ipAfterNotifiers.push_front(ipANotifier);
507 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
509 //-----------------------------------------------------------------------------
510 void TRAFFCOUNTER::UnSetUserNotifiers(user_iter user)
512 // Removing user. Removing notifiers from user.
513 list<TRF_IP_BEFORE>::iterator bi;
514 list<TRF_IP_AFTER>::iterator ai;
516 bi = ipBeforeNotifiers.begin();
517 while (bi != ipBeforeNotifiers.end())
519 if (user->GetLogin() == bi->GetUser()->GetLogin())
521 user->DelCurrIPBeforeNotifier(&(*bi));
522 ipBeforeNotifiers.erase(bi);
528 ai = ipAfterNotifiers.begin();
529 while (ai != ipAfterNotifiers.end())
531 if (user->GetLogin() == ai->GetUser()->GetLogin())
533 user->DelCurrIPAfterNotifier(&(*ai));
534 ipAfterNotifiers.erase(ai);
540 //-----------------------------------------------------------------------------
541 void TRAFFCOUNTER::DeterminateDir(const RAW_PACKET & packet,
542 int * dirU, // Direction for incoming packet
543 int * dirD) const // Direction for outgoing packet
549 bool foundU = false; // Was rule for U found ?
550 bool foundD = false; // Was rule for D found ?
551 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
553 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
555 list<RULE>::const_iterator ln;
558 while (ln != rules.end())
572 portMatchU = (packet.GetProto() == ICMP_RPOTO);
576 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
577 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
581 if (packet.GetProto() == TCP_PROTO)
582 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
586 if (packet.GetProto() == UDP_PROTO)
587 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
591 printfd(__FILE__, "Error! Incorrect rule!\n");
595 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
597 if (!foundU && addrMatchU && portMatchU)
601 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
602 //PrintRule(ln->rule);
619 portMatchD = (packet.GetProto() == ICMP_RPOTO);
623 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
624 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
628 if (packet.GetProto() == TCP_PROTO)
629 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
633 if (packet.GetProto() == UDP_PROTO)
634 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
638 printfd(__FILE__, "Error! Incorrect rule!\n");
642 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
644 if (!foundD && addrMatchD && portMatchD)
648 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
649 //PrintRule(ln->rule);
654 } //while (ln != rules.end())
664 //-----------------------------------------------------------------------------
665 void TRAFFCOUNTER::SetRulesFile(const string & fn)
669 //-----------------------------------------------------------------------------
670 bool TRAFFCOUNTER::ReadRules(bool test)
672 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
677 char tp[100]; // protocol
678 char ta[100]; // address
679 char td[100]; // target direction
682 f = fopen(rulesFileName.c_str(), "rt");
686 WriteServLog("File %s cannot be oppened.", rulesFileName.c_str());
690 while (fgets(str, 1023, f))
693 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
698 r = sscanf(str,"%s %s %s", tp, ta, td);
701 WriteServLog("Error in file %s. There must be 3 parameters. Line %d.", rulesFileName.c_str(), lineNumber);
709 for (int i = 0; i < PROTOMAX; i++)
711 if (strcasecmp(tp, protoName[i]) == 0)
715 for (int i = 0; i < DIR_NUM + 1; i++)
717 if (td == dirName[i])
721 if (rul.dir == 0xff || rul.proto == 0xff)
723 WriteServLog("Error in file %s. Line %d.",
724 rulesFileName.c_str(), lineNumber);
729 if (ParseAddress(ta, &rul) != 0)
731 WriteServLog("Error in file %s. Error in adress. Line %d.",
732 rulesFileName.c_str(), lineNumber);
737 rules.push_back(rul);
743 // Adding lastest rule: ALL 0.0.0.0/0 NULL
744 rul.dir = DIR_NUM; //NULL
745 rul.ip = 0; //0.0.0.0
752 rules.push_back(rul);
758 //-----------------------------------------------------------------------------
759 int TRAFFCOUNTER::Reload()
761 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
765 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
771 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
774 //-----------------------------------------------------------------------------
775 bool TRAFFCOUNTER::ParseAddress(const char * ta, RULE * rule) const
777 char addr[50], mask[20], port1[20], port2[20], ports[40];
779 int len = strlen(ta);
782 memset(addr, 0, sizeof(addr));
783 for (i = 0; i < len; i++)
785 if (ta[i] == '/' || ta[i] == ':')
823 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
825 WriteServLog("No ports specified for this protocol.");
830 ports[i - p] = ta[i];
836 strcpy(ports, "0-65535");
843 if ((sss = strchr(ports, '-')) != NULL)
845 strncpy(port1, ports, int(sss-ports));
846 port1[int(sss - ports)] = 0;
847 strcpy(port2, sss + 1);
851 strcpy(port1, ports);
852 strcpy(port2, ports);
855 // Convert strings to mask, ports and IP
860 msk = strtol(mask, &res, 10);
864 prt1 = strtol(port1, &res, 10);
868 prt2 = strtol(port2, &res, 10);
872 int r = inet_aton(addr, (struct in_addr*)&ip);
877 rule->mask = CalcMask(msk);
879 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
881 if ((ip & rule->mask) != ip)
883 WriteServLog("Address does'n match mask.");
892 //-----------------------------------------------------------------------------
893 uint32_t TRAFFCOUNTER::CalcMask(uint32_t msk) const
895 if (msk >= 32) return 0xFFffFFff;
896 if (msk == 0) return 0;
897 return htonl(0xFFffFFff << (32 - msk));
899 //---------------------------------------------------------------------------
900 void TRAFFCOUNTER::FreeRules()
904 //-----------------------------------------------------------------------------
905 void TRAFFCOUNTER::PrintRule(RULE rule) const
907 printf("%15s ", inet_ntostring(rule.ip).c_str());
908 printf("mask=%08X ", rule.mask);
909 printf("port1=%5d ", rule.port1);
910 printf("port2=%5d ", rule.port2);
929 printf("dir=%d \n", rule.dir);
932 //-----------------------------------------------------------------------------
933 void TRAFFCOUNTER::SetMonitorDir(const string & monitorDir)
935 TRAFFCOUNTER::monitorDir = monitorDir;
936 monitoring = (monitorDir != "");
938 //-----------------------------------------------------------------------------