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