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