]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter_impl.cpp
Move variables declaration to the beginning of the function (old C)
[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 return;
630 };
631 //-----------------------------------------------------------------------------
632 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
633 {
634 rulesFileName = fn;
635 }
636 //-----------------------------------------------------------------------------
637 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
638 {
639 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
640
641 RULE rul;
642 FILE * f;
643 char str[1024];
644 char tp[100];   // protocol
645 char ta[100];   // address
646 char td[100];   // target direction
647 int r;
648 int lineNumber = 0;
649 f = fopen(rulesFileName.c_str(), "rt");
650
651 if (!f)
652     {
653     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
654     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
655     return true;
656     }
657
658 while (fgets(str, 1023, f))
659     {
660     lineNumber++;
661     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
662         {
663         continue;
664         }
665
666     r = sscanf(str,"%s %s %s", tp, ta, td);
667     if (r != 3)
668         {
669         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
670         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
671         fclose(f);
672         return true;
673         }
674
675     rul.proto = 0xff;
676     rul.dir = 0xff;
677
678     for (int i = 0; i < PROTOMAX; i++)
679         {
680         if (strcasecmp(tp, protoName[i]) == 0)
681             rul.proto = i;
682         }
683
684     for (int i = 0; i < DIR_NUM + 1; i++)
685         {
686         if (td == dirName[i])
687             rul.dir = i;
688         }
689
690     if (rul.dir == 0xff || rul.proto == 0xff)
691         {
692         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
693         WriteServLog("Error in file %s. Line %d.",
694                      rulesFileName.c_str(), lineNumber);
695         fclose(f);
696         return true;
697         }
698
699     if (ParseAddress(ta, &rul) != 0)
700         {
701         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
702         WriteServLog("Error in file %s. Error in adress. Line %d.",
703                      rulesFileName.c_str(), lineNumber);
704         fclose(f);
705         return true;
706         }
707     if (!test)
708         rules.push_back(rul);
709     //PrintRule(rul);
710     }
711
712 fclose(f);
713
714 // Adding lastest rule: ALL 0.0.0.0/0 NULL
715 rul.dir = DIR_NUM; //NULL
716 rul.ip = 0;  //0.0.0.0
717 rul.mask = 0;
718 rul.port1 = 0;
719 rul.port2 = 65535;
720 rul.proto = all;
721
722 if (!test)
723     rules.push_back(rul);
724
725 //PrintRule(rul);
726
727 return false;
728 }
729 //-----------------------------------------------------------------------------
730 int TRAFFCOUNTER_IMPL::Reload()
731 {
732 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
733
734 if (ReadRules(true))
735     {
736     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
737     WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
738     return -1;
739     }
740
741 FreeRules();
742 ReadRules();
743 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reload rules successfull.\n");
744 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
745 return 0;
746 }
747 //-----------------------------------------------------------------------------
748 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
749 {
750 char addr[50], mask[20], port1[20], port2[20], ports[40];
751
752 int len = strlen(ta);
753 char n = 0;
754 int i, p;
755 memset(addr, 0, sizeof(addr));
756 for (i = 0; i < len; i++)
757     {
758     if (ta[i] == '/' || ta[i] == ':')
759         {
760         addr[i] = 0;
761         n = ta[i];
762         break;
763         }
764     addr[i] = ta[i];
765     n = 0;
766     }
767 addr[i + 1] = 0;
768 p = i + 1;
769
770 if (n == '/')
771     {
772     // mask
773     for (; i < len; i++)
774         {
775         if (ta[i] == ':')
776             {
777             mask[i - p] = 0;
778             n = ':';
779             break;
780             }
781         mask[i - p] = ta[i];
782         }
783     mask[i - p] = 0;
784     }
785 else
786     {
787     strcpy(mask, "32");
788     }
789
790 p = i + 1;
791 i++;
792
793 if (n == ':')
794     {
795     // port
796     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
797         {
798         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
799         WriteServLog("No ports specified for this protocol.");
800         return true;
801         }
802
803     for (; i < len; i++)
804         ports[i - p] = ta[i];
805
806     ports[i - p] = 0;
807     }
808 else
809     {
810     strcpy(ports, "0-65535");
811     }
812
813 char *sss;
814 char pts[100];
815 strcpy(pts, ports);
816
817 if ((sss = strchr(ports, '-')) != NULL)
818     {
819     strncpy(port1, ports, int(sss-ports));
820     port1[int(sss - ports)] = 0;
821     strcpy(port2, sss + 1);
822     }
823 else
824     {
825     strcpy(port1, ports);
826     strcpy(port2, ports);
827     }
828
829 // Convert strings to mask, ports and IP
830 int prt1, prt2, msk;
831 unsigned ip;
832 char *res;
833
834 msk = strtol(mask, &res, 10);
835 if (*res != 0)
836     return true;
837
838 prt1 = strtol(port1, &res, 10);
839 if (*res != 0)
840     return true;
841
842 prt2 = strtol(port2, &res, 10);
843 if (*res != 0)
844     return true;
845
846 int r = inet_aton(addr, (struct in_addr*)&ip);
847 if (r == 0)
848     return true;
849
850 rule->ip = ip;
851 rule->mask = CalcMask(msk);
852 //msk = 1;
853 //printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
854
855 if ((ip & rule->mask) != ip)
856     {
857     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
858     WriteServLog("Address does'n match mask.");
859     return true;
860     }
861
862 rule->port1 = prt1;
863 rule->port2 = prt2;
864
865 return false;
866 }
867 //-----------------------------------------------------------------------------
868 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
869 {
870 if (msk >= 32) return 0xFFffFFff;
871 if (msk == 0) return 0;
872 return htonl(0xFFffFFff << (32 - msk));
873 }
874 //---------------------------------------------------------------------------
875 void TRAFFCOUNTER_IMPL::FreeRules()
876 {
877 rules.clear();
878 }
879 //-----------------------------------------------------------------------------
880 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
881 {
882 printf("%15s   ", inet_ntostring(rule.ip).c_str());
883 printf("mask=%08X ", rule.mask);
884 printf("port1=%5d ", rule.port1);
885 printf("port2=%5d ", rule.port2);
886 switch (rule.proto)
887     {
888     case 0:
889         printf("TCP     ");
890         break;
891     case 1:
892         printf("UDP     ");
893         break;
894     case 2:
895         printf("ICMP    ");
896         break;
897     case 3:
898         printf("TCP_UDP ");
899         break;
900     case 4:
901         printf("ALL     ");
902         break;
903     }
904 printf("dir=%d \n", rule.dir);
905 return;
906 }
907 //-----------------------------------------------------------------------------
908 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
909 {
910 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
911 monitoring = (monitorDir != "");
912 }
913 //-----------------------------------------------------------------------------