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