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
41 #include "stg/common.h"
42 #include "stg/locker.h"
43 #include "traffcounter_impl.h"
44 #include "stg_timer.h"
46 #define FLUSH_TIME (10)
47 #define REMOVE_TIME (31)
49 const char protoName[PROTOMAX][8] =
50 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
54 tcp = 0, udp, icmp, tcp_udp, all
57 //-----------------------------------------------------------------------------
58 TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS * u, const TARIFFS *, const std::string & fn)
59 : WriteServLog(GetStgLogger()),
65 addUserNotifier(*this),
66 delUserNotifier(*this)
68 for (int i = 0; i < DIR_NUM; i++)
69 strprintf(&dirName[i], "DIR%d", i);
71 dirName[DIR_NUM] = "NULL";
73 users->AddNotifierUserAdd(&addUserNotifier);
74 users->AddNotifierUserDel(&delUserNotifier);
76 pthread_mutex_init(&mutex, NULL);
78 //-----------------------------------------------------------------------------
79 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
81 pthread_mutex_destroy(&mutex);
83 //-----------------------------------------------------------------------------
84 int TRAFFCOUNTER_IMPL::Start()
86 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
93 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
97 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
98 int h = users->OpenSearch();
102 WriteServLog("TRAFFCOUNTER: Cannot get users.");
106 while (users->SearchNext(h, &u) == 0)
110 users->CloseSearch(h);
113 if (pthread_create(&thread, NULL, Run, this))
115 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread!");
120 //-----------------------------------------------------------------------------
121 int TRAFFCOUNTER_IMPL::Stop()
128 int h = users->OpenSearch();
131 WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
136 while (users->SearchNext(h, &u) == 0)
138 UnSetUserNotifiers(u);
140 users->CloseSearch(h);
142 //5 seconds to thread stops itself
143 struct timespec ts = {0, 200000000};
144 for (int i = 0; i < 25 && !stopped; i++)
146 nanosleep(&ts, NULL);
149 //after 5 seconds waiting thread still running. now kill it
152 printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
153 if (pthread_kill(thread, SIGINT))
157 printfd(__FILE__, "TRAFFCOUNTER killed\n");
159 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
163 //-----------------------------------------------------------------------------
164 void * TRAFFCOUNTER_IMPL::Run(void * data)
166 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
170 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
171 struct timespec ts = {0, 500000000};
177 tc->FlushAndRemove();
181 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
183 std::string monFile(tc->monitorDir + "/traffcounter_r");
184 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
186 TouchFile(monFile.c_str());
189 if (++c % FLUSH_TIME == 0)
190 tc->FlushAndRemove();
196 //-----------------------------------------------------------------------------
197 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
202 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
204 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
206 static std::string monFile = monitorDir + "/traffcounter_p";
207 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
209 TouchFile(monFile.c_str());
212 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
214 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
215 //TODO replace find with lower_bound.
217 // Searching a new packet in a tree.
218 pp_iter pi = packets.find(rawPacket);
220 // Packet found - update length and time
221 if (pi != packets.end())
223 pi->second.lenU += rawPacket.GetLen();
224 pi->second.lenD += rawPacket.GetLen();
225 pi->second.updateTime = stgTime;
226 /*printfd(__FILE__, "=============================\n");
227 printfd(__FILE__, "Packet found!\n");
228 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
229 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
230 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
231 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
232 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
233 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
234 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
235 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
236 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
237 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
238 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
239 printfd(__FILE__, "=============================\n");*/
243 PACKET_EXTRA_DATA ed;
245 // Packet not found - add new packet
247 ed.updateTime = stgTime;
248 ed.flushTime = stgTime;
251 userU is that whose user_ip == packet_ip_src
252 userD is that whose user_ip == packet_ip_dst
255 uint32_t ipU = rawPacket.GetSrcIP();
256 uint32_t ipD = rawPacket.GetDstIP();
258 // Searching users with such IP
259 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
261 ed.userUPresent = true;
264 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
266 ed.userDPresent = true;
269 if (ed.userUPresent ||
272 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
274 ed.lenD = ed.lenU = rawPacket.GetLen();
276 //TODO use result of lower_bound to inserting new record
278 // Adding packet to a tree.
279 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
280 pp_iter newPacket = insertResult.first;
282 // Adding packet reference to an IP index.
283 ip2packets.insert(std::make_pair(ipU, newPacket));
284 ip2packets.insert(std::make_pair(ipD, newPacket));
287 //-----------------------------------------------------------------------------
288 void TRAFFCOUNTER_IMPL::FlushAndRemove()
290 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
292 int oldPacketsSize = packets.size();
293 int oldIp2packetsSize = ip2packets.size();
296 pi = packets.begin();
297 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
298 ip2packets.erase(ip2packets.begin(), ip2packets.end());
299 while (pi != packets.end())
302 if (stgTime - pi->second.flushTime > FLUSH_TIME)
304 if (pi->second.userUPresent)
306 //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);
309 if (pi->second.dirU < DIR_NUM)
311 #ifdef TRAFF_STAT_WITH_PORTS
312 pi->second.userU->AddTraffStatU(pi->second.dirU,
313 pi->first.GetDstIP(),
314 pi->first.GetDstPort(),
317 pi->second.userU->AddTraffStatU(pi->second.dirU,
318 pi->first.GetDstIP(),
324 pi->second.flushTime = stgTime;
327 if (pi->second.userDPresent)
329 //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);
332 if (pi->second.dirD < DIR_NUM)
334 #ifdef TRAFF_STAT_WITH_PORTS
335 pi->second.userD->AddTraffStatD(pi->second.dirD,
336 pi->first.GetSrcIP(),
337 pi->first.GetSrcPort(),
340 pi->second.userD->AddTraffStatD(pi->second.dirD,
341 pi->first.GetSrcIP(),
347 pi->second.flushTime = stgTime;
352 if (stgTime - pi->second.updateTime > REMOVE_TIME)
354 // Remove packet and references from ip2packets index
355 //printfd(__FILE__, "+++ Removing +++\n");
356 pair<ip2p_iter, ip2p_iter> be(
357 ip2packets.equal_range(pi->first.GetSrcIP()));
358 while (be.first != be.second)
360 // Have a reference to a packet?
361 if (be.first->second == pi)
363 ip2packets.erase(be.first++);
364 //printfd(__FILE__, "Remove U from ip2packets %s\n", inet_ntostring(pi->first.GetSrcIP()).c_str());
372 //printfd(__FILE__, "-------------------\n");
373 be = ip2packets.equal_range(pi->first.GetDstIP());
374 while (be.first != be.second)
376 // Have a reference to a packet?
377 if (be.first->second == pi)
379 ip2packets.erase(be.first++);
380 //printfd(__FILE__, "Remove D from ip2packets %s\n", inet_ntostring(pi->first.GetDstIP()).c_str());
387 //printfd(__FILE__, "Remove packet\n");
394 if (stgTime - pi->second.updateTime < REMOVE_TIME)
396 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
399 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
400 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
405 swap(packets, newPackets);
406 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
408 oldPacketsSize - packets.size(),
410 oldIp2packetsSize - ip2packets.size());
413 //-----------------------------------------------------------------------------
414 void TRAFFCOUNTER_IMPL::AddUser(USER_PTR user)
416 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
417 uint32_t uip = user->GetCurrIP();
418 std::pair<ip2p_iter, ip2p_iter> pi;
420 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
421 // Find all packets with IP belongs to this user
422 pi = ip2packets.equal_range(uip);
424 while (pi.first != pi.second)
426 if (pi.first->second->first.GetSrcIP() == uip)
428 assert((!pi.first->second->second.userUPresent ||
429 pi.first->second->second.userU == user) &&
430 "U user present but it's not current user");
432 pi.first->second->second.lenU = 0;
433 pi.first->second->second.userU = user;
434 pi.first->second->second.userUPresent = true;
437 if (pi.first->second->first.GetDstIP() == uip)
439 assert((!pi.first->second->second.userDPresent ||
440 pi.first->second->second.userD == user) &&
441 "D user present but it's not current user");
443 pi.first->second->second.lenD = 0;
444 pi.first->second->second.userD = user;
445 pi.first->second->second.userDPresent = true;
451 //-----------------------------------------------------------------------------
452 void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
454 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
455 std::pair<ip2p_iter, ip2p_iter> pi;
457 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
458 pi = ip2packets.equal_range(uip);
460 while (pi.first != pi.second)
462 if (pi.first->second->first.GetSrcIP() == uip)
464 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
466 #ifdef TRAFF_STAT_WITH_PORTS
467 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
468 pi.first->second->first.GetDstIP(),
469 pi.first->second->first.GetDstPort(),
470 pi.first->second->second.lenU);
472 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
473 pi.first->second->first.GetDstIP(),
474 pi.first->second->second.lenU);
477 pi.first->second->second.userUPresent = false;
480 if (pi.first->second->first.GetDstIP() == uip)
482 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
484 #ifdef TRAFF_STAT_WITH_PORTS
485 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
486 pi.first->second->first.GetSrcIP(),
487 pi.first->second->first.GetSrcPort(),
488 pi.first->second->second.lenD);
490 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
491 pi.first->second->first.GetSrcIP(),
492 pi.first->second->second.lenD);
496 pi.first->second->second.userDPresent = false;
502 ip2packets.erase(pi.first, pi.second);
504 //-----------------------------------------------------------------------------
505 void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_PTR user)
507 // Adding user. Adding notifiers to user.
508 TRF_IP_BEFORE ipBNotifier(*this, user);
509 ipBeforeNotifiers.push_front(ipBNotifier);
510 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
512 TRF_IP_AFTER ipANotifier(*this, user);
513 ipAfterNotifiers.push_front(ipANotifier);
514 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
516 //-----------------------------------------------------------------------------
517 void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_PTR user)
519 // Removing user. Removing notifiers from user.
520 std::list<TRF_IP_BEFORE>::iterator bi;
521 std::list<TRF_IP_AFTER>::iterator ai;
523 bi = ipBeforeNotifiers.begin();
524 while (bi != ipBeforeNotifiers.end())
526 if (user->GetLogin() == bi->GetUser()->GetLogin())
528 user->DelCurrIPBeforeNotifier(&(*bi));
529 ipBeforeNotifiers.erase(bi);
535 ai = ipAfterNotifiers.begin();
536 while (ai != ipAfterNotifiers.end())
538 if (user->GetLogin() == ai->GetUser()->GetLogin())
540 user->DelCurrIPAfterNotifier(&(*ai));
541 ipAfterNotifiers.erase(ai);
547 //-----------------------------------------------------------------------------
548 void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
549 int * dirU, // Direction for incoming packet
550 int * dirD) const // Direction for outgoing packet
556 bool foundU = false; // Was rule for U found ?
557 bool foundD = false; // Was rule for D found ?
558 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
560 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
562 std::list<RULE>::const_iterator ln;
565 while (ln != rules.end())
579 portMatchU = (packet.GetProto() == ICMP_RPOTO);
583 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
584 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
588 if (packet.GetProto() == TCP_PROTO)
589 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
593 if (packet.GetProto() == UDP_PROTO)
594 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
598 printfd(__FILE__, "Error! Incorrect rule!\n");
602 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
604 if (!foundU && addrMatchU && portMatchU)
608 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
609 //PrintRule(ln->rule);
626 portMatchD = (packet.GetProto() == ICMP_RPOTO);
630 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
631 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
635 if (packet.GetProto() == TCP_PROTO)
636 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
640 if (packet.GetProto() == UDP_PROTO)
641 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
645 printfd(__FILE__, "Error! Incorrect rule!\n");
649 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
651 if (!foundD && addrMatchD && portMatchD)
655 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
656 //PrintRule(ln->rule);
661 } //while (ln != rules.end())
671 //-----------------------------------------------------------------------------
672 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
676 //-----------------------------------------------------------------------------
677 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
679 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
684 char tp[100]; // protocol
685 char ta[100]; // address
686 char td[100]; // target direction
689 f = fopen(rulesFileName.c_str(), "rt");
693 WriteServLog("File %s cannot be oppened.", rulesFileName.c_str());
697 while (fgets(str, 1023, f))
700 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
705 r = sscanf(str,"%s %s %s", tp, ta, td);
708 WriteServLog("Error in file %s. There must be 3 parameters. Line %d.", rulesFileName.c_str(), lineNumber);
716 for (int i = 0; i < PROTOMAX; i++)
718 if (strcasecmp(tp, protoName[i]) == 0)
722 for (int i = 0; i < DIR_NUM + 1; i++)
724 if (td == dirName[i])
728 if (rul.dir == 0xff || rul.proto == 0xff)
730 WriteServLog("Error in file %s. Line %d.",
731 rulesFileName.c_str(), lineNumber);
736 if (ParseAddress(ta, &rul) != 0)
738 WriteServLog("Error in file %s. Error in adress. Line %d.",
739 rulesFileName.c_str(), lineNumber);
744 rules.push_back(rul);
750 // Adding lastest rule: ALL 0.0.0.0/0 NULL
751 rul.dir = DIR_NUM; //NULL
752 rul.ip = 0; //0.0.0.0
759 rules.push_back(rul);
765 //-----------------------------------------------------------------------------
766 int TRAFFCOUNTER_IMPL::Reload()
768 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
772 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
778 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
781 //-----------------------------------------------------------------------------
782 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
784 char addr[50], mask[20], port1[20], port2[20], ports[40];
786 int len = strlen(ta);
789 memset(addr, 0, sizeof(addr));
790 for (i = 0; i < len; i++)
792 if (ta[i] == '/' || ta[i] == ':')
830 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
832 WriteServLog("No ports specified for this protocol.");
837 ports[i - p] = ta[i];
843 strcpy(ports, "0-65535");
850 if ((sss = strchr(ports, '-')) != NULL)
852 strncpy(port1, ports, int(sss-ports));
853 port1[int(sss - ports)] = 0;
854 strcpy(port2, sss + 1);
858 strcpy(port1, ports);
859 strcpy(port2, ports);
862 // Convert strings to mask, ports and IP
867 msk = strtol(mask, &res, 10);
871 prt1 = strtol(port1, &res, 10);
875 prt2 = strtol(port2, &res, 10);
879 int r = inet_aton(addr, (struct in_addr*)&ip);
884 rule->mask = CalcMask(msk);
886 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
888 if ((ip & rule->mask) != ip)
890 WriteServLog("Address does'n match mask.");
899 //-----------------------------------------------------------------------------
900 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
902 if (msk >= 32) return 0xFFffFFff;
903 if (msk == 0) return 0;
904 return htonl(0xFFffFFff << (32 - msk));
906 //---------------------------------------------------------------------------
907 void TRAFFCOUNTER_IMPL::FreeRules()
911 //-----------------------------------------------------------------------------
912 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
914 printf("%15s ", inet_ntostring(rule.ip).c_str());
915 printf("mask=%08X ", rule.mask);
916 printf("port1=%5d ", rule.port1);
917 printf("port2=%5d ", rule.port2);
936 printf("dir=%d \n", rule.dir);
939 //-----------------------------------------------------------------------------
940 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
942 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
943 monitoring = (monitorDir != "");
945 //-----------------------------------------------------------------------------