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