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