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)
66 WriteServLog(GetStgLogger()),
77 addUserNotifier(*this),
78 delUserNotifier(*this)
80 for (int i = 0; i < DIR_NUM; i++)
81 strprintf(&dirName[i], "DIR%d", i);
83 dirName[DIR_NUM] = "NULL";
85 users->AddNotifierUserAdd(&addUserNotifier);
86 users->AddNotifierUserDel(&delUserNotifier);
88 pthread_mutex_init(&mutex, NULL);
90 //-----------------------------------------------------------------------------
91 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
93 pthread_mutex_destroy(&mutex);
95 //-----------------------------------------------------------------------------
96 int TRAFFCOUNTER_IMPL::Start()
98 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
105 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
106 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
110 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
111 int h = users->OpenSearch();
112 assert(h && "USERS::OpenSearch is always correct");
115 while (users->SearchNext(h, &u) == 0)
119 users->CloseSearch(h);
122 if (pthread_create(&thread, NULL, Run, this))
124 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
125 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
130 //-----------------------------------------------------------------------------
131 int TRAFFCOUNTER_IMPL::Stop()
138 int h = users->OpenSearch();
139 assert(h && "USERS::OpenSearch is always correct");
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);
158 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
162 //-----------------------------------------------------------------------------
163 void * TRAFFCOUNTER_IMPL::Run(void * data)
166 sigfillset(&signalSet);
167 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
169 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
173 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
174 struct timespec ts = {0, 500000000};
180 tc->FlushAndRemove();
184 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
186 std::string monFile(tc->monitorDir + "/traffcounter_r");
187 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
189 TouchFile(monFile.c_str());
192 if (++c % FLUSH_TIME == 0)
193 tc->FlushAndRemove();
199 //-----------------------------------------------------------------------------
200 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
205 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
207 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
209 static std::string monFile = monitorDir + "/traffcounter_p";
210 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
212 TouchFile(monFile.c_str());
215 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
217 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
218 //TODO replace find with lower_bound.
220 // Searching a new packet in a tree.
221 pp_iter pi = packets.find(rawPacket);
223 // Packet found - update length and time
224 if (pi != packets.end())
226 pi->second.lenU += rawPacket.GetLen();
227 pi->second.lenD += rawPacket.GetLen();
228 pi->second.updateTime = stgTime;
229 /*printfd(__FILE__, "=============================\n");
230 printfd(__FILE__, "Packet found!\n");
231 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
232 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
233 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
234 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
235 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
236 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
237 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
238 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
239 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
240 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
241 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
242 printfd(__FILE__, "=============================\n");*/
246 PACKET_EXTRA_DATA ed;
248 // Packet not found - add new packet
250 ed.updateTime = stgTime;
251 ed.flushTime = stgTime;
254 userU is that whose user_ip == packet_ip_src
255 userD is that whose user_ip == packet_ip_dst
258 uint32_t ipU = rawPacket.GetSrcIP();
259 uint32_t ipD = rawPacket.GetDstIP();
261 // Searching users with such IP
262 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
264 ed.userUPresent = true;
267 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
269 ed.userDPresent = true;
272 if (ed.userUPresent ||
275 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
277 ed.lenD = ed.lenU = rawPacket.GetLen();
279 //TODO use result of lower_bound to inserting new record
281 // Adding packet to a tree.
282 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
283 pp_iter newPacket = insertResult.first;
285 // Adding packet reference to an IP index.
286 ip2packets.insert(std::make_pair(ipU, newPacket));
287 ip2packets.insert(std::make_pair(ipD, newPacket));
290 //-----------------------------------------------------------------------------
291 void TRAFFCOUNTER_IMPL::FlushAndRemove()
293 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
295 int oldPacketsSize = packets.size();
296 int oldIp2packetsSize = ip2packets.size();
299 pi = packets.begin();
300 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
301 ip2packets.erase(ip2packets.begin(), ip2packets.end());
302 while (pi != packets.end())
305 if (stgTime - pi->second.flushTime > FLUSH_TIME)
307 if (pi->second.userUPresent)
309 //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);
312 if (pi->second.dirU < DIR_NUM)
314 #ifdef TRAFF_STAT_WITH_PORTS
315 pi->second.userU->AddTraffStatU(pi->second.dirU,
316 pi->first.GetDstIP(),
317 pi->first.GetDstPort(),
320 pi->second.userU->AddTraffStatU(pi->second.dirU,
321 pi->first.GetDstIP(),
327 pi->second.flushTime = stgTime;
330 if (pi->second.userDPresent)
332 //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);
335 if (pi->second.dirD < DIR_NUM)
337 #ifdef TRAFF_STAT_WITH_PORTS
338 pi->second.userD->AddTraffStatD(pi->second.dirD,
339 pi->first.GetSrcIP(),
340 pi->first.GetSrcPort(),
343 pi->second.userD->AddTraffStatD(pi->second.dirD,
344 pi->first.GetSrcIP(),
350 pi->second.flushTime = stgTime;
354 if (stgTime - pi->second.updateTime < REMOVE_TIME)
356 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
359 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
360 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
365 swap(packets, newPackets);
366 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
368 oldPacketsSize - packets.size(),
370 oldIp2packetsSize - ip2packets.size());
373 //-----------------------------------------------------------------------------
374 void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user)
376 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
377 uint32_t uip = user->GetCurrIP();
378 std::pair<ip2p_iter, ip2p_iter> pi;
380 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
381 // Find all packets with IP belongs to this user
382 pi = ip2packets.equal_range(uip);
384 while (pi.first != pi.second)
386 if (pi.first->second->first.GetSrcIP() == uip)
388 assert((!pi.first->second->second.userUPresent ||
389 pi.first->second->second.userU == user) &&
390 "U user present but it's not current user");
392 pi.first->second->second.lenU = 0;
393 pi.first->second->second.userU = user;
394 pi.first->second->second.userUPresent = true;
397 if (pi.first->second->first.GetDstIP() == uip)
399 assert((!pi.first->second->second.userDPresent ||
400 pi.first->second->second.userD == user) &&
401 "D user present but it's not current user");
403 pi.first->second->second.lenD = 0;
404 pi.first->second->second.userD = user;
405 pi.first->second->second.userDPresent = true;
411 //-----------------------------------------------------------------------------
412 void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
414 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
415 std::pair<ip2p_iter, ip2p_iter> pi;
417 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
418 pi = ip2packets.equal_range(uip);
420 while (pi.first != pi.second)
422 if (pi.first->second->first.GetSrcIP() == uip)
424 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
426 #ifdef TRAFF_STAT_WITH_PORTS
427 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
428 pi.first->second->first.GetDstIP(),
429 pi.first->second->first.GetDstPort(),
430 pi.first->second->second.lenU);
432 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
433 pi.first->second->first.GetDstIP(),
434 pi.first->second->second.lenU);
437 pi.first->second->second.userUPresent = false;
440 if (pi.first->second->first.GetDstIP() == uip)
442 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
444 #ifdef TRAFF_STAT_WITH_PORTS
445 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
446 pi.first->second->first.GetSrcIP(),
447 pi.first->second->first.GetSrcPort(),
448 pi.first->second->second.lenD);
450 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
451 pi.first->second->first.GetSrcIP(),
452 pi.first->second->second.lenD);
456 pi.first->second->second.userDPresent = false;
462 ip2packets.erase(pi.first, pi.second);
464 //-----------------------------------------------------------------------------
465 void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user)
467 // Adding user. Adding notifiers to user.
468 TRF_IP_BEFORE ipBNotifier(*this, user);
469 ipBeforeNotifiers.push_front(ipBNotifier);
470 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
472 TRF_IP_AFTER ipANotifier(*this, user);
473 ipAfterNotifiers.push_front(ipANotifier);
474 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
476 //-----------------------------------------------------------------------------
477 void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
479 // Removing user. Removing notifiers from user.
480 std::list<TRF_IP_BEFORE>::iterator bi;
481 std::list<TRF_IP_AFTER>::iterator ai;
483 bi = ipBeforeNotifiers.begin();
484 while (bi != ipBeforeNotifiers.end())
486 if (user->GetLogin() == bi->GetUser()->GetLogin())
488 user->DelCurrIPBeforeNotifier(&(*bi));
489 ipBeforeNotifiers.erase(bi);
495 ai = ipAfterNotifiers.begin();
496 while (ai != ipAfterNotifiers.end())
498 if (user->GetLogin() == ai->GetUser()->GetLogin())
500 user->DelCurrIPAfterNotifier(&(*ai));
501 ipAfterNotifiers.erase(ai);
507 //-----------------------------------------------------------------------------
508 void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
509 int * dirU, // Direction for incoming packet
510 int * dirD) const // Direction for outgoing packet
516 bool foundU = false; // Was rule for U found ?
517 bool foundD = false; // Was rule for D found ?
518 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
520 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
522 std::list<RULE>::const_iterator ln;
525 while (ln != rules.end())
539 portMatchU = (packet.GetProto() == ICMP_RPOTO);
543 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
544 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
548 if (packet.GetProto() == TCP_PROTO)
549 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
553 if (packet.GetProto() == UDP_PROTO)
554 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
558 printfd(__FILE__, "Error! Incorrect rule!\n");
562 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
564 if (!foundU && addrMatchU && portMatchU)
568 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
569 //PrintRule(ln->rule);
586 portMatchD = (packet.GetProto() == ICMP_RPOTO);
590 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
591 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
595 if (packet.GetProto() == TCP_PROTO)
596 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
600 if (packet.GetProto() == UDP_PROTO)
601 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
605 printfd(__FILE__, "Error! Incorrect rule!\n");
609 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
611 if (!foundD && addrMatchD && portMatchD)
615 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
616 //PrintRule(ln->rule);
621 } //while (ln != rules.end())
629 //-----------------------------------------------------------------------------
630 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
634 //-----------------------------------------------------------------------------
635 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
637 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
642 char tp[100]; // protocol
643 char ta[100]; // address
644 char td[100]; // target direction
647 f = fopen(rulesFileName.c_str(), "rt");
651 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
652 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
656 while (fgets(str, 1023, f))
659 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
664 r = sscanf(str,"%s %s %s", tp, ta, td);
667 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
668 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
676 for (int i = 0; i < PROTOMAX; i++)
678 if (strcasecmp(tp, protoName[i]) == 0)
682 for (int i = 0; i < DIR_NUM + 1; i++)
684 if (td == dirName[i])
688 if (rul.dir == 0xff || rul.proto == 0xff)
690 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
691 WriteServLog("Error in file %s. Line %d.",
692 rulesFileName.c_str(), lineNumber);
697 if (ParseAddress(ta, &rul) != 0)
699 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
700 WriteServLog("Error in file %s. Error in adress. Line %d.",
701 rulesFileName.c_str(), lineNumber);
706 rules.push_back(rul);
712 // Adding lastest rule: ALL 0.0.0.0/0 NULL
713 rul.dir = DIR_NUM; //NULL
714 rul.ip = 0; //0.0.0.0
721 rules.push_back(rul);
727 //-----------------------------------------------------------------------------
728 int TRAFFCOUNTER_IMPL::Reload()
730 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
734 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
735 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
741 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reload rules successfull.\n");
742 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
745 //-----------------------------------------------------------------------------
746 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
748 char addr[50], mask[20], port1[20], port2[20], ports[40];
750 int len = strlen(ta);
753 memset(addr, 0, sizeof(addr));
754 for (i = 0; i < len; i++)
756 if (ta[i] == '/' || ta[i] == ':')
794 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
796 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
797 WriteServLog("No ports specified for this protocol.");
802 ports[i - p] = ta[i];
808 strcpy(ports, "0-65535");
815 if ((sss = strchr(ports, '-')) != NULL)
817 strncpy(port1, ports, int(sss-ports));
818 port1[int(sss - ports)] = 0;
819 strcpy(port2, sss + 1);
823 strcpy(port1, ports);
824 strcpy(port2, ports);
827 // Convert strings to mask, ports and IP
832 msk = strtol(mask, &res, 10);
836 prt1 = strtol(port1, &res, 10);
840 prt2 = strtol(port2, &res, 10);
844 int r = inet_aton(addr, (struct in_addr*)&ip);
849 rule->mask = CalcMask(msk);
851 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
853 if ((ip & rule->mask) != ip)
855 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
856 WriteServLog("Address does'n match mask.");
865 //-----------------------------------------------------------------------------
866 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
868 if (msk >= 32) return 0xFFffFFff;
869 if (msk == 0) return 0;
870 return htonl(0xFFffFFff << (32 - msk));
872 //---------------------------------------------------------------------------
873 void TRAFFCOUNTER_IMPL::FreeRules()
877 //-----------------------------------------------------------------------------
878 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
880 printf("%15s ", inet_ntostring(rule.ip).c_str());
881 printf("mask=%08X ", rule.mask);
882 printf("port1=%5d ", rule.port1);
883 printf("port2=%5d ", rule.port2);
902 printf("dir=%d \n", static_cast<unsigned>(rule.dir));
904 //-----------------------------------------------------------------------------
905 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
907 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
908 monitoring = (monitorDir != "");
910 //-----------------------------------------------------------------------------