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