]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter_impl.cpp
More std::jthread stuff.
[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
55 namespace AsyncPoolST = STG::AsyncPoolST;
56
57 const char protoName[PROTOMAX][8] =
58 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
59
60 enum protoNum
61 {
62 tcp = 0, udp, icmp, tcp_udp, all
63 };
64
65 //-----------------------------------------------------------------------------
66 TraffCounterImpl::TraffCounterImpl(UsersImpl * u, const std::string & fn)
67     : WriteServLog(Logger::get()),
68       rulesFileName(fn),
69       monitoring(false),
70       touchTimeP(stgTime - MONITOR_TIME_DELAY_SEC),
71       users(u),
72       stopped(true)
73 {
74 for (int i = 0; i < DIR_NUM; i++)
75     strprintf(&dirName[i], "DIR%d", i);
76
77 dirName[DIR_NUM] = "NULL";
78
79 m_onAddUserConn = users->onImplAdd([this](auto user){
80     AsyncPoolST::enqueue([this, user](){ SetUserNotifiers(user); });
81 });
82 m_onDelUserConn = users->onImplDel([this](auto user){
83     AsyncPoolST::enqueue([this, user](){ UnSetUserNotifiers(user); DelUser(user->GetCurrIP()); });
84 });
85 }
86 //-----------------------------------------------------------------------------
87 TraffCounterImpl::~TraffCounterImpl()
88 {
89 }
90 //-----------------------------------------------------------------------------
91 int TraffCounterImpl::Start()
92 {
93 std::lock_guard<std::mutex> lock(m_mutex);
94
95 if (!stopped)
96     return 0;
97
98 if (ReadRules())
99     {
100     printfd(__FILE__, "TraffCounterImpl::Start() - Cannot read rules\n");
101     WriteServLog("TraffCounter: Cannot read rules.");
102     return -1;
103     }
104
105 printfd(__FILE__, "TraffCounter::Start()\n");
106 int h = users->OpenSearch();
107 assert(h && "USERS::OpenSearch is always correct");
108 UserImpl * u;
109
110 while (users->SearchNext(h, &u) == 0)
111     SetUserNotifiers(u);
112 users->CloseSearch(h);
113
114 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
115 return 0;
116 }
117 //-----------------------------------------------------------------------------
118 int TraffCounterImpl::Stop()
119 {
120 if (stopped)
121     return 0;
122
123 m_thread.request_stop();
124
125 int h = users->OpenSearch();
126 assert(h && "USERS::OpenSearch is always correct");
127
128 m_onIPConns.clear();
129
130 //5 seconds to thread stops itself
131 for (int i = 0; i < 25 && !stopped; i++)
132     std::this_thread::sleep_for(std::chrono::milliseconds(200));
133
134 if (!stopped)
135 {
136     m_thread.detach();
137     return -1;
138 }
139
140 m_thread.join();
141
142 printfd(__FILE__, "TraffCounter::Stop()\n");
143
144 return 0;
145 }
146 //-----------------------------------------------------------------------------
147 void TraffCounterImpl::Run(std::stop_token token)
148 {
149 sigset_t signalSet;
150 sigfillset(&signalSet);
151 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
152
153 stopped = false;
154 int c = 0;
155
156 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
157 while (!token.stop_requested())
158     {
159     std::this_thread::sleep_for(std::chrono::milliseconds(500));
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     m_onIPConns.emplace_back(
445         user->GetID(),
446         user->beforeCurrIPChange([this](auto oldVal, auto /*newVal*/){ beforeIPChange(oldVal); }),
447         user->afterCurrIPChange([this, user](auto /*oldVal*/, auto newVal){ afterIPChange(user, newVal); })
448     );
449 }
450 //-----------------------------------------------------------------------------
451 void TraffCounterImpl::UnSetUserNotifiers(UserImpl * user)
452 {
453     // Removing user. Removing notifiers from user.
454     m_onIPConns.erase(std::remove_if(m_onIPConns.begin(), m_onIPConns.end(),
455                                      [user](const auto& cs){ return std::get<0>(cs) == user->GetID(); }),
456                       m_onIPConns.end());
457 }
458 //-----------------------------------------------------------------------------
459 void TraffCounterImpl::DeterminateDir(const RawPacket & packet,
460                                        int * dirU, // Direction for incoming packet
461                                        int * dirD) const // Direction for outgoing packet
462 {
463 bool addrMatchU = false;
464 bool portMatchU = false;
465 bool addrMatchD = false;
466 bool portMatchD = false;
467 bool foundU = false; // Was rule for U found ?
468 bool foundD = false; // Was rule for D found ?
469 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
470
471 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
472
473 std::list<Rule>::const_iterator ln;
474 ln = rules.begin();
475
476 while (ln != rules.end())
477     {
478     if (!foundU)
479         {
480         portMatchU = false;
481
482         switch (ln->proto)
483             {
484             case all:
485                 portMatchU = true;
486                 break;
487
488             case icmp:
489                 portMatchU = (packet.GetProto() == ICMP_RPOTO);
490                 break;
491
492             case tcp_udp:
493                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
494                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
495                 break;
496
497             case tcp:
498                 if (packet.GetProto() == TCP_PROTO)
499                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
500                 break;
501
502             case udp:
503                 if (packet.GetProto() == UDP_PROTO)
504                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
505                 break;
506
507             default:
508                 printfd(__FILE__, "Error! Incorrect rule!\n");
509                 break;
510             }
511
512         addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
513
514         if (!foundU && addrMatchU && portMatchU)
515             {
516             foundU = true;
517             *dirU = ln->dir;
518             //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
519             }
520
521         } //if (!foundU)
522
523     if (!foundD)
524         {
525         portMatchD = false;
526
527         switch (ln->proto)
528             {
529             case all:
530                 portMatchD = true;
531                 break;
532
533             case icmp:
534                 portMatchD = (packet.GetProto() == ICMP_RPOTO);
535                 break;
536
537             case tcp_udp:
538                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
539                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
540                 break;
541
542             case tcp:
543                 if (packet.GetProto() == TCP_PROTO)
544                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
545                 break;
546
547             case udp:
548                 if (packet.GetProto() == UDP_PROTO)
549                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
550                 break;
551
552             default:
553                 printfd(__FILE__, "Error! Incorrect rule!\n");
554                 break;
555             }
556
557         addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
558
559         if (!foundD && addrMatchD && portMatchD)
560             {
561             foundD = true;
562             *dirD = ln->dir;
563             //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
564             }
565         } //if (!foundD)
566
567     ++ln;
568     }   //while (ln != rules.end())
569
570 if (!foundU)
571     *dirU = DIR_NUM;
572
573 if (!foundD)
574     *dirD = DIR_NUM;
575 }
576 //-----------------------------------------------------------------------------
577 bool TraffCounterImpl::ReadRules(bool test)
578 {
579 //printfd(__FILE__, "TraffCounter::ReadRules()\n");
580
581 Rule rul;
582 FILE * f;
583 char str[1024];
584 char tp[100];   // protocol
585 char ta[100];   // address
586 char td[100];   // target direction
587 int r;
588 int lineNumber = 0;
589 f = fopen(rulesFileName.c_str(), "rt");
590
591 if (!f)
592     {
593     printfd(__FILE__, "TraffCounterImpl::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
594     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
595     return true;
596     }
597
598 while (fgets(str, 1023, f))
599     {
600     lineNumber++;
601     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
602         {
603         continue;
604         }
605
606     r = sscanf(str,"%99s %99s %99s", tp, ta, td);
607     if (r != 3)
608         {
609         printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
610         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
611         fclose(f);
612         return true;
613         }
614
615     rul.proto = 0xff;
616     rul.dir = 0xff;
617
618     for (uint8_t i = 0; i < PROTOMAX; i++)
619         {
620         if (strcasecmp(tp, protoName[i]) == 0)
621             rul.proto = i;
622         }
623
624     for (uint32_t i = 0; i < DIR_NUM + 1; i++)
625         {
626         if (td == dirName[i])
627             rul.dir = i;
628         }
629
630     if (rul.dir == 0xff || rul.proto == 0xff)
631         {
632         printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
633         WriteServLog("Error in file %s. Line %d.",
634                      rulesFileName.c_str(), lineNumber);
635         fclose(f);
636         return true;
637         }
638
639     if (ParseAddress(ta, &rul) != 0)
640         {
641         printfd(__FILE__, "TraffCounterImpl::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
642         WriteServLog("Error in file %s. Error in adress. Line %d.",
643                      rulesFileName.c_str(), lineNumber);
644         fclose(f);
645         return true;
646         }
647     if (!test)
648         rules.push_back(rul);
649     }
650
651 fclose(f);
652
653 // Adding lastest rule: ALL 0.0.0.0/0 NULL
654 rul.dir = DIR_NUM; //NULL
655 rul.ip = 0;  //0.0.0.0
656 rul.mask = 0;
657 rul.port1 = 0;
658 rul.port2 = 65535;
659 rul.proto = all;
660
661 if (!test)
662     rules.push_back(rul);
663
664 return false;
665 }
666 //-----------------------------------------------------------------------------
667 int TraffCounterImpl::Reload()
668 {
669 std::lock_guard<std::mutex> lock(m_mutex);
670
671 if (ReadRules(true))
672     {
673     printfd(__FILE__, "TraffCounterImpl::Reload() - Failed to reload rules.\n");
674     WriteServLog("TraffCounter: Cannot reload rules. Errors found.");
675     return -1;
676     }
677
678 FreeRules();
679 ReadRules();
680 printfd(__FILE__, "TraffCounterImpl::Reload() -  Reloaded rules successfully.\n");
681 WriteServLog("TraffCounter: Reloaded rules successfully.");
682 return 0;
683 }
684 //-----------------------------------------------------------------------------
685 bool TraffCounterImpl::ParseAddress(const char * ta, Rule * rule) const
686 {
687 char addr[50], mask[20], port1[20], port2[20], ports[40];
688
689 size_t len = strlen(ta);
690 char n = 0;
691 size_t i, p;
692 memset(addr, 0, sizeof(addr));
693 for (i = 0; i < len; i++)
694     {
695     if (ta[i] == '/' || ta[i] == ':')
696         {
697         addr[i] = 0;
698         n = ta[i];
699         break;
700         }
701     addr[i] = ta[i];
702     n = 0;
703     }
704 addr[i + 1] = 0;
705 p = i + 1;
706
707 if (n == '/')
708     {
709     // mask
710     for (; i < len; i++)
711         {
712         if (ta[i] == ':')
713             {
714             mask[i - p] = 0;
715             n = ':';
716             break;
717             }
718         mask[i - p] = ta[i];
719         }
720     mask[i - p] = 0;
721     }
722 else
723     {
724     strcpy(mask, "32");
725     }
726
727 p = i + 1;
728 i++;
729
730 if (n == ':')
731     {
732     // port
733     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
734         {
735         printfd(__FILE__, "TraffCounterImpl::ParseAddress() - No ports specified for this protocol.\n");
736         WriteServLog("No ports specified for this protocol.");
737         return true;
738         }
739
740     for (; i < len; i++)
741         ports[i - p] = ta[i];
742
743     ports[i - p] = 0;
744     }
745 else
746     {
747     strcpy(ports, "0-65535");
748     }
749
750 char *sss;
751 char pts[100];
752 strcpy(pts, ports);
753
754 if ((sss = strchr(ports, '-')) != NULL)
755     {
756     strncpy(port1, ports, int(sss-ports));
757     port1[int(sss - ports)] = 0;
758     strcpy(port2, sss + 1);
759     }
760 else
761     {
762     strcpy(port1, ports);
763     strcpy(port2, ports);
764     }
765
766 // Convert strings to mask, ports and IP
767 uint16_t prt1, prt2, msk;
768 struct in_addr ipaddr;
769 char *res;
770
771 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
772 if (*res != 0)
773     return true;
774
775 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
776 if (*res != 0)
777     return true;
778
779 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
780 if (*res != 0)
781     return true;
782
783 int r = inet_aton(addr, &ipaddr);
784 if (r == 0)
785     return true;
786
787 rule->ip = ipaddr.s_addr;
788 rule->mask = CalcMask(msk);
789
790 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
791     {
792     printfd(__FILE__, "TraffCounterImpl::ParseAddress() - Address does'n match mask.\n");
793     WriteServLog("Address does'n match mask.");
794     return true;
795     }
796
797 rule->port1 = prt1;
798 rule->port2 = prt2;
799
800 return false;
801 }
802 //-----------------------------------------------------------------------------
803 uint32_t TraffCounterImpl::CalcMask(uint32_t msk) const
804 {
805 if (msk >= 32) return 0xFFffFFff;
806 if (msk == 0) return 0;
807 return htonl(0xFFffFFff << (32 - msk));
808 }
809 //---------------------------------------------------------------------------
810 void TraffCounterImpl::FreeRules()
811 {
812 rules.clear();
813 }
814 //-----------------------------------------------------------------------------
815 void TraffCounterImpl::SetMonitorDir(const std::string & dir)
816 {
817 monitorDir = dir;
818 monitoring = !monitorDir.empty();
819 }
820 //-----------------------------------------------------------------------------
821 void TraffCounterImpl::beforeIPChange(uint32_t oldVal)
822 {
823     // User changes his address. Remove old IP
824     if (!oldVal)
825         return;
826
827     AsyncPoolST::enqueue([this, oldVal](){ DelUser(oldVal); });
828 }
829 //-----------------------------------------------------------------------------
830 void TraffCounterImpl::afterIPChange(UserImpl* user, uint32_t newVal)
831 {
832     // User changes his address. Add new IP
833     if (!newVal)
834         return;
835
836     AsyncPoolST::enqueue([this, user](){ AddUser(user); });
837 }
838 //-----------------------------------------------------------------------------