]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter_impl.cpp
Fixed ip_queue.h checking.
[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 "traffcounter_impl.h"
45 #include "stg_timer.h"
46 #include "users_impl.h"
47
48 #define FLUSH_TIME  (10)
49 #define REMOVE_TIME  (31)
50
51 const char protoName[PROTOMAX][8] =
52 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
53
54 enum protoNum
55 {
56 tcp = 0, udp, icmp, tcp_udp, all
57 };
58
59 //-----------------------------------------------------------------------------
60 TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
61     : TRAFFCOUNTER(),
62       rules(),
63       packets(),
64       ip2packets(),
65       dirName(),
66       WriteServLog(GetStgLogger()),
67       rulesFileName(fn),
68       monitorDir(),
69       monitoring(false),
70       users(u),
71       running(false),
72       stopped(true),
73       mutex(),
74       thread(),
75       ipBeforeNotifiers(),
76       ipAfterNotifiers(),
77       addUserNotifier(*this),
78       delUserNotifier(*this)
79 {
80 for (int i = 0; i < DIR_NUM; i++)
81     strprintf(&dirName[i], "DIR%d", i);
82
83 dirName[DIR_NUM] = "NULL";
84
85 users->AddNotifierUserAdd(&addUserNotifier);
86 users->AddNotifierUserDel(&delUserNotifier);
87
88 pthread_mutex_init(&mutex, NULL);
89 }
90 //-----------------------------------------------------------------------------
91 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
92 {
93 pthread_mutex_destroy(&mutex);
94 }
95 //-----------------------------------------------------------------------------
96 int TRAFFCOUNTER_IMPL::Start()
97 {
98 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
99
100 if (!stopped)
101     return 0;
102
103 if (ReadRules())
104     {
105     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
106     WriteServLog("TRAFFCOUNTER: Cannot read rules.");
107     return -1;
108     }
109
110 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
111 int h = users->OpenSearch();
112 assert(h && "USERS::OpenSearch is always correct");
113 USER_IMPL * u;
114
115 while (users->SearchNext(h, &u) == 0)
116     {
117     SetUserNotifiers(u);
118     }
119 users->CloseSearch(h);
120
121 running = true;
122 if (pthread_create(&thread, NULL, Run, this))
123     {
124     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
125     WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
126     return -1;
127     }
128 return 0;
129 }
130 //-----------------------------------------------------------------------------
131 int TRAFFCOUNTER_IMPL::Stop()
132 {
133 if (stopped)
134     return 0;
135
136 running = false;
137
138 int h = users->OpenSearch();
139 assert(h && "USERS::OpenSearch is always correct");
140
141 USER_IMPL * u;
142 while (users->SearchNext(h, &u) == 0)
143     {
144     UnSetUserNotifiers(u);
145     }
146 users->CloseSearch(h);
147
148 //5 seconds to thread stops itself
149 struct timespec ts = {0, 200000000};
150 for (int i = 0; i < 25 && !stopped; i++)
151     {
152     nanosleep(&ts, NULL);
153     }
154
155 if (!stopped)
156     return -1;
157
158 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
159
160 return 0;
161 }
162 //-----------------------------------------------------------------------------
163 void * TRAFFCOUNTER_IMPL::Run(void * data)
164 {
165 sigset_t signalSet;
166 sigfillset(&signalSet);
167 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
168
169 TRAFFCOUNTER_IMPL * tc = static_cast<TRAFFCOUNTER_IMPL *>(data);
170 tc->stopped = false;
171 int c = 0;
172
173 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
174 struct timespec ts = {0, 500000000};
175 while (tc->running)
176     {
177     nanosleep(&ts, 0);
178     if (!tc->running)
179         {
180         tc->FlushAndRemove();
181         break;
182         }
183
184     if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
185         {
186         std::string monFile(tc->monitorDir + "/traffcounter_r");
187         printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
188         touchTime = stgTime;
189         TouchFile(monFile.c_str());
190         }
191
192     if (++c % FLUSH_TIME == 0)
193         tc->FlushAndRemove();
194     }
195
196 tc->stopped = true;
197 return NULL;
198 }
199 //-----------------------------------------------------------------------------
200 void TRAFFCOUNTER_IMPL::Process(const RAW_PACKET & rawPacket)
201 {
202 if (!running)
203     return;
204
205 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
206
207 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
208     {
209     static std::string monFile = monitorDir + "/traffcounter_p";
210     printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
211     touchTime = stgTime;
212     TouchFile(monFile.c_str());
213     }
214
215 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
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, __FILE__, __LINE__);
294
295 int oldPacketsSize = packets.size();
296 int oldIp2packetsSize = ip2packets.size();
297
298 pp_iter pi;
299 pi = packets.begin();
300 std::map<RAW_PACKET, PACKET_EXTRA_DATA> 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, __FILE__, __LINE__);
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, __FILE__, __LINE__);
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             //PrintRule(ln->rule);
570             }
571
572         } //if (!foundU)
573
574     if (!foundD)
575         {
576         addrMatchD = false;
577         portMatchD = false;
578
579         switch (ln->proto)
580             {
581             case all:
582                 portMatchD = true;
583                 break;
584
585             case icmp:
586                 portMatchD = (packet.GetProto() == ICMP_RPOTO);
587                 break;
588
589             case tcp_udp:
590                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
591                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
592                 break;
593
594             case tcp:
595                 if (packet.GetProto() == TCP_PROTO)
596                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
597                 break;
598
599             case udp:
600                 if (packet.GetProto() == UDP_PROTO)
601                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
602                 break;
603
604             default:
605                 printfd(__FILE__, "Error! Incorrect rule!\n");
606                 break;
607             }
608
609         addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
610
611         if (!foundD && addrMatchD && portMatchD)
612             {
613             foundD = true;
614             *dirD = ln->dir;
615             //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
616             //PrintRule(ln->rule);
617             }
618         } //if (!foundD)
619
620     ++ln;
621     }   //while (ln != rules.end())
622
623 if (!foundU)
624     *dirU = DIR_NUM;
625
626 if (!foundD)
627     *dirD = DIR_NUM;
628 }
629 //-----------------------------------------------------------------------------
630 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
631 {
632 rulesFileName = fn;
633 }
634 //-----------------------------------------------------------------------------
635 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
636 {
637 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
638
639 RULE rul;
640 FILE * f;
641 char str[1024];
642 char tp[100];   // protocol
643 char ta[100];   // address
644 char td[100];   // target direction
645 int r;
646 int lineNumber = 0;
647 f = fopen(rulesFileName.c_str(), "rt");
648
649 if (!f)
650     {
651     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
652     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
653     return true;
654     }
655
656 while (fgets(str, 1023, f))
657     {
658     lineNumber++;
659     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
660         {
661         continue;
662         }
663
664     r = sscanf(str,"%s %s %s", tp, ta, td);
665     if (r != 3)
666         {
667         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
668         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
669         fclose(f);
670         return true;
671         }
672
673     rul.proto = 0xff;
674     rul.dir = 0xff;
675
676     for (size_t i = 0; i < PROTOMAX; i++)
677         {
678         if (strcasecmp(tp, protoName[i]) == 0)
679             rul.proto = i;
680         }
681
682     for (size_t i = 0; i < DIR_NUM + 1; i++)
683         {
684         if (td == dirName[i])
685             rul.dir = i;
686         }
687
688     if (rul.dir == 0xff || rul.proto == 0xff)
689         {
690         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
691         WriteServLog("Error in file %s. Line %d.",
692                      rulesFileName.c_str(), lineNumber);
693         fclose(f);
694         return true;
695         }
696
697     if (ParseAddress(ta, &rul) != 0)
698         {
699         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
700         WriteServLog("Error in file %s. Error in adress. Line %d.",
701                      rulesFileName.c_str(), lineNumber);
702         fclose(f);
703         return true;
704         }
705     if (!test)
706         rules.push_back(rul);
707     //PrintRule(rul);
708     }
709
710 fclose(f);
711
712 // Adding lastest rule: ALL 0.0.0.0/0 NULL
713 rul.dir = DIR_NUM; //NULL
714 rul.ip = 0;  //0.0.0.0
715 rul.mask = 0;
716 rul.port1 = 0;
717 rul.port2 = 65535;
718 rul.proto = all;
719
720 if (!test)
721     rules.push_back(rul);
722
723 //PrintRule(rul);
724
725 return false;
726 }
727 //-----------------------------------------------------------------------------
728 int TRAFFCOUNTER_IMPL::Reload()
729 {
730 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
731
732 if (ReadRules(true))
733     {
734     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
735     WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
736     return -1;
737     }
738
739 FreeRules();
740 ReadRules();
741 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reload rules successfull.\n");
742 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
743 return 0;
744 }
745 //-----------------------------------------------------------------------------
746 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
747 {
748 char addr[50], mask[20], port1[20], port2[20], ports[40];
749
750 int len = strlen(ta);
751 char n = 0;
752 int i, p;
753 memset(addr, 0, sizeof(addr));
754 for (i = 0; i < len; i++)
755     {
756     if (ta[i] == '/' || ta[i] == ':')
757         {
758         addr[i] = 0;
759         n = ta[i];
760         break;
761         }
762     addr[i] = ta[i];
763     n = 0;
764     }
765 addr[i + 1] = 0;
766 p = i + 1;
767
768 if (n == '/')
769     {
770     // mask
771     for (; i < len; i++)
772         {
773         if (ta[i] == ':')
774             {
775             mask[i - p] = 0;
776             n = ':';
777             break;
778             }
779         mask[i - p] = ta[i];
780         }
781     mask[i - p] = 0;
782     }
783 else
784     {
785     strcpy(mask, "32");
786     }
787
788 p = i + 1;
789 i++;
790
791 if (n == ':')
792     {
793     // port
794     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
795         {
796         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
797         WriteServLog("No ports specified for this protocol.");
798         return true;
799         }
800
801     for (; i < len; i++)
802         ports[i - p] = ta[i];
803
804     ports[i - p] = 0;
805     }
806 else
807     {
808     strcpy(ports, "0-65535");
809     }
810
811 char *sss;
812 char pts[100];
813 strcpy(pts, ports);
814
815 if ((sss = strchr(ports, '-')) != NULL)
816     {
817     strncpy(port1, ports, int(sss-ports));
818     port1[int(sss - ports)] = 0;
819     strcpy(port2, sss + 1);
820     }
821 else
822     {
823     strcpy(port1, ports);
824     strcpy(port2, ports);
825     }
826
827 // Convert strings to mask, ports and IP
828 uint16_t prt1, prt2, msk;
829 struct in_addr ipaddr;
830 char *res;
831
832 msk = strtol(mask, &res, 10);
833 if (*res != 0)
834     return true;
835
836 prt1 = strtol(port1, &res, 10);
837 if (*res != 0)
838     return true;
839
840 prt2 = strtol(port2, &res, 10);
841 if (*res != 0)
842     return true;
843
844 int r = inet_aton(addr, &ipaddr);
845 if (r == 0)
846     return true;
847
848 rule->ip = ipaddr.s_addr;
849 rule->mask = CalcMask(msk);
850 //msk = 1;
851 //printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
852
853 if ((ipaddr.s_addr & rule->mask) != ipaddr.s_addr)
854     {
855     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
856     WriteServLog("Address does'n match mask.");
857     return true;
858     }
859
860 rule->port1 = prt1;
861 rule->port2 = prt2;
862
863 return false;
864 }
865 //-----------------------------------------------------------------------------
866 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
867 {
868 if (msk >= 32) return 0xFFffFFff;
869 if (msk == 0) return 0;
870 return htonl(0xFFffFFff << (32 - msk));
871 }
872 //---------------------------------------------------------------------------
873 void TRAFFCOUNTER_IMPL::FreeRules()
874 {
875 rules.clear();
876 }
877 //-----------------------------------------------------------------------------
878 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
879 {
880 printf("%15s   ", inet_ntostring(rule.ip).c_str());
881 printf("mask=%08X ", rule.mask);
882 printf("port1=%5d ", rule.port1);
883 printf("port2=%5d ", rule.port2);
884 switch (rule.proto)
885     {
886     case 0:
887         printf("TCP     ");
888         break;
889     case 1:
890         printf("UDP     ");
891         break;
892     case 2:
893         printf("ICMP    ");
894         break;
895     case 3:
896         printf("TCP_UDP ");
897         break;
898     case 4:
899         printf("ALL     ");
900         break;
901     }
902 printf("dir=%u \n", static_cast<unsigned>(rule.dir));
903 }
904 //-----------------------------------------------------------------------------
905 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
906 {
907 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
908 monitoring = (monitorDir != "");
909 }
910 //-----------------------------------------------------------------------------