]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter.cpp
Генерацію документації по XML RPC перенесено у каталог book
[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 ip2packets.erase(ip2packets.begin(), ip2packets.end());
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             ip2packets.insert(make_pair(pi->first.GetSrcIP(), res.first));
392             ip2packets.insert(make_pair(pi->first.GetDstIP(), res.first));
393             }
394         }
395     ++pi;
396     }
397 swap(packets, newPackets);
398 printfd(__FILE__, "FlushAndRemove() packets: %d(rem %d) ip2packets: %d(rem %d)\n",
399         packets.size(),
400         oldPacketsSize - packets.size(),
401         ip2packets.size(),
402         oldIp2packetsSize - ip2packets.size());
403
404 }
405 //-----------------------------------------------------------------------------
406 void TRAFFCOUNTER::AddUser(user_iter user)
407 {
408 printfd(__FILE__, "AddUser: %s\n", user->GetLogin().c_str());
409 uint32_t uip = user->GetCurrIP();
410 pair<ip2p_iter, ip2p_iter> pi;
411
412 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
413 // Find all packets with IP belongs to this user
414 pi = ip2packets.equal_range(uip);
415
416 while (pi.first != pi.second)
417     {
418     if (pi.first->second->first.GetSrcIP() == uip)
419         {
420         assert((!pi.first->second->second.userUPresent || 
421                  pi.first->second->second.userU == user) &&
422                "U user present but it's not current user");
423
424         pi.first->second->second.lenU = 0;
425         pi.first->second->second.userU = user;
426         pi.first->second->second.userUPresent = true;
427         }
428
429     if (pi.first->second->first.GetDstIP() == uip)
430         {
431         assert((!pi.first->second->second.userDPresent || 
432                  pi.first->second->second.userD == user) &&
433                "D user present but it's not current user");
434
435         pi.first->second->second.lenD = 0;
436         pi.first->second->second.userD = user;
437         pi.first->second->second.userDPresent = true;
438         }
439
440     ++pi.first;
441     }
442 }
443 //-----------------------------------------------------------------------------
444 void TRAFFCOUNTER::DelUser(uint32_t uip)
445 {
446 printfd(__FILE__, "DelUser: %s \n", inet_ntostring(uip).c_str());
447 pair<ip2p_iter, ip2p_iter> pi;
448
449 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
450 pi = ip2packets.equal_range(uip);
451
452 while (pi.first != pi.second)
453     {
454     if (pi.first->second->first.GetSrcIP() == uip)
455         {
456         if (pi.first->second->second.dirU < DIR_NUM && pi.first->second->second.userUPresent)
457             {
458             #ifdef TRAFF_STAT_WITH_PORTS
459             pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
460                                                           pi.first->second->first.GetDstIP(),
461                                                           pi.first->second->first.GetDstPort(),
462                                                           pi.first->second->second.lenU);
463             #else
464             pi.first->second->second.userU->AddTraffStatU(pi.first->second->second.dirU,
465                                                           pi.first->second->first.GetDstIP(),
466                                                           pi.first->second->second.lenU);
467             #endif
468             }
469         pi.first->second->second.userUPresent = false;
470         }
471
472     if (pi.first->second->first.GetDstIP() == uip)
473         {
474         if (pi.first->second->second.dirD < DIR_NUM && pi.first->second->second.userDPresent)
475             {
476             #ifdef TRAFF_STAT_WITH_PORTS
477             pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
478                                                           pi.first->second->first.GetSrcIP(),
479                                                           pi.first->second->first.GetSrcPort(),
480                                                           pi.first->second->second.lenD);
481             #else
482             pi.first->second->second.userD->AddTraffStatD(pi.first->second->second.dirD,
483                                                           pi.first->second->first.GetSrcIP(),
484                                                           pi.first->second->second.lenD);
485             #endif
486             }
487
488         pi.first->second->second.userDPresent = false;
489         }
490
491     ++pi.first;
492     }
493
494 ip2packets.erase(pi.first, pi.second);
495 }
496 //-----------------------------------------------------------------------------
497 void TRAFFCOUNTER::SetUserNotifiers(user_iter user)
498 {
499 // Adding user. Adding notifiers to user.
500 TRF_IP_BEFORE ipBNotifier(*this, user);
501 ipBeforeNotifiers.push_front(ipBNotifier);
502 user->AddCurrIPBeforeNotifier(&(*ipBeforeNotifiers.begin()));
503
504 TRF_IP_AFTER ipANotifier(*this, user);
505 ipAfterNotifiers.push_front(ipANotifier);
506 user->AddCurrIPAfterNotifier(&(*ipAfterNotifiers.begin()));
507 }
508 //-----------------------------------------------------------------------------
509 void TRAFFCOUNTER::UnSetUserNotifiers(user_iter user)
510 {
511 // Removing user. Removing notifiers from user.
512 list<TRF_IP_BEFORE>::iterator bi;
513 list<TRF_IP_AFTER>::iterator ai;
514
515 bi = ipBeforeNotifiers.begin();
516 while (bi != ipBeforeNotifiers.end())
517     {
518     if (user->GetLogin() == bi->GetUser()->GetLogin())
519         {
520         user->DelCurrIPBeforeNotifier(&(*bi));
521         ipBeforeNotifiers.erase(bi);
522         break;
523         }
524     ++bi;
525     }
526
527 ai = ipAfterNotifiers.begin();
528 while (ai != ipAfterNotifiers.end())
529     {
530     if (user->GetLogin() == ai->GetUser()->GetLogin())
531         {
532         user->DelCurrIPAfterNotifier(&(*ai));
533         ipAfterNotifiers.erase(ai);
534         break;
535         }
536     ++ai;
537     }
538 }
539 //-----------------------------------------------------------------------------
540 void TRAFFCOUNTER::DeterminateDir(const RAW_PACKET & packet,
541                                  int * dirU, // Direction for incoming packet
542                                  int * dirD) const // Direction for outgoing packet
543 {
544 bool addrMatchU;
545 bool portMatchU;
546 bool addrMatchD;
547 bool portMatchD;
548 bool foundU = false; // Was rule for U found ?
549 bool foundD = false; // Was rule for D found ?
550 //printfd(__FILE__, "foundU=%d, foundD=%d\n", foundU, foundD);
551
552 enum { ICMP_RPOTO = 1, TCP_PROTO = 6, UDP_PROTO = 17 };
553
554 list<RULE>::const_iterator ln;
555 ln = rules.begin();
556
557 while (ln != rules.end())
558     {
559     if (!foundU)
560         {
561         addrMatchU = false;
562         portMatchU = false;
563
564         switch (ln->proto)
565             {
566             case all:
567                 portMatchU = true;
568                 break;
569
570             case icmp:
571                 portMatchU = (packet.GetProto() == ICMP_RPOTO);
572                 break;
573
574             case tcp_udp:
575                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
576                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
577                 break;
578
579             case tcp:
580                 if (packet.GetProto() == TCP_PROTO)
581                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
582                 break;
583
584             case udp:
585                 if (packet.GetProto() == UDP_PROTO)
586                     portMatchU = (packet.GetDstPort() >= ln->port1) && (packet.GetDstPort() <= ln->port2);
587                 break;
588
589             default:
590                 printfd(__FILE__, "Error! Incorrect rule!\n");
591                 break;
592             }
593
594         addrMatchU = (packet.GetDstIP() & ln->mask) == ln->ip;
595
596         if (!foundU && addrMatchU && portMatchU)
597             {
598             foundU = true;
599             *dirU = ln->dir;
600             //printfd(__FILE__, "Up rule ok! %d\n", ln->dir);
601             //PrintRule(ln->rule);
602             }
603
604         } //if (!foundU)
605
606     if (!foundD)
607         {
608         addrMatchD = false;
609         portMatchD = false;
610
611         switch (ln->proto)
612             {
613             case all:
614                 portMatchD = true;
615                 break;
616
617             case icmp:
618                 portMatchD = (packet.GetProto() == ICMP_RPOTO);
619                 break;
620
621             case tcp_udp:
622                 if (packet.GetProto() == TCP_PROTO || packet.GetProto() == UDP_PROTO)
623                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
624                 break;
625
626             case tcp:
627                 if (packet.GetProto() == TCP_PROTO)
628                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
629                 break;
630
631             case udp:
632                 if (packet.GetProto() == UDP_PROTO)
633                     portMatchD = (packet.GetSrcPort() >= ln->port1) && (packet.GetSrcPort() <= ln->port2);
634                 break;
635
636             default:
637                 printfd(__FILE__, "Error! Incorrect rule!\n");
638                 break;
639             }
640
641         addrMatchD = (packet.GetSrcIP() & ln->mask) == ln->ip;
642
643         if (!foundD && addrMatchD && portMatchD)
644             {
645             foundD = true;
646             *dirD = ln->dir;
647             //printfd(__FILE__, "Down rule ok! %d\n", ln->dir);
648             //PrintRule(ln->rule);
649             }
650         } //if (!foundD)
651
652     ++ln;
653     }   //while (ln != rules.end())
654
655 if (!foundU)
656     *dirU = DIR_NUM;
657
658 if (!foundD)
659     *dirD = DIR_NUM;
660
661 return;
662 };
663 //-----------------------------------------------------------------------------
664 void TRAFFCOUNTER::SetRulesFile(const string & fn)
665 {
666 rulesFileName = fn;
667 }
668 //-----------------------------------------------------------------------------
669 bool TRAFFCOUNTER::ReadRules(bool test)
670 {
671 //printfd(__FILE__, "TRAFFCOUNTER::ReadRules()\n");
672
673 RULE rul;
674 FILE * f;
675 char str[1024];
676 char tp[100];   // protocol
677 char ta[100];   // address
678 char td[100];   // target direction
679 int r;
680 int lineNumber = 0;
681 f = fopen(rulesFileName.c_str(), "rt");
682
683 if (!f)
684     {
685     WriteServLog("File %s cannot be oppened.", rulesFileName.c_str());
686     return true;
687     }
688
689 while (fgets(str, 1023, f))
690     {
691     lineNumber++;
692     if (str[strspn(str," \t")] == '#' || str[strspn(str," \t")] == '\n')
693         {
694         continue;
695         }
696
697     r = sscanf(str,"%s %s %s", tp, ta, td);
698     if (r != 3)
699         {
700         WriteServLog("Error in file %s. There must be 3 parameters. Line %d.", rulesFileName.c_str(), lineNumber);
701         fclose(f);
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         fclose(f);
725         return true;
726         }
727
728     if (ParseAddress(ta, &rul) != 0)
729         {
730         WriteServLog("Error in file %s. Error in adress. Line %d.",
731                      rulesFileName.c_str(), lineNumber);
732         fclose(f);
733         return true;
734         }
735     if (!test)
736         rules.push_back(rul);
737     //PrintRule(rul);
738     }
739
740 fclose(f);
741
742 // Adding lastest rule: ALL 0.0.0.0/0 NULL
743 rul.dir = DIR_NUM; //NULL
744 rul.ip = 0;  //0.0.0.0
745 rul.mask = 0;
746 rul.port1 = 0;
747 rul.port2 = 65535;
748 rul.proto = all;
749
750 if (!test)
751     rules.push_back(rul);
752
753 //PrintRule(rul);
754
755 return false;
756 }
757 //-----------------------------------------------------------------------------
758 int TRAFFCOUNTER::Reload()
759 {
760 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
761
762 if (ReadRules(true))
763     {
764     WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
765     return -1;
766     }
767
768 FreeRules();
769 ReadRules();
770 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
771 return 0;
772 }
773 //-----------------------------------------------------------------------------
774 bool TRAFFCOUNTER::ParseAddress(const char * ta, RULE * rule) const
775 {
776 char addr[50], mask[20], port1[20], port2[20], ports[40];
777
778 int len = strlen(ta);
779 char n = 0;
780 int i, p;
781 memset(addr, 0, sizeof(addr));
782 for (i = 0; i < len; i++)
783     {
784     if (ta[i] == '/' || ta[i] == ':')
785         {
786         addr[i] = 0;
787         n = ta[i];
788         break;
789         }
790     addr[i] = ta[i];
791     n = 0;
792     }
793 addr[i + 1] = 0;
794 p = i + 1;
795
796 if (n == '/')
797     {
798     // mask
799     for (; i < len; i++)
800         {
801         if (ta[i] == ':')
802             {
803             mask[i - p] = 0;
804             n = ':';
805             break;
806             }
807         mask[i - p] = ta[i];
808         }
809     mask[i - p] = 0;
810     }
811 else
812     {
813     strcpy(mask, "32");
814     }
815
816 p = i + 1;
817 i++;
818
819 if (n == ':')
820     {
821     // port
822     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
823         {
824         WriteServLog("No ports specified for this protocol.");
825         return true;
826         }
827
828     for (; i < len; i++)
829         ports[i - p] = ta[i];
830
831     ports[i - p] = 0;
832     }
833 else
834     {
835     strcpy(ports, "0-65535");
836     }
837
838 char *sss;
839 char pts[100];
840 strcpy(pts, ports);
841
842 if ((sss = strchr(ports, '-')) != NULL)
843     {
844     strncpy(port1, ports, int(sss-ports));
845     port1[int(sss - ports)] = 0;
846     strcpy(port2, sss + 1);
847     }
848 else
849     {
850     strcpy(port1, ports);
851     strcpy(port2, ports);
852     }
853
854 // Convert strings to mask, ports and IP
855 int prt1, prt2, msk;
856 unsigned ip;
857 char *res;
858
859 msk = strtol(mask, &res, 10);
860 if (*res != 0)
861     return true;
862
863 prt1 = strtol(port1, &res, 10);
864 if (*res != 0)
865     return true;
866
867 prt2 = strtol(port2, &res, 10);
868 if (*res != 0)
869     return true;
870
871 int r = inet_aton(addr, (struct in_addr*)&ip);
872 if (r == 0)
873     return true;
874
875 rule->ip = ip;
876 rule->mask = CalcMask(msk);
877 //msk = 1;
878 //printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
879
880 if ((ip & rule->mask) != ip)
881     {
882     WriteServLog("Address does'n match mask.");
883     return true;
884     }
885
886 rule->port1 = prt1;
887 rule->port2 = prt2;
888
889 return false;
890 }
891 //-----------------------------------------------------------------------------
892 uint32_t TRAFFCOUNTER::CalcMask(uint32_t msk) const
893 {
894 if (msk >= 32) return 0xFFffFFff;
895 if (msk == 0) return 0;
896 return htonl(0xFFffFFff << (32 - msk));
897 }
898 //---------------------------------------------------------------------------
899 void TRAFFCOUNTER::FreeRules()
900 {
901 rules.clear();
902 }
903 //-----------------------------------------------------------------------------
904 void TRAFFCOUNTER::PrintRule(RULE rule) const
905 {
906 printf("%15s   ", inet_ntostring(rule.ip).c_str());
907 printf("mask=%08X ", rule.mask);
908 printf("port1=%5d ", rule.port1);
909 printf("port2=%5d ", rule.port2);
910 switch (rule.proto)
911     {
912     case 0:
913         printf("TCP     ");
914         break;
915     case 1:
916         printf("UDP     ");
917         break;
918     case 2:
919         printf("ICMP    ");
920         break;
921     case 3:
922         printf("TCP_UDP ");
923         break;
924     case 4:
925         printf("ALL     ");
926         break;
927     }
928 printf("dir=%d \n", rule.dir);
929 return;
930 }
931 //-----------------------------------------------------------------------------
932 void TRAFFCOUNTER::SetMonitorDir(const string & monitorDir)
933 {
934 TRAFFCOUNTER::monitorDir = monitorDir;
935 monitoring = (monitorDir != "");
936 }
937 //-----------------------------------------------------------------------------