]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter_impl.cpp
IP initialization added in TEST_ADMIN
[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
41 #include "stg/common.h"
42 #include "stg/locker.h"
43 #include "traffcounter_impl.h"
44 #include "stg_timer.h"
45 #include "users_impl.h"
46
47 #define FLUSH_TIME  (10)
48 #define REMOVE_TIME  (31)
49
50 const char protoName[PROTOMAX][8] =
51 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
52
53 enum protoNum
54 {
55 tcp = 0, udp, icmp, tcp_udp, all
56 };
57
58 //-----------------------------------------------------------------------------
59 TRAFFCOUNTER_IMPL::TRAFFCOUNTER_IMPL(USERS_IMPL * u, const std::string & fn)
60     : WriteServLog(GetStgLogger()),
61       rulesFileName(fn),
62       monitoring(false),
63       users(u),
64       running(false),
65       stopped(true),
66       addUserNotifier(*this),
67       delUserNotifier(*this)
68 {
69 for (int i = 0; i < DIR_NUM; i++)
70     strprintf(&dirName[i], "DIR%d", i);
71
72 dirName[DIR_NUM] = "NULL";
73
74 users->AddNotifierUserAdd(&addUserNotifier);
75 users->AddNotifierUserDel(&delUserNotifier);
76
77 pthread_mutex_init(&mutex, NULL);
78 }
79 //-----------------------------------------------------------------------------
80 TRAFFCOUNTER_IMPL::~TRAFFCOUNTER_IMPL()
81 {
82 pthread_mutex_destroy(&mutex);
83 }
84 //-----------------------------------------------------------------------------
85 int TRAFFCOUNTER_IMPL::Start()
86 {
87 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
88
89 if (!stopped)
90     return 0;
91
92 if (ReadRules())
93     {
94     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot read rules\n");
95     WriteServLog("TRAFFCOUNTER: Cannot read rules.");
96     return -1;
97     }
98
99 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
100 int h = users->OpenSearch();
101 USER_IMPL * u;
102 if (!h)
103     {
104     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot get users\n");
105     WriteServLog("TRAFFCOUNTER: Cannot get users.");
106     return -1;
107     }
108
109 while (users->SearchNext(h, &u) == 0)
110     {
111     SetUserNotifiers(u);
112     }
113 users->CloseSearch(h);
114
115 running = true;
116 if (pthread_create(&thread, NULL, Run, this))
117     {
118     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Start() - Cannot start thread\n");
119     WriteServLog("TRAFFCOUNTER: Error: Cannot start thread.");
120     return -1;
121     }
122 return 0;
123 }
124 //-----------------------------------------------------------------------------
125 int TRAFFCOUNTER_IMPL::Stop()
126 {
127 if (stopped)
128     return 0;
129
130 running = false;
131
132 int h = users->OpenSearch();
133 if (!h)
134     {
135     WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
136     return -1;
137     }
138
139 USER_IMPL * u;
140 while (users->SearchNext(h, &u) == 0)
141     {
142     UnSetUserNotifiers(u);
143     }
144 users->CloseSearch(h);
145
146 //5 seconds to thread stops itself
147 struct timespec ts = {0, 200000000};
148 for (int i = 0; i < 25 && !stopped; i++)
149     {
150     nanosleep(&ts, NULL);
151     }
152
153 //after 5 seconds waiting thread still running. now kill it
154 if (!stopped)
155     {
156     printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
157     if (pthread_kill(thread, SIGINT))
158         {
159         return -1;
160         }
161     printfd(__FILE__, "TRAFFCOUNTER killed\n");
162     }
163 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
164
165 return 0;
166 }
167 //-----------------------------------------------------------------------------
168 void * TRAFFCOUNTER_IMPL::Run(void * data)
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 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
207
208 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
209     {
210     static 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 int oldPacketsSize = packets.size();
297 int oldIp2packetsSize = ip2packets.size();
298
299 pp_iter pi;
300 pi = packets.begin();
301 std::map<RAW_PACKET, PACKET_EXTRA_DATA> 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 return;
631 };
632 //-----------------------------------------------------------------------------
633 void TRAFFCOUNTER_IMPL::SetRulesFile(const std::string & fn)
634 {
635 rulesFileName = fn;
636 }
637 //-----------------------------------------------------------------------------
638 bool TRAFFCOUNTER_IMPL::ReadRules(bool test)
639 {
640 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
641
642 RULE rul;
643 FILE * f;
644 char str[1024];
645 char tp[100];   // protocol
646 char ta[100];   // address
647 char td[100];   // target direction
648 int r;
649 int lineNumber = 0;
650 f = fopen(rulesFileName.c_str(), "rt");
651
652 if (!f)
653     {
654     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - File '%s' cannot be opened.\n", rulesFileName.c_str());
655     WriteServLog("File '%s' cannot be oppened.", rulesFileName.c_str());
656     return true;
657     }
658
659 while (fgets(str, 1023, f))
660     {
661     lineNumber++;
662     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
663         {
664         continue;
665         }
666
667     r = sscanf(str,"%s %s %s", tp, ta, td);
668     if (r != 3)
669         {
670         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. There must be 3 parameters.\n", rulesFileName.c_str(), lineNumber);
671         WriteServLog("Error in file '%s' at line %d. There must be 3 parameters.", rulesFileName.c_str(), lineNumber);
672         fclose(f);
673         return true;
674         }
675
676     rul.proto = 0xff;
677     rul.dir = 0xff;
678
679     for (int i = 0; i < PROTOMAX; i++)
680         {
681         if (strcasecmp(tp, protoName[i]) == 0)
682             rul.proto = i;
683         }
684
685     for (int i = 0; i < DIR_NUM + 1; i++)
686         {
687         if (td == dirName[i])
688             rul.dir = i;
689         }
690
691     if (rul.dir == 0xff || rul.proto == 0xff)
692         {
693         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d.\n", rulesFileName.c_str(), lineNumber);
694         WriteServLog("Error in file %s. Line %d.",
695                      rulesFileName.c_str(), lineNumber);
696         fclose(f);
697         return true;
698         }
699
700     if (ParseAddress(ta, &rul) != 0)
701         {
702         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ReadRules() - Error in file '%s' at line %d. Error in adress.\n", rulesFileName.c_str(), lineNumber);
703         WriteServLog("Error in file %s. Error in adress. Line %d.",
704                      rulesFileName.c_str(), lineNumber);
705         fclose(f);
706         return true;
707         }
708     if (!test)
709         rules.push_back(rul);
710     //PrintRule(rul);
711     }
712
713 fclose(f);
714
715 // Adding lastest rule: ALL 0.0.0.0/0 NULL
716 rul.dir = DIR_NUM; //NULL
717 rul.ip = 0;  //0.0.0.0
718 rul.mask = 0;
719 rul.port1 = 0;
720 rul.port2 = 65535;
721 rul.proto = all;
722
723 if (!test)
724     rules.push_back(rul);
725
726 //PrintRule(rul);
727
728 return false;
729 }
730 //-----------------------------------------------------------------------------
731 int TRAFFCOUNTER_IMPL::Reload()
732 {
733 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
734
735 if (ReadRules(true))
736     {
737     printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() - Failed to reload rules.\n");
738     WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
739     return -1;
740     }
741
742 FreeRules();
743 ReadRules();
744 printfd(__FILE__, "TRAFFCOUNTER_IMPL::Reload() -  Reload rules successfull.\n");
745 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
746 return 0;
747 }
748 //-----------------------------------------------------------------------------
749 bool TRAFFCOUNTER_IMPL::ParseAddress(const char * ta, RULE * rule) const
750 {
751 char addr[50], mask[20], port1[20], port2[20], ports[40];
752
753 int len = strlen(ta);
754 char n = 0;
755 int i, p;
756 memset(addr, 0, sizeof(addr));
757 for (i = 0; i < len; i++)
758     {
759     if (ta[i] == '/' || ta[i] == ':')
760         {
761         addr[i] = 0;
762         n = ta[i];
763         break;
764         }
765     addr[i] = ta[i];
766     n = 0;
767     }
768 addr[i + 1] = 0;
769 p = i + 1;
770
771 if (n == '/')
772     {
773     // mask
774     for (; i < len; i++)
775         {
776         if (ta[i] == ':')
777             {
778             mask[i - p] = 0;
779             n = ':';
780             break;
781             }
782         mask[i - p] = ta[i];
783         }
784     mask[i - p] = 0;
785     }
786 else
787     {
788     strcpy(mask, "32");
789     }
790
791 p = i + 1;
792 i++;
793
794 if (n == ':')
795     {
796     // port
797     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
798         {
799         printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - No ports specified for this protocol.\n");
800         WriteServLog("No ports specified for this protocol.");
801         return true;
802         }
803
804     for (; i < len; i++)
805         ports[i - p] = ta[i];
806
807     ports[i - p] = 0;
808     }
809 else
810     {
811     strcpy(ports, "0-65535");
812     }
813
814 char *sss;
815 char pts[100];
816 strcpy(pts, ports);
817
818 if ((sss = strchr(ports, '-')) != NULL)
819     {
820     strncpy(port1, ports, int(sss-ports));
821     port1[int(sss - ports)] = 0;
822     strcpy(port2, sss + 1);
823     }
824 else
825     {
826     strcpy(port1, ports);
827     strcpy(port2, ports);
828     }
829
830 // Convert strings to mask, ports and IP
831 int prt1, prt2, msk;
832 unsigned ip;
833 char *res;
834
835 msk = strtol(mask, &res, 10);
836 if (*res != 0)
837     return true;
838
839 prt1 = strtol(port1, &res, 10);
840 if (*res != 0)
841     return true;
842
843 prt2 = strtol(port2, &res, 10);
844 if (*res != 0)
845     return true;
846
847 int r = inet_aton(addr, (struct in_addr*)&ip);
848 if (r == 0)
849     return true;
850
851 rule->ip = ip;
852 rule->mask = CalcMask(msk);
853 //msk = 1;
854 //printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
855
856 if ((ip & rule->mask) != ip)
857     {
858     printfd(__FILE__, "TRAFFCOUNTER_IMPL::ParseAddress() - Address does'n match mask.\n");
859     WriteServLog("Address does'n match mask.");
860     return true;
861     }
862
863 rule->port1 = prt1;
864 rule->port2 = prt2;
865
866 return false;
867 }
868 //-----------------------------------------------------------------------------
869 uint32_t TRAFFCOUNTER_IMPL::CalcMask(uint32_t msk) const
870 {
871 if (msk >= 32) return 0xFFffFFff;
872 if (msk == 0) return 0;
873 return htonl(0xFFffFFff << (32 - msk));
874 }
875 //---------------------------------------------------------------------------
876 void TRAFFCOUNTER_IMPL::FreeRules()
877 {
878 rules.clear();
879 }
880 //-----------------------------------------------------------------------------
881 void TRAFFCOUNTER_IMPL::PrintRule(RULE rule) const
882 {
883 printf("%15s   ", inet_ntostring(rule.ip).c_str());
884 printf("mask=%08X ", rule.mask);
885 printf("port1=%5d ", rule.port1);
886 printf("port2=%5d ", rule.port2);
887 switch (rule.proto)
888     {
889     case 0:
890         printf("TCP     ");
891         break;
892     case 1:
893         printf("UDP     ");
894         break;
895     case 2:
896         printf("ICMP    ");
897         break;
898     case 3:
899         printf("TCP_UDP ");
900         break;
901     case 4:
902         printf("ALL     ");
903         break;
904     }
905 printf("dir=%d \n", rule.dir);
906 return;
907 }
908 //-----------------------------------------------------------------------------
909 void TRAFFCOUNTER_IMPL::SetMonitorDir(const std::string & monitorDir)
910 {
911 TRAFFCOUNTER_IMPL::monitorDir = monitorDir;
912 monitoring = (monitorDir != "");
913 }
914 //-----------------------------------------------------------------------------