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/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
38 #include <cstdio> // Functions fopen and similar
40 #include "traffcounter.h"
42 #include "stg_locker.h"
43 #include "stg_timer.h"
45 #define FLUSH_TIME (10)
46 #define REMOVE_TIME (31)
48 const char protoName[PROTOMAX][8] =
49 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
53 tcp = 0, udp, icmp, tcp_udp, all
56 //-----------------------------------------------------------------------------
57 TRAFFCOUNTER::TRAFFCOUNTER(USERS * u, const TARIFFS *, const std::string & fn)
58 : WriteServLog(GetStgLogger()),
64 addUserNotifier(*this),
65 delUserNotifier(*this)
67 for (int i = 0; i < DIR_NUM; i++)
68 strprintf(&dirName[i], "DIR%d", i);
70 dirName[DIR_NUM] = "NULL";
72 users->AddNotifierUserAdd(&addUserNotifier);
73 users->AddNotifierUserDel(&delUserNotifier);
75 pthread_mutex_init(&mutex, NULL);
77 //-----------------------------------------------------------------------------
78 TRAFFCOUNTER::~TRAFFCOUNTER()
80 pthread_mutex_destroy(&mutex);
82 //-----------------------------------------------------------------------------
83 int TRAFFCOUNTER::Start()
85 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
92 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
96 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
97 int h = users->OpenSearch();
101 WriteServLog("TRAFFCOUNTER: Cannot get users.");
105 while (users->SearchNext(h, &u) == 0)
109 users->CloseSearch(h);
112 if (pthread_create(&thread, NULL, Run, this))
114 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread!");
119 //-----------------------------------------------------------------------------
120 int TRAFFCOUNTER::Stop()
127 int h = users->OpenSearch();
130 WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
135 while (users->SearchNext(h, &u) == 0)
137 UnSetUserNotifiers(u);
139 users->CloseSearch(h);
141 //5 seconds to thread stops itself
142 for (int i = 0; i < 25 && !stopped; i++)
147 //after 5 seconds waiting thread still running. now kill it
150 printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
151 if (pthread_kill(thread, SIGINT))
155 printfd(__FILE__, "TRAFFCOUNTER killed\n");
157 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
161 //-----------------------------------------------------------------------------
162 void * TRAFFCOUNTER::Run(void * data)
164 TRAFFCOUNTER * tc = static_cast<TRAFFCOUNTER *>(data);
168 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
175 tc->FlushAndRemove();
179 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
181 std::string monFile(tc->monitorDir + "/traffcounter_r");
182 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
184 TouchFile(monFile.c_str());
187 if (++c % FLUSH_TIME == 0)
188 tc->FlushAndRemove();
194 //-----------------------------------------------------------------------------
195 void TRAFFCOUNTER::Process(const RAW_PACKET & rawPacket)
200 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
202 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
204 static std::string monFile = monitorDir + "/traffcounter_p";
205 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
207 TouchFile(monFile.c_str());
210 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
212 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
213 //TODO replace find with lower_bound.
215 // Searching a new packet in a tree.
216 pp_iter pi = packets.find(rawPacket);
218 // Packet found - update length and time
219 if (pi != packets.end())
221 pi->second.lenU += rawPacket.GetLen();
222 pi->second.lenD += rawPacket.GetLen();
223 pi->second.updateTime = stgTime;
224 /*printfd(__FILE__, "=============================\n");
225 printfd(__FILE__, "Packet found!\n");
226 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
227 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
228 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
229 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
230 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
231 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
232 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
233 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
234 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
235 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
236 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
237 printfd(__FILE__, "=============================\n");*/
241 PACKET_EXTRA_DATA ed;
243 // Packet not found - add new packet
245 ed.updateTime = stgTime;
246 ed.flushTime = stgTime;
249 userU is that whose user_ip == packet_ip_src
250 userD is that whose user_ip == packet_ip_dst
253 uint32_t ipU = rawPacket.GetSrcIP();
254 uint32_t ipD = rawPacket.GetDstIP();
256 // Searching users with such IP
257 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
259 ed.userUPresent = true;
262 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
264 ed.userDPresent = true;
267 if (ed.userUPresent ||
270 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
272 ed.lenD = ed.lenU = rawPacket.GetLen();
274 //TODO use result of lower_bound to inserting new record
276 // Adding packet to a tree.
277 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
278 pp_iter newPacket = insertResult.first;
280 // Adding packet reference to an IP index.
281 ip2packets.insert(std::make_pair(ipU, newPacket));
282 ip2packets.insert(std::make_pair(ipD, newPacket));
285 //-----------------------------------------------------------------------------
286 void TRAFFCOUNTER::FlushAndRemove()
288 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
290 int oldPacketsSize = packets.size();
291 int oldIp2packetsSize = ip2packets.size();
294 pi = packets.begin();
295 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
296 ip2packets.erase(ip2packets.begin(), ip2packets.end());
297 while (pi != packets.end())
300 if (stgTime - pi->second.flushTime > FLUSH_TIME)
302 if (pi->second.userUPresent)
304 //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);
307 if (pi->second.dirU < DIR_NUM)
309 #ifdef TRAFF_STAT_WITH_PORTS
310 pi->second.userU->AddTraffStatU(pi->second.dirU,
311 pi->first.GetDstIP(),
312 pi->first.GetDstPort(),
315 pi->second.userU->AddTraffStatU(pi->second.dirU,
316 pi->first.GetDstIP(),
322 pi->second.flushTime = stgTime;
325 if (pi->second.userDPresent)
327 //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);
330 if (pi->second.dirD < DIR_NUM)
332 #ifdef TRAFF_STAT_WITH_PORTS
333 pi->second.userD->AddTraffStatD(pi->second.dirD,
334 pi->first.GetSrcIP(),
335 pi->first.GetSrcPort(),
338 pi->second.userD->AddTraffStatD(pi->second.dirD,
339 pi->first.GetSrcIP(),
345 pi->second.flushTime = stgTime;
350 if (stgTime - pi->second.updateTime > REMOVE_TIME)
352 // Remove packet and references from ip2packets index
353 //printfd(__FILE__, "+++ Removing +++\n");
354 pair<ip2p_iter, ip2p_iter> be(
355 ip2packets.equal_range(pi->first.GetSrcIP()));
356 while (be.first != be.second)
358 // Have a reference to a packet?
359 if (be.first->second == pi)
361 ip2packets.erase(be.first++);
362 //printfd(__FILE__, "Remove U from ip2packets %s\n", inet_ntostring(pi->first.GetSrcIP()).c_str());
370 //printfd(__FILE__, "-------------------\n");
371 be = ip2packets.equal_range(pi->first.GetDstIP());
372 while (be.first != be.second)
374 // Have a reference to a packet?
375 if (be.first->second == pi)
377 ip2packets.erase(be.first++);
378 //printfd(__FILE__, "Remove D from ip2packets %s\n", inet_ntostring(pi->first.GetDstIP()).c_str());
385 //printfd(__FILE__, "Remove packet\n");
392 if (stgTime - pi->second.updateTime < REMOVE_TIME)
394 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
397 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
398 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
403 swap(packets, newPackets);
404 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
406 oldPacketsSize - packets.size(),
408 oldIp2packetsSize - ip2packets.size());
411 //-----------------------------------------------------------------------------
412 void TRAFFCOUNTER::AddUser(USER_PTR user)
414 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
415 uint32_t uip = user->GetCurrIP();
416 std::pair<ip2p_iter, ip2p_iter> pi;
418 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
419 // Find all packets with IP belongs to this user
420 pi = ip2packets.equal_range(uip);
422 while (pi.first != pi.second)
424 if (pi.first->second->first.GetSrcIP() == uip)
426 assert((!pi.first->second->second.userUPresent ||
427 pi.first->second->second.userU == user) &&
428 "U user present but it's not current user");
430 pi.first->second->second.lenU = 0;
431 pi.first->second->second.userU = user;
432 pi.first->second->second.userUPresent = true;
435 if (pi.first->second->first.GetDstIP() == uip)
437 assert((!pi.first->second->second.userDPresent ||
438 pi.first->second->second.userD == user) &&
439 "D user present but it's not current user");
441 pi.first->second->second.lenD = 0;
442 pi.first->second->second.userD = user;
443 pi.first->second->second.userDPresent = true;
449 //-----------------------------------------------------------------------------
450 void TRAFFCOUNTER::DelUser(uint32_t uip)
452 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
453 std::pair<ip2p_iter, ip2p_iter> pi;
455 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
456 pi = ip2packets.equal_range(uip);
458 while (pi.first != pi.second)
460 if (pi.first->second->first.GetSrcIP() == uip)
462 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
464 #ifdef TRAFF_STAT_WITH_PORTS
465 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
466 pi.first->second->first.GetDstIP(),
467 pi.first->second->first.GetDstPort(),
468 pi.first->second->second.lenU);
470 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
471 pi.first->second->first.GetDstIP(),
472 pi.first->second->second.lenU);
475 pi.first->second->second.userUPresent = false;
478 if (pi.first->second->first.GetDstIP() == uip)
480 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
482 #ifdef TRAFF_STAT_WITH_PORTS
483 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
484 pi.first->second->first.GetSrcIP(),
485 pi.first->second->first.GetSrcPort(),
486 pi.first->second->second.lenD);
488 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
489 pi.first->second->first.GetSrcIP(),
490 pi.first->second->second.lenD);
494 pi.first->second->second.userDPresent = false;
500 ip2packets.erase(pi.first, pi.second);
502 //-----------------------------------------------------------------------------
503 void TRAFFCOUNTER::SetUserNotifiers(USER_PTR user)
505 // Adding user. Adding notifiers to user.
506 TRF_IP_BEFORE ipBNotifier(*this, user);
507 ipBeforeNotifiers.push_front(ipBNotifier);
508 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
510 TRF_IP_AFTER ipANotifier(*this, user);
511 ipAfterNotifiers.push_front(ipANotifier);
512 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
514 //-----------------------------------------------------------------------------
515 void TRAFFCOUNTER::UnSetUserNotifiers(USER_PTR user)
517 // Removing user. Removing notifiers from user.
518 std::list<TRF_IP_BEFORE>::iterator bi;
519 std::list<TRF_IP_AFTER>::iterator ai;
521 bi = ipBeforeNotifiers.begin();
522 while (bi != ipBeforeNotifiers.end())
524 if (user->GetLogin() == bi->GetUser()->GetLogin())
526 user->DelCurrIPBeforeNotifier(&(*bi));
527 ipBeforeNotifiers.erase(bi);
533 ai = ipAfterNotifiers.begin();
534 while (ai != ipAfterNotifiers.end())
536 if (user->GetLogin() == ai->GetUser()->GetLogin())
538 user->DelCurrIPAfterNotifier(&(*ai));
539 ipAfterNotifiers.erase(ai);
545 //-----------------------------------------------------------------------------
546 void TRAFFCOUNTER::DeterminateDir(const RAW_PACKET & packet,
547 int * dirU, // Direction for incoming packet
548 int * dirD) const // Direction for outgoing packet
554 bool foundU = false; // Was rule for U found ?
555 bool foundD = false; // Was rule for D found ?
556 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
558 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
560 std::list<RULE>::const_iterator ln;
563 while (ln != rules.end())
577 portMatchU = (packet.GetProto() == ICMP_RPOTO);
581 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
582 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
586 if (packet.GetProto() == TCP_PROTO)
587 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
591 if (packet.GetProto() == UDP_PROTO)
592 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
596 printfd(__FILE__, "Error! Incorrect rule!\n");
600 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
602 if (!foundU && addrMatchU && portMatchU)
606 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
607 //PrintRule(ln->rule);
624 portMatchD = (packet.GetProto() == ICMP_RPOTO);
628 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
629 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
633 if (packet.GetProto() == TCP_PROTO)
634 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
638 if (packet.GetProto() == UDP_PROTO)
639 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
643 printfd(__FILE__, "Error! Incorrect rule!\n");
647 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
649 if (!foundD && addrMatchD && portMatchD)
653 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
654 //PrintRule(ln->rule);
659 } //while (ln != rules.end())
669 //-----------------------------------------------------------------------------
670 void TRAFFCOUNTER::SetRulesFile(const std::string & fn)
674 //-----------------------------------------------------------------------------
675 bool TRAFFCOUNTER::ReadRules(bool test)
677 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
682 char tp[100]; // protocol
683 char ta[100]; // address
684 char td[100]; // target direction
687 f = fopen(rulesFileName.c_str(), "rt");
691 WriteServLog("File %s cannot be oppened.", rulesFileName.c_str());
695 while (fgets(str, 1023, f))
698 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
703 r = sscanf(str,"%s %s %s", tp, ta, td);
706 WriteServLog("Error in file %s. There must be 3 parameters. Line %d.", rulesFileName.c_str(), lineNumber);
714 for (int i = 0; i < PROTOMAX; i++)
716 if (strcasecmp(tp, protoName[i]) == 0)
720 for (int i = 0; i < DIR_NUM + 1; i++)
722 if (td == dirName[i])
726 if (rul.dir == 0xff || rul.proto == 0xff)
728 WriteServLog("Error in file %s. Line %d.",
729 rulesFileName.c_str(), lineNumber);
734 if (ParseAddress(ta, &rul) != 0)
736 WriteServLog("Error in file %s. Error in adress. Line %d.",
737 rulesFileName.c_str(), lineNumber);
742 rules.push_back(rul);
748 // Adding lastest rule: ALL 0.0.0.0/0 NULL
749 rul.dir = DIR_NUM; //NULL
750 rul.ip = 0; //0.0.0.0
757 rules.push_back(rul);
763 //-----------------------------------------------------------------------------
764 int TRAFFCOUNTER::Reload()
766 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
770 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
776 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
779 //-----------------------------------------------------------------------------
780 bool TRAFFCOUNTER::ParseAddress(const char * ta, RULE * rule) const
782 char addr[50], mask[20], port1[20], port2[20], ports[40];
784 int len = strlen(ta);
787 memset(addr, 0, sizeof(addr));
788 for (i = 0; i < len; i++)
790 if (ta[i] == '/' || ta[i] == ':')
828 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
830 WriteServLog("No ports specified for this protocol.");
835 ports[i - p] = ta[i];
841 strcpy(ports, "0-65535");
848 if ((sss = strchr(ports, '-')) != NULL)
850 strncpy(port1, ports, int(sss-ports));
851 port1[int(sss - ports)] = 0;
852 strcpy(port2, sss + 1);
856 strcpy(port1, ports);
857 strcpy(port2, ports);
860 // Convert strings to mask, ports and IP
865 msk = strtol(mask, &res, 10);
869 prt1 = strtol(port1, &res, 10);
873 prt2 = strtol(port2, &res, 10);
877 int r = inet_aton(addr, (struct in_addr*)&ip);
882 rule->mask = CalcMask(msk);
884 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
886 if ((ip & rule->mask) != ip)
888 WriteServLog("Address does'n match mask.");
897 //-----------------------------------------------------------------------------
898 uint32_t TRAFFCOUNTER::CalcMask(uint32_t msk) const
900 if (msk >= 32) return 0xFFffFFff;
901 if (msk == 0) return 0;
902 return htonl(0xFFffFFff << (32 - msk));
904 //---------------------------------------------------------------------------
905 void TRAFFCOUNTER::FreeRules()
909 //-----------------------------------------------------------------------------
910 void TRAFFCOUNTER::PrintRule(RULE rule) const
912 printf("%15s ", inet_ntostring(rule.ip).c_str());
913 printf("mask=%08X ", rule.mask);
914 printf("port1=%5d ", rule.port1);
915 printf("port2=%5d ", rule.port2);
934 printf("dir=%d \n", rule.dir);
937 //-----------------------------------------------------------------------------
938 void TRAFFCOUNTER::SetMonitorDir(const std::string & monitorDir)
940 TRAFFCOUNTER::monitorDir = monitorDir;
941 monitoring = (monitorDir != "");
943 //-----------------------------------------------------------------------------