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