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