]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter_impl.cpp
Checkout submodules in GitHub Actions.
[stg.git] / projects / stargazer / traffcounter_impl.cpp
1 /*
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.
6  *
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.
11  *
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
15  */
16
17 /*
18  *    Date: 27.10.2002
19  */
20
21 /*
22  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
23  */
24
25 /*
26  $Revision: 1.58 $
27  $Date: 2010/11/03 11:28:07 $
28  $Author: faust $
29  */
30
31 /* inet_aton */
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36
37 #include <csignal>
38 #include <cassert>
39 #include <cstdio> // fopen and similar
40 #include <cstdlib> // strtol
41
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"
48
49 #define FLUSH_TIME  (10)
50 #define REMOVE_TIME  (31)
51
52 using STG::TraffCounterImpl;
53
54 const char protoName[PROTOMAX][8] =
55 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
56
57 enum protoNum
58 {
59 tcp = 0, udp, icmp, tcp_udp, all
60 };
61
62 //-----------------------------------------------------------------------------
63 TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn)
64     : WriteServLog(Logger::get()),
65       rulesFileName(fn),
66       monitoring(false),
67       touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
68       users(u),
69       stopped(true),
70       addUserNotifier(*this),
71       delUserNotifier(*this)
72 {
73 for (int i = 0; i < DIR_NUM; i++)
74     strprintf(&dirName[i], "DIR%d", i);
75
76 dirName[DIR_NUM] = "NULL";
77
78 users->AddNotifierUserAdd(&addUserNotifier);
79 users->AddNotifierUserDel(&delUserNotifier);
80 }
81 //-----------------------------------------------------------------------------
82 TraffCounterImpl::~TraffCounterImpl()
83 {
84 }
85 //-----------------------------------------------------------------------------
86 int TraffCounterImpl::Start()
87 {
88 std::lock_guard<std::mutex> lock(m_mutex);
89
90 if (!stopped)
91     return 0;
92
93 if (ReadRules())
94     {
95     printfd(__FILE__, "TraffCounterImpl::Start() - Cannot read rules\n");
96     WriteServLog("TraffCounter: Cannot read rules.");
97     return -1;
98     }
99
100 printfd(__FILE__, "TraffCounter::Start()\n");
101 int h = users->OpenSearch();
102 assert(h && "USERS::OpenSearch is always correct");
103 UserImpl * u;
104
105 while (users->SearchNext(h, &u) == 0)
106     SetUserNotifiers(u);
107 users->CloseSearch(h);
108
109 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
110 return 0;
111 }
112 //-----------------------------------------------------------------------------
113 int TraffCounterImpl::Stop()
114 {
115 if (stopped)
116     return 0;
117
118 m_thread.request_stop();
119
120 int h = users->OpenSearch();
121 assert(h && "USERS::OpenSearch is always correct");
122
123 UserImpl * u;
124 while (users->SearchNext(h, &u) == 0)
125     UnSetUserNotifiers(u);
126 users->CloseSearch(h);
127
128 //5 seconds to thread stops itself
129 struct timespec ts = {0, 200000000};
130 for (int i = 0; i < 25 && !stopped; i++)
131     nanosleep(&ts, NULL);
132
133 if (!stopped)
134 {
135     m_thread.detach();
136     return -1;
137 }
138
139 m_thread.join();
140
141 printfd(__FILE__, "TraffCounter::Stop()\n");
142
143 return 0;
144 }
145 //-----------------------------------------------------------------------------
146 void TraffCounterImpl::Run(std::stop_token token)
147 {
148 sigset_t signalSet;
149 sigfillset(&signalSet);
150 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
151
152 stopped = false;
153 int c = 0;
154
155 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
156 struct timespec ts = {0, 500000000};
157 while (!token.stop_requested())
158     {
159     nanosleep(&ts, 0);
160     if (token.stop_requested())
161         {
162         FlushAndRemove();
163         break;
164         }
165
166     if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
167         {
168         std::string monFile(monitorDir + "/traffcounter_r");
169         printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
170         touchTime = stgTime;
171         TouchFile(monFile);
172         }
173
174     if (++c % FLUSH_TIME == 0)
175         FlushAndRemove();
176     }
177
178 stopped = true;
179 }
180 //-----------------------------------------------------------------------------
181 void TraffCounterImpl::process(const RawPacket & rawPacket)
182 {
183 if (monitoring && (touchTimeP + MONITOR_TIME_DELAY_SEC <= stgTime))
184     {
185     std::string monFile = monitorDir + "/traffcounter_p";
186     printfd(__FILE__, "Monitor=%d file TraffCounter %s\n", monitoring, monFile.c_str());
187     touchTimeP = stgTime;
188     TouchFile(monFile);
189     }
190
191 std::lock_guard<std::mutex> lock(m_mutex);
192
193 //printfd(__FILE__, "TraffCounter::Process()\n");
194 //TODO replace find with lower_bound.
195
196 // Searching a new packet in a tree.
197 pp_iter pi = packets.find(rawPacket);
198
199 // Packet found - update length and time
200 if (pi != packets.end())
201     {
202     pi->second.lenU += rawPacket.GetLen();
203     pi->second.lenD += rawPacket.GetLen();
204     pi->second.updateTime = stgTime;
205     /*printfd(__FILE__, "=============================\n");
206     printfd(__FILE__, "Packet found!\n");
207     printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
208     printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
209     printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
210     printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
211     printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
212     printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
213     printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
214     printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
215     printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
216     printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
217     printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
218     printfd(__FILE__, "=============================\n");*/
219     return;
220     }
221
222 PacketExtraData ed;
223
224 // Packet not found - add new packet
225
226 ed.updateTime = stgTime;
227 ed.flushTime = stgTime;
228
229 /*
230  userU is that whose user_ip == packet_ip_src
231  userD is that whose user_ip == packet_ip_dst
232  */
233
234 uint32_t ipU = rawPacket.GetSrcIP();
235 uint32_t ipD = rawPacket.GetDstIP();
236
237 // Searching users with such IP
238 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
239     {
240     ed.userUPresent = true;
241     }
242
243 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
244     {
245     ed.userDPresent = true;
246     }
247
248 if (ed.userUPresent ||
249     ed.userDPresent)
250     {
251     DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
252
253     ed.lenD = ed.lenU = rawPacket.GetLen();
254
255     //TODO use result of lower_bound to inserting new record
256
257     // Adding packet to a tree.
258     std::pair<pp_iter, bool> insertResult = packets.insert(std::make_pair(rawPacket, ed));
259     pp_iter newPacket = insertResult.first;
260
261     // Adding packet reference to an IP index.
262     ip2packets.insert(std::make_pair(ipU, newPacket));
263     ip2packets.insert(std::make_pair(ipD, newPacket));
264     }
265 }
266 //-----------------------------------------------------------------------------
267 void TraffCounterImpl::FlushAndRemove()
268 {
269 std::lock_guard<std::mutex> lock(m_mutex);
270
271 Packets::size_type oldPacketsSize = packets.size();
272 Index::size_type oldIp2packetsSize = ip2packets.size();
273
274 pp_iter pi;
275 pi = packets.begin();
276 Packets newPackets;
277 ip2packets.erase(ip2packets.begin(), ip2packets.end());
278 while (pi != packets.end())
279     {
280     //Flushing
281     if (stgTime - pi->second.flushTime > FLUSH_TIME)
282         {
283         if (pi->second.userUPresent)
284             {
285             //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);
286
287             // Add stat
288             if (pi->second.dirU < DIR_NUM)
289                 {
290                 #ifdef TRAFF_STAT_WITH_PORTS
291                 pi->second.userU->AddTraffStatU(pi->second.dirU,
292                                                 pi->first.GetDstIP(),
293                                                 pi->first.GetDstPort(),
294                                                 pi->second.lenU);
295                 #else
296                 pi->second.userU->AddTraffStatU(pi->second.dirU,
297                                                 pi->first.GetDstIP(),
298                                                 pi->second.lenU);
299                 #endif
300                 }
301
302             pi->second.lenU = 0;
303             pi->second.flushTime = stgTime;
304             }
305
306         if (pi->second.userDPresent)
307             {
308             //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);
309
310             // Add stat
311             if (pi->second.dirD < DIR_NUM)
312                 {
313                 #ifdef TRAFF_STAT_WITH_PORTS
314                 pi->second.userD->AddTraffStatD(pi->second.dirD,
315                                                 pi->first.GetSrcIP(),
316                                                 pi->first.GetSrcPort(),
317                                                 pi->second.lenD);
318                 #else
319                 pi->second.userD->AddTraffStatD(pi->second.dirD,
320                                                 pi->first.GetSrcIP(),
321                                                 pi->second.lenD);
322                 #endif
323                 }
324
325             pi->second.lenD = 0;
326             pi->second.flushTime = stgTime;
327             }
328         }
329
330     if (stgTime - pi->second.updateTime < REMOVE_TIME)
331         {
332         std::pair<pp_iter, bool> res = newPackets.insert(*pi);
333         if (res.second)
334             {
335             ip2packets.insert(std::make_pair(pi->first.GetSrcIP(), res.first));
336             ip2packets.insert(std::make_pair(pi->first.GetDstIP(), res.first));
337             }
338         }
339     ++pi;
340     }
341 swap(packets, newPackets);
342 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
343         packets.size(),
344         oldPacketsSize - packets.size(),
345         ip2packets.size(),
346         oldIp2packetsSize - ip2packets.size());
347
348 }
349 //-----------------------------------------------------------------------------
350 void TraffCounterImpl::AddUser(UserImpl * user)
351 {
352 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
353 uint32_t uip = user->GetCurrIP();
354 std::pair<ip2p_iter, ip2p_iter> pi;
355
356 std::lock_guard<std::mutex> lock(m_mutex);
357 // Find all packets with IP belongs to this user
358 pi = ip2packets.equal_range(uip);
359
360 while (pi.first != pi.second)
361     {
362     if (pi.first->second->first.GetSrcIP() == uip)
363         {
364         assert((!pi.first->second->second.userUPresent ||
365                  pi.first->second->second.userU == user) &&
366                "U user present but it's not current user");
367
368         pi.first->second->second.lenU = 0;
369         pi.first->second->second.userU = user;
370         pi.first->second->second.userUPresent = true;
371         }
372
373     if (pi.first->second->first.GetDstIP() == uip)
374         {
375         assert((!pi.first->second->second.userDPresent ||
376                  pi.first->second->second.userD == user) &&
377                "D user present but it's not current user");
378
379         pi.first->second->second.lenD = 0;
380         pi.first->second->second.userD = user;
381         pi.first->second->second.userDPresent = true;
382         }
383
384     ++pi.first;
385     }
386 }
387 //-----------------------------------------------------------------------------
388 void TraffCounterImpl::DelUser(uint32_t uip)
389 {
390 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
391 std::pair<ip2p_iter, ip2p_iter> pi;
392
393 std::lock_guard<std::mutex> lock(m_mutex);
394 pi = ip2packets.equal_range(uip);
395
396 while (pi.first != pi.second)
397     {
398     if (pi.first->second->first.GetSrcIP() == uip)
399         {
400         if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
401             {
402             #ifdef TRAFF_STAT_WITH_PORTS
403             pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
404                                                           pi.first->second->first.GetDstIP(),
405                                                           pi.first->second->first.GetDstPort(),
406                                                           pi.first->second->second.lenU);
407             #else
408             pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
409                                                           pi.first->second->first.GetDstIP(),
410                                                           pi.first->second->second.lenU);
411             #endif
412             }
413         pi.first->second->second.userUPresent = false;
414         }
415
416     if (pi.first->second->first.GetDstIP() == uip)
417         {
418         if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
419             {
420             #ifdef TRAFF_STAT_WITH_PORTS
421             pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
422                                                           pi.first->second->first.GetSrcIP(),
423                                                           pi.first->second->first.GetSrcPort(),
424                                                           pi.first->second->second.lenD);
425             #else
426             pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
427                                                           pi.first->second->first.GetSrcIP(),
428                                                           pi.first->second->second.lenD);
429             #endif
430             }
431
432         pi.first->second->second.userDPresent = false;
433         }
434
435     ++pi.first;
436     }
437
438 ip2packets.erase(pi.first, pi.second);
439 }
440 //-----------------------------------------------------------------------------
441 void TraffCounterImpl::SetUserNotifiers(UserImpl * user)
442 {
443 // Adding user. Adding notifiers to user.
444 TRF_IP_BEFORE ipBNotifier(*this, user);
445 ipBeforeNotifiers.push_front(ipBNotifier);
446 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
447
448 TRF_IP_AFTER ipANotifier(*this, user);
449 ipAfterNotifiers.push_front(ipANotifier);
450 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
451 }
452 //-----------------------------------------------------------------------------
453 void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user)
454 {
455 // Removing user. Removing notifiers from user.
456 std::list<TRF_IP_BEFORE>::iterator bi;
457 std::list<TRF_IP_AFTER>::iterator ai;
458
459 bi = ipBeforeNotifiers.begin();
460 while (bi != ipBeforeNotifiers.end())
461     {
462     if (user->GetLogin() == bi->GetUser()->GetLogin())
463         {
464         user->DelCurrIPBeforeNotifier(&(*bi));
465         ipBeforeNotifiers.erase(bi);
466         break;
467         }
468     ++bi;
469     }
470
471 ai = ipAfterNotifiers.begin();
472 while (ai != ipAfterNotifiers.end())
473     {
474     if (user->GetLogin() == ai->GetUser()->GetLogin())
475         {
476         user->DelCurrIPAfterNotifier(&(*ai));
477         ipAfterNotifiers.erase(ai);
478         break;
479         }
480     ++ai;
481     }
482 }
483 //-----------------------------------------------------------------------------
484 void TraffCounterImpl::DeterminateDir(const RawPacket & packet,
485                                        int * dirU, // Direction for incoming packet
486                                        int * dirD) const // Direction for outgoing packet
487 {
488 bool addrMatchU = false;
489 bool portMatchU = false;
490 bool addrMatchD = false;
491 bool portMatchD = false;
492 bool foundU = false; // Was rule for U found ?
493 bool foundD = false; // Was rule for D found ?
494 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
495
496 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
497
498 std::list<Rule>::const_iterator ln;
499 ln = rules.begin();
500
501 while (ln != rules.end())
502     {
503     if (!foundU)
504         {
505         portMatchU = false;
506
507         switch (ln->proto)
508             {
509             case all:
510                 portMatchU = true;
511                 break;
512
513             case icmp:
514                 portMatchU = (packet.GetProto() == ICMP_RPOTO);
515                 break;
516
517             case tcp_udp:
518                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
519                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
520                 break;
521
522             case tcp:
523                 if (packet.GetProto() == TCP_PROTO)
524                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
525                 break;
526
527             case udp:
528                 if (packet.GetProto() == UDP_PROTO)
529                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
530                 break;
531
532             default:
533                 printfd(__FILE__, "Error! Incorrect rule!\n");
534                 break;
535             }
536
537         addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
538
539         if (!foundU && addrMatchU && portMatchU)
540             {
541             foundU = true;
542             *dirU = ln->dir;
543             //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
544             }
545
546         } //if (!foundU)
547
548     if (!foundD)
549         {
550         portMatchD = false;
551
552         switch (ln->proto)
553             {
554             case all:
555                 portMatchD = true;
556                 break;
557
558             case icmp:
559                 portMatchD = (packet.GetProto() == ICMP_RPOTO);
560                 break;
561
562             case tcp_udp:
563                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
564                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
565                 break;
566
567             case tcp:
568                 if (packet.GetProto() == TCP_PROTO)
569                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
570                 break;
571
572             case udp:
573                 if (packet.GetProto() == UDP_PROTO)
574                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
575                 break;
576
577             default:
578                 printfd(__FILE__, "Error! Incorrect rule!\n");
579                 break;
580             }
581
582         addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
583
584         if (!foundD && addrMatchD && portMatchD)
585             {
586             foundD = true;
587             *dirD = ln->dir;
588             //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
589             }
590         } //if (!foundD)
591
592     ++ln;
593     }   //while (ln != rules.end())
594
595 if (!foundU)
596     *dirU = DIR_NUM;
597
598 if (!foundD)
599     *dirD = DIR_NUM;
600 }
601 //-----------------------------------------------------------------------------
602 bool TraffCounterImpl::ReadRules(bool test)
603 {
604 //printfd(__FILE__, "TraffCounter::ReadRules()\n");
605
606 Rule rul;
607 FILE * f;
608 char str[1024];
609 char tp[100];   // protocol
610 char ta[100];   // address
611 char td[100];   // target direction
612 int r;
613 int lineNumber = 0;
614 f = fopen(rulesFileName.c_str(), "rt");
615
616 if (!f)
617     {
618     printfd(__FILE__, "TraffCounterImpl::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
619     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
620     return true;
621     }
622
623 while (fgets(str, 1023, f))
624     {
625     lineNumber++;
626     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
627         {
628         continue;
629         }
630
631     r = sscanf(str,"%99s %99s %99s", tp, ta, td);
632     if (r != 3)
633         {
634         printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
635         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
636         fclose(f);
637         return true;
638         }
639
640     rul.proto = 0xff;
641     rul.dir = 0xff;
642
643     for (uint8_t i = 0; i < PROTOMAX; i++)
644         {
645         if (strcasecmp(tp, protoName[i]) == 0)
646             rul.proto = i;
647         }
648
649     for (uint32_t i = 0; i < DIR_NUM + 1; i++)
650         {
651         if (td == dirName[i])
652             rul.dir = i;
653         }
654
655     if (rul.dir == 0xff || rul.proto == 0xff)
656         {
657         printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
658         WriteServLog("Error in file %s. Line %d.",
659                      rulesFileName.c_str(), lineNumber);
660         fclose(f);
661         return true;
662         }
663
664     if (ParseAddress(ta, &rul) != 0)
665         {
666         printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
667         WriteServLog("Error in file %s. Error in adress. Line %d.",
668                      rulesFileName.c_str(), lineNumber);
669         fclose(f);
670         return true;
671         }
672     if (!test)
673         rules.push_back(rul);
674     }
675
676 fclose(f);
677
678 // Adding lastest rule: ALL 0.0.0.0/0 NULL
679 rul.dir = DIR_NUM; //NULL
680 rul.ip = 0;  //0.0.0.0
681 rul.mask = 0;
682 rul.port1 = 0;
683 rul.port2 = 65535;
684 rul.proto = all;
685
686 if (!test)
687     rules.push_back(rul);
688
689 return false;
690 }
691 //-----------------------------------------------------------------------------
692 int TraffCounterImpl::Reload()
693 {
694 std::lock_guard<std::mutex> lock(m_mutex);
695
696 if (ReadRules(true))
697     {
698     printfd(__FILE__, "TraffCounterImpl::Reload() - Failed to reload rules.\n");
699     WriteServLog("TraffCounter: Cannot reload rules. Errors found.");
700     return -1;
701     }
702
703 FreeRules();
704 ReadRules();
705 printfd(__FILE__, "TraffCounterImpl::Reload() -  Reloaded rules successfully.\n");
706 WriteServLog("TraffCounter: Reloaded rules successfully.");
707 return 0;
708 }
709 //-----------------------------------------------------------------------------
710 bool TraffCounterImpl::ParseAddress(const char * ta, Rule * rule) const
711 {
712 char addr[50], mask[20], port1[20], port2[20], ports[40];
713
714 size_t len = strlen(ta);
715 char n = 0;
716 size_t i, p;
717 memset(addr, 0, sizeof(addr));
718 for (i = 0; i < len; i++)
719     {
720     if (ta[i] == '/' || ta[i] == ':')
721         {
722         addr[i] = 0;
723         n = ta[i];
724         break;
725         }
726     addr[i] = ta[i];
727     n = 0;
728     }
729 addr[i + 1] = 0;
730 p = i + 1;
731
732 if (n == '/')
733     {
734     // mask
735     for (; i < len; i++)
736         {
737         if (ta[i] == ':')
738             {
739             mask[i - p] = 0;
740             n = ':';
741             break;
742             }
743         mask[i - p] = ta[i];
744         }
745     mask[i - p] = 0;
746     }
747 else
748     {
749     strcpy(mask, "32");
750     }
751
752 p = i + 1;
753 i++;
754
755 if (n == ':')
756     {
757     // port
758     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
759         {
760         printfd(__FILE__, "TraffCounterImpl::ParseAddress() - No ports specified for this protocol.\n");
761         WriteServLog("No ports specified for this protocol.");
762         return true;
763         }
764
765     for (; i < len; i++)
766         ports[i - p] = ta[i];
767
768     ports[i - p] = 0;
769     }
770 else
771     {
772     strcpy(ports, "0-65535");
773     }
774
775 char *sss;
776 char pts[100];
777 strcpy(pts, ports);
778
779 if ((sss = strchr(ports, '-')) != NULL)
780     {
781     strncpy(port1, ports, int(sss-ports));
782     port1[int(sss - ports)] = 0;
783     strcpy(port2, sss + 1);
784     }
785 else
786     {
787     strcpy(port1, ports);
788     strcpy(port2, ports);
789     }
790
791 // Convert strings to mask, ports and IP
792 uint16_t prt1, prt2, msk;
793 struct in_addr ipaddr;
794 char *res;
795
796 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
797 if (*res != 0)
798     return true;
799
800 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
801 if (*res != 0)
802     return true;
803
804 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
805 if (*res != 0)
806     return true;
807
808 int r = inet_aton(addr, &ipaddr);
809 if (r == 0)
810     return true;
811
812 rule->ip = ipaddr.s_addr;
813 rule->mask = CalcMask(msk);
814
815 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
816     {
817     printfd(__FILE__, "TraffCounterImpl::ParseAddress() - Address does'n match mask.\n");
818     WriteServLog("Address does'n match mask.");
819     return true;
820     }
821
822 rule->port1 = prt1;
823 rule->port2 = prt2;
824
825 return false;
826 }
827 //-----------------------------------------------------------------------------
828 uint32_t TraffCounterImpl::CalcMask(uint32_t msk) const
829 {
830 if (msk >= 32) return 0xFFffFFff;
831 if (msk == 0) return 0;
832 return htonl(0xFFffFFff << (32 - msk));
833 }
834 //---------------------------------------------------------------------------
835 void TraffCounterImpl::FreeRules()
836 {
837 rules.clear();
838 }
839 //-----------------------------------------------------------------------------
840 void TraffCounterImpl::SetMonitorDir(const std::string & dir)
841 {
842 monitorDir = dir;
843 monitoring = !monitorDir.empty();
844 }
845 //-----------------------------------------------------------------------------