]> git.stg.codes - stg.git/blob - projects/stargazer/traffcounter.cpp
1d088f489dfb1f5a8c1a5bdd0ebfcae15afc0cba
[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 #include <cstdio> // Functions fopen and similar
34
35 #include "traffcounter.h"
36 #include "common.h"
37 #include "stg_locker.h"
38
39 #define FLUSH_TIME  (10)
40 #define REMOVE_TIME  (31)
41
42 const char protoName[PROTOMAX][8] =
43 {"TCP", "UDP", "ICMP", "TCP_UDP", "ALL"};
44
45 enum protoNum
46     {
47     tcp = 0, udp, icmp, tcp_udp, all
48     };
49
50 //-----------------------------------------------------------------------------
51 TRAFFCOUNTER::TRAFFCOUNTER(USERS * u, const TARIFFS *, const string & fn)
52     : WriteServLog(GetStgLogger()),
53       rulesFileName(fn),
54       monitoring(false),
55       users(u),
56       running(false),
57       stopped(true),
58       addUserNotifier(*this),
59       delUserNotifier(*this)
60 {
61 for (int i = 0; i < DIR_NUM; i++)
62     strprintf(&dirName[i], "DIR%d", i);
63
64 dirName[DIR_NUM] = "NULL";
65
66 users->AddNotifierUserAdd(&addUserNotifier);
67 users->AddNotifierUserDel(&delUserNotifier);
68
69 pthread_mutex_init(&mutex, NULL);
70 }
71 //-----------------------------------------------------------------------------
72 TRAFFCOUNTER::~TRAFFCOUNTER()
73 {
74 pthread_mutex_destroy(&mutex);
75 }
76 //-----------------------------------------------------------------------------
77 int TRAFFCOUNTER::Start()
78 {
79 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
80
81 if (!stopped)
82     return 0;
83
84 if (ReadRules())
85     {
86     WriteServLog("TRAFFCOUNTER: Cannot read rules.");
87     return -1;
88     }
89
90 printfd(__FILE__, "TRAFFCOUNTER::Start()\n");
91 int h = users->OpenSearch();
92 user_iter u;
93 if (!h)
94     {
95     WriteServLog("TRAFFCOUNTER: Cannot get users.");
96     return -1;
97     }
98
99 while (users->SearchNext(h, &u) == 0)
100     {
101     SetUserNotifiers(u);
102     }
103 users->CloseSearch(h);
104
105 running = true;
106 if (pthread_create(&thread, NULL, Run, this))
107     {
108     WriteServLog("TRAFFCOUNTER: Error: Cannot start thread!");
109     return -1;
110     }
111 return 0;
112 }
113 //-----------------------------------------------------------------------------
114 int TRAFFCOUNTER::Stop()
115 {
116 if (stopped)
117     return 0;
118
119 running = false;
120
121 int h = users->OpenSearch();
122 if (!h)
123     {
124     WriteServLog("TRAFFCOUNTER: Fatal error: Cannot get users.");
125     return -1;
126     }
127
128 user_iter u;
129 while (users->SearchNext(h, &u) == 0)
130     {
131     UnSetUserNotifiers(u);
132     }
133 users->CloseSearch(h);
134
135 //5 seconds to thread stops itself
136 for (int i = 0; i < 25 && !stopped; i++)
137     {
138     usleep(200000);
139     }
140
141 //after 5 seconds waiting thread still running. now kill it
142 if (!stopped)
143     {
144     printfd(__FILE__, "kill TRAFFCOUNTER thread.\n");
145     if (pthread_kill(thread, SIGINT))
146         {
147         return -1;
148         }
149     printfd(__FILE__, "TRAFFCOUNTER killed\n");
150     }
151 printfd(__FILE__, "TRAFFCOUNTER::Stop()\n");
152
153 return 0;
154 }
155 //-----------------------------------------------------------------------------
156 void * TRAFFCOUNTER::Run(void * data)
157 {
158 TRAFFCOUNTER * tc = static_cast<TRAFFCOUNTER *>(data);
159 tc->stopped = false;
160 int c = 0;
161
162 time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
163
164 while (tc->running)
165     {
166     usleep(500000);
167     if (!tc->running)
168         {
169         tc->FlushAndRemove();
170         break;
171         }
172
173     if (tc->monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
174         {
175         string monFile(tc->monitorDir + "/traffcounter_r");
176         printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", tc->monitoring, monFile.c_str());
177         touchTime = stgTime;
178         TouchFile(monFile.c_str());
179         }
180
181     if (++c % FLUSH_TIME == 0)
182         tc->FlushAndRemove();
183     }
184
185 tc->stopped = true;
186 return NULL;
187 }
188 //-----------------------------------------------------------------------------
189 void TRAFFCOUNTER::Process(const RAW_PACKET & rawPacket)
190 {
191 if (!running)
192     return;
193
194 static time_t touchTime = stgTime - MONITOR_TIME_DELAY_SEC;
195
196 if (monitoring && (touchTime + MONITOR_TIME_DELAY_SEC <= stgTime))
197     {
198     static string monFile = monitorDir + "/traffcounter_p";
199     printfd(__FILE__, "Monitor=%d file TRAFFCOUNTER %s\n", monitoring, monFile.c_str());
200     touchTime = stgTime;
201     TouchFile(monFile.c_str());
202     }
203
204 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
205
206 //printfd(__FILE__, "TRAFFCOUNTER::Process()\n");
207 //TODO replace find with lower_bound.
208
209 // Searching a new packet in a tree.
210 pp_iter pi = packets.find(rawPacket);
211
212 // Packet found - update length and time
213 if (pi != packets.end())
214     {
215     pi->second.lenU += rawPacket.GetLen();
216     pi->second.lenD += rawPacket.GetLen();
217     pi->second.updateTime = stgTime;
218     /*printfd(__FILE__, "=============================\n");
219     printfd(__FILE__, "Packet found!\n");
220     printfd(__FILE__, "Version=%d\n", rawPacket.GetIPVersion());
221     printfd(__FILE__, "HeaderLen=%d\n", rawPacket.GetHeaderLen());
222     printfd(__FILE__, "PacketLen=%d\n", rawPacket.GetLen());
223     printfd(__FILE__, "SIP=%s\n", inet_ntostring(rawPacket.GetSrcIP()).c_str());
224     printfd(__FILE__, "DIP=%s\n", inet_ntostring(rawPacket.GetDstIP()).c_str());
225     printfd(__FILE__, "src port=%d\n", rawPacket.GetSrcPort());
226     printfd(__FILE__, "pst port=%d\n", rawPacket.GetDstPort());
227     printfd(__FILE__, "len=%d\n", rawPacket.GetLen());
228     printfd(__FILE__, "proto=%d\n", rawPacket.GetProto());
229     printfd(__FILE__, "PacketDirU=%d\n", pi->second.dirU);
230     printfd(__FILE__, "PacketDirD=%d\n", pi->second.dirD);
231     printfd(__FILE__, "=============================\n");*/
232     return;
233     }
234
235 PACKET_EXTRA_DATA ed;
236
237 // Packet not found - add new packet
238
239 ed.updateTime = stgTime;
240 ed.flushTime = stgTime;
241
242 /*
243  userU is that whose user_ip == packet_ip_src
244  userD is that whose user_ip == packet_ip_dst
245  */
246
247 uint32_t ipU = rawPacket.GetSrcIP();
248 uint32_t ipD = rawPacket.GetDstIP();
249
250 // Searching users with such IP
251 if (users->FindByIPIdx(ipU, &ed.userU) == 0)
252     {
253     ed.userUPresent = true;
254     }
255
256 if (users->FindByIPIdx(ipD, &ed.userD) == 0)
257     {
258     ed.userDPresent = true;
259     }
260
261 if (ed.userUPresent ||
262     ed.userDPresent)
263     {
264     DeterminateDir(rawPacket, &ed.dirU, &ed.dirD);
265
266     ed.lenD = ed.lenU = rawPacket.GetLen();
267
268     //TODO use result of lower_bound to inserting new record
269
270     // Adding packet to a tree.
271     pair<pp_iter, bool> insertResult = packets.insert(pair<RAW_PACKET,
272                                                       PACKET_EXTRA_DATA>(rawPacket, ed));
273     pp_iter newPacket = insertResult.first;
274
275     // Adding packet reference to an IP index.
276     ip2packets.insert(pair<uint32_t, pp_iter>(ipU, newPacket));
277     ip2packets.insert(pair<uint32_t, pp_iter>(ipD, newPacket));
278     }
279 }
280 //-----------------------------------------------------------------------------
281 void TRAFFCOUNTER::FlushAndRemove()
282 {
283 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
284
285 int oldPacketsSize = packets.size();
286 int oldIp2packetsSize = ip2packets.size();
287
288 pp_iter pi;
289 pi = packets.begin();
290 std::map<RAW_PACKET, PACKET_EXTRA_DATA> newPackets;
291 ip2packets.erase(ip2packets.begin(), ip2packets.end());
292 while (pi != packets.end())
293     {
294     //Flushing
295     if (stgTime - pi->second.flushTime > FLUSH_TIME)
296         {
297         if (pi->second.userUPresent)
298             {
299             //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);
300
301             // Add stat
302             if (pi->second.dirU < DIR_NUM)
303                 {
304                 #ifdef TRAFF_STAT_WITH_PORTS
305                 pi->second.userU->AddTraffStatU(pi->second.dirU,
306                                                 pi->first.GetDstIP(),
307                                                 pi->first.GetDstPort(),
308                                                 pi->second.lenU);
309                 #else
310                 pi->second.userU->AddTraffStatU(pi->second.dirU,
311                                                 pi->first.GetDstIP(),
312                                                 pi->second.lenU);
313                 #endif
314                 }
315
316             pi->second.lenU = 0;
317             pi->second.flushTime = stgTime;
318             }
319
320         if (pi->second.userDPresent)
321             {
322             //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);
323
324             // Add stat
325             if (pi->second.dirD < DIR_NUM)
326                 {
327                 #ifdef TRAFF_STAT_WITH_PORTS
328                 pi->second.userD->AddTraffStatD(pi->second.dirD,
329                                                 pi->first.GetSrcIP(),
330                                                 pi->first.GetSrcPort(),
331                                                 pi->second.lenD);
332                 #else
333                 pi->second.userD->AddTraffStatD(pi->second.dirD,
334                                                 pi->first.GetSrcIP(),
335                                                 pi->second.lenD);
336                 #endif
337                 }
338
339             pi->second.lenD = 0;
340             pi->second.flushTime = stgTime;
341             }
342         }
343
344     /*//Removing
345     if (stgTime - pi->second.updateTime > REMOVE_TIME)
346         {
347         // Remove packet and references from ip2packets index
348         //printfd(__FILE__, "+++ Removing +++\n");
349         pair<ip2p_iter, ip2p_iter> be(
350                 ip2packets.equal_range(pi->first.GetSrcIP()));
351         while (be.first != be.second)
352             {
353             // Have a reference to a packet?
354             if (be.first->second == pi)
355                 {
356                 ip2packets.erase(be.first++);
357                 //printfd(__FILE__, "Remove U from ip2packets %s\n", inet_ntostring(pi->first.GetSrcIP()).c_str());
358                 }
359             else
360                 {
361                 ++be.first;
362                 }
363             }
364
365         //printfd(__FILE__, "-------------------\n");
366         be = ip2packets.equal_range(pi->first.GetDstIP());
367         while (be.first != be.second)
368             {
369             // Have a reference to a packet?
370             if (be.first->second == pi)
371                 {
372                 ip2packets.erase(be.first++);
373                 //printfd(__FILE__, "Remove D from ip2packets %s\n", inet_ntostring(pi->first.GetDstIP()).c_str());
374                 }
375             else
376                 {
377                 ++be.first;
378                 }
379             }
380         //printfd(__FILE__, "Remove packet\n");
381         packets.erase(pi++);
382         }
383     else
384         {
385         ++pi;
386         }*/
387     if (stgTime - pi->second.updateTime < REMOVE_TIME)
388         {
389         pair<pp_iter, bool> res = newPackets.insert(*pi);
390         if (res.second)
391             {
392             ip2packets.insert(make_pair(pi->first.GetSrcIP(), res.first));
393             ip2packets.insert(make_pair(pi->first.GetDstIP(), res.first));
394             }
395         }
396     ++pi;
397     }
398 swap(packets, newPackets);
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 lock(&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 lock(&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         fclose(f);
703         return true;
704         }
705
706     rul.proto = 0xff;
707     rul.dir = 0xff;
708
709     for (int i = 0; i < PROTOMAX; i++)
710         {
711         if (strcasecmp(tp, protoName[i]) == 0)
712             rul.proto = i;
713         }
714
715     for (int i = 0; i < DIR_NUM + 1; i++)
716         {
717         if (td == dirName[i])
718             rul.dir = i;
719         }
720
721     if (rul.dir == 0xff || rul.proto == 0xff)
722         {
723         WriteServLog("Error in file %s. Line %d.",
724                      rulesFileName.c_str(), lineNumber);
725         fclose(f);
726         return true;
727         }
728
729     if (ParseAddress(ta, &rul) != 0)
730         {
731         WriteServLog("Error in file %s. Error in adress. Line %d.",
732                      rulesFileName.c_str(), lineNumber);
733         fclose(f);
734         return true;
735         }
736     if (!test)
737         rules.push_back(rul);
738     //PrintRule(rul);
739     }
740
741 fclose(f);
742
743 // Adding lastest rule: ALL 0.0.0.0/0 NULL
744 rul.dir = DIR_NUM; //NULL
745 rul.ip = 0;  //0.0.0.0
746 rul.mask = 0;
747 rul.port1 = 0;
748 rul.port2 = 65535;
749 rul.proto = all;
750
751 if (!test)
752     rules.push_back(rul);
753
754 //PrintRule(rul);
755
756 return false;
757 }
758 //-----------------------------------------------------------------------------
759 int TRAFFCOUNTER::Reload()
760 {
761 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
762
763 if (ReadRules(true))
764     {
765     WriteServLog("TRAFFCOUNTER: Cannot reload rules. Errors found.");
766     return -1;
767     }
768
769 FreeRules();
770 ReadRules();
771 WriteServLog("TRAFFCOUNTER: Reload rules successfull.");
772 return 0;
773 }
774 //-----------------------------------------------------------------------------
775 bool TRAFFCOUNTER::ParseAddress(const char * ta, RULE * rule) const
776 {
777 char addr[50], mask[20], port1[20], port2[20], ports[40];
778
779 int len = strlen(ta);
780 char n = 0;
781 int i, p;
782 memset(addr, 0, sizeof(addr));
783 for (i = 0; i < len; i++)
784     {
785     if (ta[i] == '/' || ta[i] == ':')
786         {
787         addr[i] = 0;
788         n = ta[i];
789         break;
790         }
791     addr[i] = ta[i];
792     n = 0;
793     }
794 addr[i + 1] = 0;
795 p = i + 1;
796
797 if (n == '/')
798     {
799     // mask
800     for (; i < len; i++)
801         {
802         if (ta[i] == ':')
803             {
804             mask[i - p] = 0;
805             n = ':';
806             break;
807             }
808         mask[i - p] = ta[i];
809         }
810     mask[i - p] = 0;
811     }
812 else
813     {
814     strcpy(mask, "32");
815     }
816
817 p = i + 1;
818 i++;
819
820 if (n == ':')
821     {
822     // port
823     if (!(rule->proto == tcp || rule->proto == udp || rule->proto == tcp_udp))
824         {
825         WriteServLog("No ports specified for this protocol.");
826         return true;
827         }
828
829     for (; i < len; i++)
830         ports[i - p] = ta[i];
831
832     ports[i - p] = 0;
833     }
834 else
835     {
836     strcpy(ports, "0-65535");
837     }
838
839 char *sss;
840 char pts[100];
841 strcpy(pts, ports);
842
843 if ((sss = strchr(ports, '-')) != NULL)
844     {
845     strncpy(port1, ports, int(sss-ports));
846     port1[int(sss - ports)] = 0;
847     strcpy(port2, sss + 1);
848     }
849 else
850     {
851     strcpy(port1, ports);
852     strcpy(port2, ports);
853     }
854
855 // Convert strings to mask, ports and IP
856 int prt1, prt2, msk;
857 unsigned ip;
858 char *res;
859
860 msk = strtol(mask, &res, 10);
861 if (*res != 0)
862     return true;
863
864 prt1 = strtol(port1, &res, 10);
865 if (*res != 0)
866     return true;
867
868 prt2 = strtol(port2, &res, 10);
869 if (*res != 0)
870     return true;
871
872 int r = inet_aton(addr, (struct in_addr*)&ip);
873 if (r == 0)
874     return true;
875
876 rule->ip = ip;
877 rule->mask = CalcMask(msk);
878 //msk = 1;
879 //printfd(__FILE__, "msk=%d mask=%08X   mask=%08X\n", msk, rule->mask, (0xFFffFFff << (32 - msk)));
880
881 if ((ip & rule->mask) != ip)
882     {
883     WriteServLog("Address does'n match mask.");
884     return true;
885     }
886
887 rule->port1 = prt1;
888 rule->port2 = prt2;
889
890 return false;
891 }
892 //-----------------------------------------------------------------------------
893 uint32_t TRAFFCOUNTER::CalcMask(uint32_t msk) const
894 {
895 if (msk >= 32) return 0xFFffFFff;
896 if (msk == 0) return 0;
897 return htonl(0xFFffFFff << (32 - msk));
898 }
899 //---------------------------------------------------------------------------
900 void TRAFFCOUNTER::FreeRules()
901 {
902 rules.clear();
903 }
904 //-----------------------------------------------------------------------------
905 void TRAFFCOUNTER::PrintRule(RULE rule) const
906 {
907 printf("%15s   ", inet_ntostring(rule.ip).c_str());
908 printf("mask=%08X ", rule.mask);
909 printf("port1=%5d ", rule.port1);
910 printf("port2=%5d ", rule.port2);
911 switch (rule.proto)
912     {
913     case 0:
914         printf("TCP     ");
915         break;
916     case 1:
917         printf("UDP     ");
918         break;
919     case 2:
920         printf("ICMP    ");
921         break;
922     case 3:
923         printf("TCP_UDP ");
924         break;
925     case 4:
926         printf("ALL     ");
927         break;
928     }
929 printf("dir=%d \n", rule.dir);
930 return;
931 }
932 //-----------------------------------------------------------------------------
933 void TRAFFCOUNTER::SetMonitorDir(const string & monitorDir)
934 {
935 TRAFFCOUNTER::monitorDir = monitorDir;
936 monitoring = (monitorDir != "");
937 }
938 //-----------------------------------------------------------------------------