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