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)
62 : WriteServLog(GetStgLogger()),
65 touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
69 addUserNotifier(*this),
70 delUserNotifier(*this)
72 for (int i = 0; i < DIR_NUM; i++)
73 strprintf(&dirName[i], "DIR%d", i);
75 dirName[DIR_NUM] = "NULL";
77 users->AddNotifierUserAdd(&addUserNotifier);
78 users->AddNotifierUserDel(&delUserNotifier);
80 pthread_mutex_init(&mutex, NULL);
82 //-----------------------------------------------------------------------------
83 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
85 pthread_mutex_destroy(&mutex);
87 //-----------------------------------------------------------------------------
88 int TRAFFCOUNTER_IMPL::Start()
90 STG_LOCKER lock(&mutex);
97 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
98 WriteServLog("TRAFFCOUNTER: Cannot read rules.");
102 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
103 int h = users->OpenSearch();
104 assert(h && "USERS::OpenSearch is always correct");
107 while (users->SearchNext(h, &u) == 0)
109 users->CloseSearch(h);
112 if (pthread_create(&thread, NULL, Run, this))
114 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
115 WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
120 //-----------------------------------------------------------------------------
121 int TRAFFCOUNTER_IMPL::Stop()
128 int h = users->OpenSearch();
129 assert(h && "USERS::OpenSearch is always correct");
132 while (users->SearchNext(h, &u) == 0)
133 UnSetUserNotifiers(u);
134 users->CloseSearch(h);
136 //5 seconds to thread stops itself
137 struct timespec ts = {0, 200000000};
138 for (int i = 0; i < 25 && !stopped; i++)
140 nanosleep(&ts, NULL);
146 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
150 //-----------------------------------------------------------------------------
151 void * TRAFFCOUNTER_IMPL::Run(void * data)
154 sigfillset(&signalSet);
155 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
157 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
161 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
162 struct timespec ts = {0, 500000000};
168 tc->FlushAndRemove();
172 if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
174 std::string monFile(tc->monitorDir + "/traffcounter_r");
175 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
180 if (++c % FLUSH_TIME == 0)
181 tc->FlushAndRemove();
187 //-----------------------------------------------------------------------------
188 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
193 if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
195 std::string monFile = monitorDir + "/traffcounter_p";
196 printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
197 touchTimeP = stgTime;
201 STG_LOCKER lock(&mutex);
203 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
204 //TODO replace find with lower_bound.
206 // Searching a new packet in a tree.
207 pp_iter pi = packets.find(rawPacket);
209 // Packet found - update length and time
210 if (pi != packets.end())
212 pi->second.lenU += rawPacket.GetLen();
213 pi->second.lenD += rawPacket.GetLen();
214 pi->second.updateTime = stgTime;
215 /*printfd(__FILE__, "=============================\n");
216 printfd(__FILE__, "Packet found!\n");
217 printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
218 printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
219 printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
220 printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
221 printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
222 printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
223 printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
224 printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
225 printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
226 printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
227 printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
228 printfd(__FILE__, "=============================\n");*/
232 PACKET_EXTRA_DATA ed;
234 // Packet not found - add new packet
236 ed.updateTime = stgTime;
237 ed.flushTime = stgTime;
240 userU is that whose user_ip == packet_ip_src
241 userD is that whose user_ip == packet_ip_dst
244 uint32_t ipU = rawPacket.GetSrcIP();
245 uint32_t ipD = rawPacket.GetDstIP();
247 // Searching users with such IP
248 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
250 ed.userUPresent = true;
253 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
255 ed.userDPresent = true;
258 if (ed.userUPresent ||
261 DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
263 ed.lenD = ed.lenU = rawPacket.GetLen();
265 //TODO use result of lower_bound to inserting new record
267 // Adding packet to a tree.
268 std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
269 pp_iter newPacket = insertResult.first;
271 // Adding packet reference to an IP index.
272 ip2packets.insert(std::make_pair(ipU, newPacket));
273 ip2packets.insert(std::make_pair(ipD, newPacket));
276 //-----------------------------------------------------------------------------
277 void TRAFFCOUNTER_IMPL::FlushAndRemove()
279 STG_LOCKER lock(&mutex);
281 Packets::size_type oldPacketsSize = packets.size();
282 Index::size_type oldIp2packetsSize = ip2packets.size();
285 pi = packets.begin();
287 ip2packets.erase(ip2packets.begin(), ip2packets.end());
288 while (pi != packets.end())
291 if (stgTime - pi->second.flushTime > FLUSH_TIME)
293 if (pi->second.userUPresent)
295 //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);
298 if (pi->second.dirU < DIR_NUM)
300 #ifdef TRAFF_STAT_WITH_PORTS
301 pi->second.userU->AddTraffStatU(pi->second.dirU,
302 pi->first.GetDstIP(),
303 pi->first.GetDstPort(),
306 pi->second.userU->AddTraffStatU(pi->second.dirU,
307 pi->first.GetDstIP(),
313 pi->second.flushTime = stgTime;
316 if (pi->second.userDPresent)
318 //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);
321 if (pi->second.dirD < DIR_NUM)
323 #ifdef TRAFF_STAT_WITH_PORTS
324 pi->second.userD->AddTraffStatD(pi->second.dirD,
325 pi->first.GetSrcIP(),
326 pi->first.GetSrcPort(),
329 pi->second.userD->AddTraffStatD(pi->second.dirD,
330 pi->first.GetSrcIP(),
336 pi->second.flushTime = stgTime;
340 if (stgTime - pi->second.updateTime < REMOVE_TIME)
342 std::pair<pp_iter, bool> res = newPackets.insert(*pi);
345 ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
346 ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
351 swap(packets, newPackets);
352 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
354 oldPacketsSize - packets.size(),
356 oldIp2packetsSize - ip2packets.size());
359 //-----------------------------------------------------------------------------
360 void TRAFFCOUNTER_IMPL::AddUser(USER_IMPL * user)
362 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
363 uint32_t uip = user->GetCurrIP();
364 std::pair<ip2p_iter, ip2p_iter> pi;
366 STG_LOCKER lock(&mutex);
367 // Find all packets with IP belongs to this user
368 pi = ip2packets.equal_range(uip);
370 while (pi.first != pi.second)
372 if (pi.first->second->first.GetSrcIP() == uip)
374 assert((!pi.first->second->second.userUPresent ||
375 pi.first->second->second.userU == user) &&
376 "U user present but it's not current user");
378 pi.first->second->second.lenU = 0;
379 pi.first->second->second.userU = user;
380 pi.first->second->second.userUPresent = true;
383 if (pi.first->second->first.GetDstIP() == uip)
385 assert((!pi.first->second->second.userDPresent ||
386 pi.first->second->second.userD == user) &&
387 "D user present but it's not current user");
389 pi.first->second->second.lenD = 0;
390 pi.first->second->second.userD = user;
391 pi.first->second->second.userDPresent = true;
397 //-----------------------------------------------------------------------------
398 void TRAFFCOUNTER_IMPL::DelUser(uint32_t uip)
400 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
401 std::pair<ip2p_iter, ip2p_iter> pi;
403 STG_LOCKER lock(&mutex);
404 pi = ip2packets.equal_range(uip);
406 while (pi.first != pi.second)
408 if (pi.first->second->first.GetSrcIP() == uip)
410 if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
412 #ifdef TRAFF_STAT_WITH_PORTS
413 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
414 pi.first->second->first.GetDstIP(),
415 pi.first->second->first.GetDstPort(),
416 pi.first->second->second.lenU);
418 pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
419 pi.first->second->first.GetDstIP(),
420 pi.first->second->second.lenU);
423 pi.first->second->second.userUPresent = false;
426 if (pi.first->second->first.GetDstIP() == uip)
428 if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
430 #ifdef TRAFF_STAT_WITH_PORTS
431 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
432 pi.first->second->first.GetSrcIP(),
433 pi.first->second->first.GetSrcPort(),
434 pi.first->second->second.lenD);
436 pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
437 pi.first->second->first.GetSrcIP(),
438 pi.first->second->second.lenD);
442 pi.first->second->second.userDPresent = false;
448 ip2packets.erase(pi.first, pi.second);
450 //-----------------------------------------------------------------------------
451 void TRAFFCOUNTER_IMPL::SetUserNotifiers(USER_IMPL * user)
453 // Adding user. Adding notifiers to user.
454 TRF_IP_BEFORE ipBNotifier(*this, user);
455 ipBeforeNotifiers.push_front(ipBNotifier);
456 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
458 TRF_IP_AFTER ipANotifier(*this, user);
459 ipAfterNotifiers.push_front(ipANotifier);
460 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
462 //-----------------------------------------------------------------------------
463 void TRAFFCOUNTER_IMPL::UnSetUserNotifiers(USER_IMPL * user)
465 // Removing user. Removing notifiers from user.
466 std::list<TRF_IP_BEFORE>::iterator bi;
467 std::list<TRF_IP_AFTER>::iterator ai;
469 bi = ipBeforeNotifiers.begin();
470 while (bi != ipBeforeNotifiers.end())
472 if (user->GetLogin() == bi->GetUser()->GetLogin())
474 user->DelCurrIPBeforeNotifier(&(*bi));
475 ipBeforeNotifiers.erase(bi);
481 ai = ipAfterNotifiers.begin();
482 while (ai != ipAfterNotifiers.end())
484 if (user->GetLogin() == ai->GetUser()->GetLogin())
486 user->DelCurrIPAfterNotifier(&(*ai));
487 ipAfterNotifiers.erase(ai);
493 //-----------------------------------------------------------------------------
494 void TRAFFCOUNTER_IMPL::DeterminateDir(const RAW_PACKET & packet,
495 int * dirU, // Direction for incoming packet
496 int * dirD) const // Direction for outgoing packet
498 bool addrMatchU = false;
499 bool portMatchU = false;
500 bool addrMatchD = false;
501 bool portMatchD = false;
502 bool foundU = false; // Was rule for U found ?
503 bool foundD = false; // Was rule for D found ?
504 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
506 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
508 std::list<RULE>::const_iterator ln;
511 while (ln != rules.end())
524 portMatchU = (packet.GetProto() == ICMP_RPOTO);
528 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
529 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
533 if (packet.GetProto() == TCP_PROTO)
534 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
538 if (packet.GetProto() == UDP_PROTO)
539 portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
543 printfd(__FILE__, "Error! Incorrect rule!\n");
547 addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
549 if (!foundU && addrMatchU && portMatchU)
553 //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
569 portMatchD = (packet.GetProto() == ICMP_RPOTO);
573 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
574 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
578 if (packet.GetProto() == TCP_PROTO)
579 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
583 if (packet.GetProto() == UDP_PROTO)
584 portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
588 printfd(__FILE__, "Error! Incorrect rule!\n");
592 addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
594 if (!foundD && addrMatchD && portMatchD)
598 //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
603 } //while (ln != rules.end())
611 //-----------------------------------------------------------------------------
612 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
614 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
619 char tp[100]; // protocol
620 char ta[100]; // address
621 char td[100]; // target direction
624 f = fopen(rulesFileName.c_str(), "rt");
628 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
629 WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
633 while (fgets(str, 1023, f))
636 if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
641 r = sscanf(str,"%99s %99s %99s", tp, ta, td);
644 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
645 WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
653 for (uint8_t i = 0; i < PROTOMAX; i++)
655 if (strcasecmp(tp, protoName[i]) == 0)
659 for (uint32_t i = 0; i < DIR_NUM + 1; i++)
661 if (td == dirName[i])
665 if (rul.dir == 0xff || rul.proto == 0xff)
667 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
668 WriteServLog("Error in file %s. Line %d.",
669 rulesFileName.c_str(), lineNumber);
674 if (ParseAddress(ta, &rul) != 0)
676 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
677 WriteServLog("Error in file %s. Error in adress. Line %d.",
678 rulesFileName.c_str(), lineNumber);
683 rules.push_back(rul);
688 // Adding lastest rule: ALL 0.0.0.0/0 NULL
689 rul.dir = DIR_NUM; //NULL
690 rul.ip = 0; //0.0.0.0
697 rules.push_back(rul);
701 //-----------------------------------------------------------------------------
702 int TRAFFCOUNTER_IMPL::Reload()
704 STG_LOCKER lock(&mutex);
708 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
709 WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
715 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Reloaded rules successfully.\n");
716 WriteServLog("TRAFFCOUNTER: Reloaded rules successfully.");
719 //-----------------------------------------------------------------------------
720 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
722 char addr[50], mask[20], port1[20], port2[20], ports[40];
724 size_t len = strlen(ta);
727 memset(addr, 0, sizeof(addr));
728 for (i = 0; i < len; i++)
730 if (ta[i] == '/' || ta[i] == ':')
768 if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
770 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
771 WriteServLog("No ports specified for this protocol.");
776 ports[i - p] = ta[i];
782 strcpy(ports, "0-65535");
789 if ((sss = strchr(ports, '-')) != NULL)
791 strncpy(port1, ports, int(sss-ports));
792 port1[int(sss - ports)] = 0;
793 strcpy(port2, sss + 1);
797 strcpy(port1, ports);
798 strcpy(port2, ports);
801 // Convert strings to mask, ports and IP
802 uint16_t prt1, prt2, msk;
803 struct in_addr ipaddr;
806 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
810 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
814 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
818 int r = inet_aton(addr, &ipaddr);
822 rule->ip = ipaddr.s_addr;
823 rule->mask = CalcMask(msk);
825 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
827 printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
828 WriteServLog("Address does'n match mask.");
837 //-----------------------------------------------------------------------------
838 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
840 if (msk >= 32) return 0xFFffFFff;
841 if (msk == 0) return 0;
842 return htonl(0xFFffFFff << (32 - msk));
844 //---------------------------------------------------------------------------
845 void TRAFFCOUNTER_IMPL::FreeRules()
849 //-----------------------------------------------------------------------------
850 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir)
853 monitoring = !monitorDir.empty();
855 //-----------------------------------------------------------------------------