]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter_impl.cpp
Uniform error reporting for services managment.
[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.c_str());
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.c_str());
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;
513 bool portMatchU;
514 bool addrMatchD;
515 bool portMatchD;
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         addrMatchU = false;
530         portMatchU = false;
531
532         switch (ln->proto)
533             {
534             case all:
535                 portMatchU = true;
536                 break;
537
538             case icmp:
539                 portMatchU = (packet.GetProto() == ICMP_RPOTO);
540                 break;
541
542             case tcp_udp:
543                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
544                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
545                 break;
546
547             case tcp:
548                 if (packet.GetProto() == TCP_PROTO)
549                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
550                 break;
551
552             case udp:
553                 if (packet.GetProto() == UDP_PROTO)
554                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
555                 break;
556
557             default:
558                 printfd(__FILE__, "Error! Incorrect rule!\n");
559                 break;
560             }
561
562         addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
563
564         if (!foundU && addrMatchU && portMatchU)
565             {
566             foundU = true;
567             *dirU = ln->dir;
568             //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
569             }
570
571         } //if (!foundU)
572
573     if (!foundD)
574         {
575         addrMatchD = false;
576         portMatchD = false;
577
578         switch (ln->proto)
579             {
580             case all:
581                 portMatchD = true;
582                 break;
583
584             case icmp:
585                 portMatchD = (packet.GetProto() == ICMP_RPOTO);
586                 break;
587
588             case tcp_udp:
589                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
590                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
591                 break;
592
593             case tcp:
594                 if (packet.GetProto() == TCP_PROTO)
595                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
596                 break;
597
598             case udp:
599                 if (packet.GetProto() == UDP_PROTO)
600                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
601                 break;
602
603             default:
604                 printfd(__FILE__, "Error! Incorrect rule!\n");
605                 break;
606             }
607
608         addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
609
610         if (!foundD && addrMatchD && portMatchD)
611             {
612             foundD = true;
613             *dirD = ln->dir;
614             //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
615             }
616         } //if (!foundD)
617
618     ++ln;
619     }   //while (ln != rules.end())
620
621 if (!foundU)
622     *dirU = DIR_NUM;
623
624 if (!foundD)
625     *dirD = DIR_NUM;
626 }
627 //-----------------------------------------------------------------------------
628 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
629 {
630 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
631
632 RULE rul;
633 FILE * f;
634 char str[1024];
635 char tp[100];   // protocol
636 char ta[100];   // address
637 char td[100];   // target direction
638 int r;
639 int lineNumber = 0;
640 f = fopen(rulesFileName.c_str(), "rt");
641
642 if (!f)
643     {
644     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
645     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
646     return true;
647     }
648
649 while (fgets(str, 1023, f))
650     {
651     lineNumber++;
652     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
653         {
654         continue;
655         }
656
657     r = sscanf(str,"%100s %100s %100s", tp, ta, td);
658     if (r != 3)
659         {
660         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
661         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
662         fclose(f);
663         return true;
664         }
665
666     rul.proto = 0xff;
667     rul.dir = 0xff;
668
669     for (uint8_t i = 0; i < PROTOMAX; i++)
670         {
671         if (strcasecmp(tp, protoName[i]) == 0)
672             rul.proto = i;
673         }
674
675     for (uint32_t i = 0; i < DIR_NUM + 1; i++)
676         {
677         if (td == dirName[i])
678             rul.dir = i;
679         }
680
681     if (rul.dir == 0xff || rul.proto == 0xff)
682         {
683         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
684         WriteServLog("Error in file %s. Line %d.",
685                      rulesFileName.c_str(), lineNumber);
686         fclose(f);
687         return true;
688         }
689
690     if (ParseAddress(ta, &rul) != 0)
691         {
692         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
693         WriteServLog("Error in file %s. Error in adress. Line %d.",
694                      rulesFileName.c_str(), lineNumber);
695         fclose(f);
696         return true;
697         }
698     if (!test)
699         rules.push_back(rul);
700     }
701
702 fclose(f);
703
704 // Adding lastest rule: ALL 0.0.0.0/0 NULL
705 rul.dir = DIR_NUM; //NULL
706 rul.ip = 0;  //0.0.0.0
707 rul.mask = 0;
708 rul.port1 = 0;
709 rul.port2 = 65535;
710 rul.proto = all;
711
712 if (!test)
713     rules.push_back(rul);
714
715 return false;
716 }
717 //-----------------------------------------------------------------------------
718 int TRAFFCOUNTER_IMPL::Reload()
719 {
720 STG_LOCKER lock(&mutex);
721
722 if (ReadRules(true))
723     {
724     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
725     WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
726     return -1;
727     }
728
729 FreeRules();
730 ReadRules();
731 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reloaded rules successfully.\n");
732 WriteServLog("TRAFFCOUNTER: Reloaded rules successfully.");
733 return 0;
734 }
735 //-----------------------------------------------------------------------------
736 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
737 {
738 char addr[50], mask[20], port1[20], port2[20], ports[40];
739
740 size_t len = strlen(ta);
741 char n = 0;
742 size_t i, p;
743 memset(addr, 0, sizeof(addr));
744 for (i = 0; i < len; i++)
745     {
746     if (ta[i] == '/' || ta[i] == ':')
747         {
748         addr[i] = 0;
749         n = ta[i];
750         break;
751         }
752     addr[i] = ta[i];
753     n = 0;
754     }
755 addr[i + 1] = 0;
756 p = i + 1;
757
758 if (n == '/')
759     {
760     // mask
761     for (; i < len; i++)
762         {
763         if (ta[i] == ':')
764             {
765             mask[i - p] = 0;
766             n = ':';
767             break;
768             }
769         mask[i - p] = ta[i];
770         }
771     mask[i - p] = 0;
772     }
773 else
774     {
775     strcpy(mask, "32");
776     }
777
778 p = i + 1;
779 i++;
780
781 if (n == ':')
782     {
783     // port
784     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
785         {
786         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
787         WriteServLog("No ports specified for this protocol.");
788         return true;
789         }
790
791     for (; i < len; i++)
792         ports[i - p] = ta[i];
793
794     ports[i - p] = 0;
795     }
796 else
797     {
798     strcpy(ports, "0-65535");
799     }
800
801 char *sss;
802 char pts[100];
803 strcpy(pts, ports);
804
805 if ((sss = strchr(ports, '-')) != NULL)
806     {
807     strncpy(port1, ports, int(sss-ports));
808     port1[int(sss - ports)] = 0;
809     strcpy(port2, sss + 1);
810     }
811 else
812     {
813     strcpy(port1, ports);
814     strcpy(port2, ports);
815     }
816
817 // Convert strings to mask, ports and IP
818 uint16_t prt1, prt2, msk;
819 struct in_addr ipaddr;
820 char *res;
821
822 msk = static_cast<uint16_t>(strtol(mask, &res, 10));
823 if (*res != 0)
824     return true;
825
826 prt1 = static_cast<uint16_t>(strtol(port1, &res, 10));
827 if (*res != 0)
828     return true;
829
830 prt2 = static_cast<uint16_t>(strtol(port2, &res, 10));
831 if (*res != 0)
832     return true;
833
834 int r = inet_aton(addr, &ipaddr);
835 if (r == 0)
836     return true;
837
838 rule->ip = ipaddr.s_addr;
839 rule->mask = CalcMask(msk);
840 //msk = 1;
841 //printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
842
843 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
844     {
845     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
846     WriteServLog("Address does'n match mask.");
847     return true;
848     }
849
850 rule->port1 = prt1;
851 rule->port2 = prt2;
852
853 return false;
854 }
855 //-----------------------------------------------------------------------------
856 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
857 {
858 if (msk >= 32) return 0xFFffFFff;
859 if (msk == 0) return 0;
860 return htonl(0xFFffFFff << (32 - msk));
861 }
862 //---------------------------------------------------------------------------
863 void TRAFFCOUNTER_IMPL::FreeRules()
864 {
865 rules.clear();
866 }
867 //-----------------------------------------------------------------------------
868 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & dir)
869 {
870 monitorDir = dir;
871 monitoring = !monitorDir.empty();
872 }
873 //-----------------------------------------------------------------------------