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