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