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