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"
45 #include "users_impl.h"
47 #define FLUSH_TIME (10)
48 #define REMOVE_TIME (31)
50 const char protoName[PROTOMAX][8] =
51 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
55 tcp = 0, udp, icmp, tcp_udp, all
58 //-----------------------------------------------------------------------------
59 TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
60 : WriteServLog(GetStgLogger()),
66 addUserNotifier(*this),
67 delUserNotifier(*this)
69 for (int i = 0; i < DIR_NUM; i++)
70 strprintf(&dirName[i], "DIR%d", i);
72 dirName[DIR_NUM] = "NULL";
74 users->AddNotifierUserAdd(&addUserNotifier);
75 users->AddNotifierUserDel(&delUserNotifier);
77 pthread_mutex_init(&mutex, NULL);
79 //-----------------------------------------------------------------------------
80 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
82 pthread_mutex_destroy(&mutex);
84 //-----------------------------------------------------------------------------
85 int TRAFFCOUNTER_IMPL::Start()
87 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
94 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
95 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
99 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
100 int h = users->OpenSearch();
104 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot get users\n");
105 WriteServLog("TRAFFCOUNTER: Cannot get users.");
109 while (users->SearchNext(h, &u) == 0)
113 users->CloseSearch(h);
116 if (pthread_create(&thread, NULL, Run, this))
118 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
119 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
124 //-----------------------------------------------------------------------------
125 int TRAFFCOUNTER_IMPL::Stop()
132 int h = users->OpenSearch();
135 WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
140 while (users->SearchNext(h, &u) == 0)
142 UnSetUserNotifiers(u);
144 users->CloseSearch(h);
146 //5 seconds to thread stops itself
147 struct timespec ts = {0, 200000000};
148 for (int i = 0; i < 25 && !stopped; i++)
150 nanosleep(&ts, NULL);
153 //after 5 seconds waiting thread still running. now kill it
156 printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
157 if (pthread_kill(thread, SIGINT))
161 printfd(__FILE__, "TRAFFCOUNTER killed\n");
163 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
167 //-----------------------------------------------------------------------------
168 void * TRAFFCOUNTER_IMPL::Run(void * data)
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 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
208 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
210 static 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 int oldPacketsSize = packets.size();
297 int oldIp2packetsSize = ip2packets.size();
300 pi = packets.begin();
301 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
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())
632 //-----------------------------------------------------------------------------
633 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
637 //-----------------------------------------------------------------------------
638 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
640 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
645 char tp[100]; // protocol
646 char ta[100]; // address
647 char td[100]; // target direction
650 f = fopen(rulesFileName.c_str(), "rt");
654 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
655 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
659 while (fgets(str, 1023, f))
662 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
667 r = sscanf(str,"%s %s %s", tp, ta, td);
670 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
671 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
679 for (int i = 0; i < PROTOMAX; i++)
681 if (strcasecmp(tp, protoName[i]) == 0)
685 for (int i = 0; i < DIR_NUM + 1; i++)
687 if (td == dirName[i])
691 if (rul.dir == 0xff || rul.proto == 0xff)
693 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
694 WriteServLog("Error in file %s. Line %d.",
695 rulesFileName.c_str(), lineNumber);
700 if (ParseAddress(ta, &rul) != 0)
702 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
703 WriteServLog("Error in file %s. Error in adress. Line %d.",
704 rulesFileName.c_str(), lineNumber);
709 rules.push_back(rul);
715 // Adding lastest rule: ALL 0.0.0.0/0 NULL
716 rul.dir = DIR_NUM; //NULL
717 rul.ip = 0; //0.0.0.0
724 rules.push_back(rul);
730 //-----------------------------------------------------------------------------
731 int TRAFFCOUNTER_IMPL::Reload()
733 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
737 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
738 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
744 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reload rules successfull.\n");
745 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
748 //-----------------------------------------------------------------------------
749 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
751 char addr[50], mask[20], port1[20], port2[20], ports[40];
753 int len = strlen(ta);
756 memset(addr, 0, sizeof(addr));
757 for (i = 0; i < len; i++)
759 if (ta[i] == '/' || ta[i] == ':')
797 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
799 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
800 WriteServLog("No ports specified for this protocol.");
805 ports[i - p] = ta[i];
811 strcpy(ports, "0-65535");
818 if ((sss = strchr(ports, '-')) != NULL)
820 strncpy(port1, ports, int(sss-ports));
821 port1[int(sss - ports)] = 0;
822 strcpy(port2, sss + 1);
826 strcpy(port1, ports);
827 strcpy(port2, ports);
830 // Convert strings to mask, ports and IP
835 msk = strtol(mask, &res, 10);
839 prt1 = strtol(port1, &res, 10);
843 prt2 = strtol(port2, &res, 10);
847 int r = inet_aton(addr, (struct in_addr*)&ip);
852 rule->mask = CalcMask(msk);
854 //printfd(__FILE__, "msk=%d mask=%08X mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
856 if ((ip & rule->mask) != ip)
858 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
859 WriteServLog("Address does'n match mask.");
868 //-----------------------------------------------------------------------------
869 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
871 if (msk >= 32) return 0xFFffFFff;
872 if (msk == 0) return 0;
873 return htonl(0xFFffFFff << (32 - msk));
875 //---------------------------------------------------------------------------
876 void TRAFFCOUNTER_IMPL::FreeRules()
880 //-----------------------------------------------------------------------------
881 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
883 printf("%15s ", inet_ntostring(rule.ip).c_str());
884 printf("mask=%08X ", rule.mask);
885 printf("port1=%5d ", rule.port1);
886 printf("port2=%5d ", rule.port2);
905 printf("dir=%d \n", rule.dir);
908 //-----------------------------------------------------------------------------
909 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
911 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
912 monitoring = (monitorDir != "");
914 //-----------------------------------------------------------------------------