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 "stg/const.h" // MONITOR_TIME_DELAY_SEC
45 #include "traffcounter_impl.h"
46 #include "stg_timer.h"
47 #include "users_impl.h"
49 #define FLUSH_TIME (10)
50 #define REMOVE_TIME (31)
52 const char protoName[PROTOMAX][8] =
53 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
57 tcp = 0, udp, icmp, tcp_udp, all
60 //-----------------------------------------------------------------------------
61 TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
67 WriteServLog(GetStgLogger()),
78 addUserNotifier(*this),
79 delUserNotifier(*this)
81 for (int i = 0; i < DIR_NUM; i++)
82 strprintf(&dirName[i], "DIR%d", i);
84 dirName[DIR_NUM] = "NULL";
86 users->AddNotifierUserAdd(&addUserNotifier);
87 users->AddNotifierUserDel(&delUserNotifier);
89 pthread_mutex_init(&mutex, NULL);
91 //-----------------------------------------------------------------------------
92 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
94 pthread_mutex_destroy(&mutex);
96 //-----------------------------------------------------------------------------
97 int TRAFFCOUNTER_IMPL::Start()
99 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
106 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
107 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
111 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
112 int h = users->OpenSearch();
113 assert(h && "USERS::OpenSearch is always correct");
116 while (users->SearchNext(h, &u) == 0)
120 users->CloseSearch(h);
123 if (pthread_create(&thread, NULL, Run, this))
125 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
126 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
131 //-----------------------------------------------------------------------------
132 int TRAFFCOUNTER_IMPL::Stop()
139 int h = users->OpenSearch();
140 assert(h && "USERS::OpenSearch is always correct");
143 while (users->SearchNext(h, &u) == 0)
145 UnSetUserNotifiers(u);
147 users->CloseSearch(h);
149 //5 seconds to thread stops itself
150 struct timespec ts = {0, 200000000};
151 for (int i = 0; i < 25 && !stopped; i++)
153 nanosleep(&ts, NULL);
159 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
163 //-----------------------------------------------------------------------------
164 void * TRAFFCOUNTER_IMPL::Run(void * data)
167 sigfillset(&signalSet);
168 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
170 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
174 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
175 struct timespec ts = {0, 500000000};
181 tc->FlushAndRemove();
185 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
187 std::string monFile(tc->monitorDir + "/traffcounter_r");
188 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
190 TouchFile(monFile.c_str());
193 if (++c % FLUSH_TIME == 0)
194 tc->FlushAndRemove();
200 //-----------------------------------------------------------------------------
201 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
206 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
208 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
210 std::string monFile = monitorDir + "/traffcounter_p";
211 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
213 TouchFile(monFile.c_str());
216 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
218 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
219 //TODO replace find with lower_bound.
221 // Searching a new packet in a tree.
222 pp_iter pi = packets.find(rawPacket);
224 // Packet found - update length and time
225 if (pi != packets.end())
227 pi->second.lenU += rawPacket.GetLen();
228 pi->second.lenD += rawPacket.GetLen();
229 pi->second.updateTime = stgTime;
230 /*printfd(__FILE__, "=============================\n");
231 printfd(__FILE__, "Packet found!\n");
232 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
233 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
234 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
235 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
236 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
237 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
238 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
239 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
240 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
241 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
242 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
243 printfd(__FILE__, "=============================\n");*/
247 PACKET_EXTRA_DATA ed;
249 // Packet not found - add new packet
251 ed.updateTime = stgTime;
252 ed.flushTime = stgTime;
255 userU is that whose user_ip == packet_ip_src
256 userD is that whose user_ip == packet_ip_dst
259 uint32_t ipU = rawPacket.GetSrcIP();
260 uint32_t ipD = rawPacket.GetDstIP();
262 // Searching users with such IP
263 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
265 ed.userUPresent = true;
268 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
270 ed.userDPresent = true;
273 if (ed.userUPresent ||
276 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
278 ed.lenD = ed.lenU = rawPacket.GetLen();
280 //TODO use result of lower_bound to inserting new record
282 // Adding packet to a tree.
283 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
284 pp_iter newPacket = insertResult.first;
286 // Adding packet reference to an IP index.
287 ip2packets.insert(std::make_pair(ipU, newPacket));
288 ip2packets.insert(std::make_pair(ipD, newPacket));
291 //-----------------------------------------------------------------------------
292 void TRAFFCOUNTER_IMPL::FlushAndRemove()
294 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
296 Packets::size_type oldPacketsSize = packets.size();
297 Index::size_type oldIp2packetsSize = ip2packets.size();
300 pi = packets.begin();
302 ip2packets.erase(ip2packets.begin(), ip2packets.end());
303 while (pi != packets.end())
306 if (stgTime - pi->second.flushTime > FLUSH_TIME)
308 if (pi->second.userUPresent)
310 //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);
313 if (pi->second.dirU < DIR_NUM)
315 #ifdef TRAFF_STAT_WITH_PORTS
316 pi->second.userU->AddTraffStatU(pi->second.dirU,
317 pi->first.GetDstIP(),
318 pi->first.GetDstPort(),
321 pi->second.userU->AddTraffStatU(pi->second.dirU,
322 pi->first.GetDstIP(),
328 pi->second.flushTime = stgTime;
331 if (pi->second.userDPresent)
333 //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);
336 if (pi->second.dirD < DIR_NUM)
338 #ifdef TRAFF_STAT_WITH_PORTS
339 pi->second.userD->AddTraffStatD(pi->second.dirD,
340 pi->first.GetSrcIP(),
341 pi->first.GetSrcPort(),
344 pi->second.userD->AddTraffStatD(pi->second.dirD,
345 pi->first.GetSrcIP(),
351 pi->second.flushTime = stgTime;
355 if (stgTime - pi->second.updateTime < REMOVE_TIME)
357 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
360 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
361 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
366 swap(packets, newPackets);
367 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
369 oldPacketsSize - packets.size(),
371 oldIp2packetsSize - ip2packets.size());
374 //-----------------------------------------------------------------------------
375 void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user)
377 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
378 uint32_t uip = user->GetCurrIP();
379 std::pair<ip2p_iter, ip2p_iter> pi;
381 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
382 // Find all packets with IP belongs to this user
383 pi = ip2packets.equal_range(uip);
385 while (pi.first != pi.second)
387 if (pi.first->second->first.GetSrcIP() == uip)
389 assert((!pi.first->second->second.userUPresent ||
390 pi.first->second->second.userU == user) &&
391 "U user present but it's not current user");
393 pi.first->second->second.lenU = 0;
394 pi.first->second->second.userU = user;
395 pi.first->second->second.userUPresent = true;
398 if (pi.first->second->first.GetDstIP() == uip)
400 assert((!pi.first->second->second.userDPresent ||
401 pi.first->second->second.userD == user) &&
402 "D user present but it's not current user");
404 pi.first->second->second.lenD = 0;
405 pi.first->second->second.userD = user;
406 pi.first->second->second.userDPresent = true;
412 //-----------------------------------------------------------------------------
413 void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
415 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
416 std::pair<ip2p_iter, ip2p_iter> pi;
418 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
419 pi = ip2packets.equal_range(uip);
421 while (pi.first != pi.second)
423 if (pi.first->second->first.GetSrcIP() == uip)
425 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
427 #ifdef TRAFF_STAT_WITH_PORTS
428 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
429 pi.first->second->first.GetDstIP(),
430 pi.first->second->first.GetDstPort(),
431 pi.first->second->second.lenU);
433 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
434 pi.first->second->first.GetDstIP(),
435 pi.first->second->second.lenU);
438 pi.first->second->second.userUPresent = false;
441 if (pi.first->second->first.GetDstIP() == uip)
443 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
445 #ifdef TRAFF_STAT_WITH_PORTS
446 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
447 pi.first->second->first.GetSrcIP(),
448 pi.first->second->first.GetSrcPort(),
449 pi.first->second->second.lenD);
451 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
452 pi.first->second->first.GetSrcIP(),
453 pi.first->second->second.lenD);
457 pi.first->second->second.userDPresent = false;
463 ip2packets.erase(pi.first, pi.second);
465 //-----------------------------------------------------------------------------
466 void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user)
468 // Adding user. Adding notifiers to user.
469 TRF_IP_BEFORE ipBNotifier(*this, user);
470 ipBeforeNotifiers.push_front(ipBNotifier);
471 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
473 TRF_IP_AFTER ipANotifier(*this, user);
474 ipAfterNotifiers.push_front(ipANotifier);
475 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
477 //-----------------------------------------------------------------------------
478 void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
480 // Removing user. Removing notifiers from user.
481 std::list<TRF_IP_BEFORE>::iterator bi;
482 std::list<TRF_IP_AFTER>::iterator ai;
484 bi = ipBeforeNotifiers.begin();
485 while (bi != ipBeforeNotifiers.end())
487 if (user->GetLogin() == bi->GetUser()->GetLogin())
489 user->DelCurrIPBeforeNotifier(&(*bi));
490 ipBeforeNotifiers.erase(bi);
496 ai = ipAfterNotifiers.begin();
497 while (ai != ipAfterNotifiers.end())
499 if (user->GetLogin() == ai->GetUser()->GetLogin())
501 user->DelCurrIPAfterNotifier(&(*ai));
502 ipAfterNotifiers.erase(ai);
508 //-----------------------------------------------------------------------------
509 void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
510 int * dirU, // Direction for incoming packet
511 int * dirD) const // Direction for outgoing packet
517 bool foundU = false; // Was rule for U found ?
518 bool foundD = false; // Was rule for D found ?
519 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
521 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
523 std::list<RULE>::const_iterator ln;
526 while (ln != rules.end())
540 portMatchU = (packet.GetProto() == ICMP_RPOTO);
544 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
545 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
549 if (packet.GetProto() == TCP_PROTO)
550 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
554 if (packet.GetProto() == UDP_PROTO)
555 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
559 printfd(__FILE__, "Error! Incorrect rule!\n");
563 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
565 if (!foundU && addrMatchU && portMatchU)
569 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
570 //PrintRule(ln->rule);
587 portMatchD = (packet.GetProto() == ICMP_RPOTO);
591 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
592 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
596 if (packet.GetProto() == TCP_PROTO)
597 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
601 if (packet.GetProto() == UDP_PROTO)
602 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
606 printfd(__FILE__, "Error! Incorrect rule!\n");
610 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
612 if (!foundD && addrMatchD && portMatchD)
616 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
617 //PrintRule(ln->rule);
622 } //while (ln != rules.end())
630 //-----------------------------------------------------------------------------
631 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
635 //-----------------------------------------------------------------------------
636 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
638 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
643 char tp[100]; // protocol
644 char ta[100]; // address
645 char td[100]; // target direction
648 f = fopen(rulesFileName.c_str(), "rt");
652 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
653 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
657 while (fgets(str, 1023, f))
660 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
665 r = sscanf(str,"%s %s %s", tp, ta, td);
668 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
669 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
677 for (uint8_t i = 0; i < PROTOMAX; i++)
679 if (strcasecmp(tp, protoName[i]) == 0)
683 for (uint32_t i = 0; i < DIR_NUM + 1; i++)
685 if (td == dirName[i])
689 if (rul.dir == 0xff || rul.proto == 0xff)
691 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
692 WriteServLog("Error in file %s. Line %d.",
693 rulesFileName.c_str(), lineNumber);
698 if (ParseAddress(ta, &rul) != 0)
700 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
701 WriteServLog("Error in file %s. Error in adress. Line %d.",
702 rulesFileName.c_str(), lineNumber);
707 rules.push_back(rul);
713 // Adding lastest rule: ALL 0.0.0.0/0 NULL
714 rul.dir = DIR_NUM; //NULL
715 rul.ip = 0; //0.0.0.0
722 rules.push_back(rul);
728 //-----------------------------------------------------------------------------
729 int TRAFFCOUNTER_IMPL::Reload()
731 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
735 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
736 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
742 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reload rules successfull.\n");
743 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
746 //-----------------------------------------------------------------------------
747 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
749 char addr[50], mask[20], port1[20], port2[20], ports[40];
751 size_t len = strlen(ta);
754 memset(addr, 0, sizeof(addr));
755 for (i = 0; i < len; i++)
757 if (ta[i] == '/' || ta[i] == ':')
795 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
797 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
798 WriteServLog("No ports specified for this protocol.");
803 ports[i - p] = ta[i];
809 strcpy(ports, "0-65535");
816 if ((sss = strchr(ports, '-')) != NULL)
818 strncpy(port1, ports, int(sss-ports));
819 port1[int(sss - ports)] = 0;
820 strcpy(port2, sss + 1);
824 strcpy(port1, ports);
825 strcpy(port2, ports);
828 // Convert strings to mask, ports and IP
829 uint16_t prt1, prt2, msk;
830 struct in_addr ipaddr;
833 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
837 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
841 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
845 int r = inet_aton(addr, &ipaddr);
849 rule->ip = ipaddr.s_addr;
850 rule->mask = CalcMask(msk);
852 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
854 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
856 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
857 WriteServLog("Address does'n match mask.");
866 //-----------------------------------------------------------------------------
867 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
869 if (msk >= 32) return 0xFFffFFff;
870 if (msk == 0) return 0;
871 return htonl(0xFFffFFff << (32 - msk));
873 //---------------------------------------------------------------------------
874 void TRAFFCOUNTER_IMPL::FreeRules()
878 //-----------------------------------------------------------------------------
879 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
881 printf("%15s ", inet_ntostring(rule.ip).c_str());
882 printf("mask=%08X ", rule.mask);
883 printf("port1=%5d ", rule.port1);
884 printf("port2=%5d ", rule.port2);
903 printf("dir=%u \n", static_cast<unsigned>(rule.dir));
905 //-----------------------------------------------------------------------------
906 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir)
909 monitoring = !monitorDir.empty();
911 //-----------------------------------------------------------------------------