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