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