eye-statd.pl 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. #!/usr/bin/perl -w
  2. use utf8;
  3. use open ":encoding(utf8)";
  4. use Encode;
  5. no warnings 'utf8';
  6. use English;
  7. use base;
  8. use FindBin '$Bin';
  9. use lib "/opt/Eye/scripts";
  10. use strict;
  11. use DBI;
  12. use Time::Local;
  13. use Net::Patricia;
  14. use Data::Dumper;
  15. use Date::Parse;
  16. use DateTime;
  17. use eyelib::config;
  18. use eyelib::main;
  19. use eyelib::net_utils;
  20. use eyelib::database;
  21. use eyelib::snmp;
  22. use Socket qw(AF_INET6 inet_ntop);
  23. use IO::Socket;
  24. my $proc_name = $MY_NAME;
  25. $proc_name =~ s/\.[^.]+$//;
  26. my $pid_file = '/run/eye/'.$proc_name;
  27. my @router_ref = ();
  28. my @interfaces = ();
  29. my %proto_map = (
  30. 1 => 'ICMP', 2 => 'IGMP', 6 => 'TCP',
  31. 17 => 'UDP', 47 => 'GRE', 50 => 'ESP',
  32. 51 => 'AH', 89 => 'OSPF', 88 => 'EIGRP'
  33. );
  34. my %mute;
  35. my %routers_svi;
  36. my %routers_by_ip;
  37. my %routers;
  38. my %wan_dev;
  39. my %lan_dev;
  40. my @traffic = ();
  41. my $saving = 0;
  42. #user statistics for cached data
  43. my %user_stats;
  44. my %wan_stats;
  45. my $MAXREAD = 9216;
  46. my $timeshift = get_option($dbh,55)*60;
  47. my $save_path = get_option($dbh,72);
  48. my $thread_count = $cpu_count;
  49. #save traffic to DB
  50. my $traf_lastflush = time();
  51. # NetFlow
  52. my $server_port = 2055;
  53. my $netflow5_header_len = 24;
  54. my $netflow5_flowrec_len = 48;
  55. my $netflow9_header_len = 20;
  56. my $netflow9_templates = {};
  57. # reap dead children
  58. $SIG{CHLD} = \&REAPER;
  59. $SIG{TERM} = \&TERM;
  60. $SIG{INT} = \&TERM;
  61. $SIG{HUP} = \&INIT;
  62. if (IsNotRun($pid_file)) {
  63. Add_PID($pid_file);
  64. } else {
  65. print "Daemon $MY_NAME already running!\n";
  66. exit 100;
  67. }
  68. sub REAPER {
  69. wait;
  70. $saving = 0;
  71. $SIG{CHLD} = \&REAPER;
  72. }
  73. sub TERM {
  74. print "SIGTERM received\n";
  75. flush_traffic(1);
  76. while (wait() != -1) {}
  77. if (IsMyPID($pid_file)) { Remove_PID($pid_file); }
  78. exit 0;
  79. }
  80. sub INIT {
  81. # Create new database handle. If we can't connect, die()
  82. my $hdb = init_db();
  83. InitSubnets();
  84. init_option($hdb);
  85. #a directory for storing traffic details in text form
  86. $save_path = get_option($dbh,72);
  87. #the period for resetting statistics from netflow to billing
  88. $timeshift = get_option($hdb,55)*60;
  89. @router_ref = get_records_sql($hdb,"SELECT * FROM devices WHERE deleted=0 AND device_type=2 AND snmp_version>0 ORDER by ip" );
  90. @interfaces = get_records_sql($hdb,"SELECT * FROM `device_l3_interfaces` ORDER by device_id" );
  91. #router device_id by known device ip
  92. foreach my $row (@router_ref) {
  93. setCommunity($row);
  94. $routers{$row->{id}}=$row;
  95. my $l3_list = getIpAdEntIfIndex($row->{ip},$row->{snmp});
  96. #create hash for interface snmp index => ip-address at interface =1;
  97. foreach my $router_ip (keys %$l3_list) { $routers_svi{$row->{id}}{$l3_list->{$router_ip}}{$router_ip}=1; }
  98. #create hash by all ip-addresses for router
  99. foreach my $router_ip (keys %$l3_list) {
  100. $routers_by_ip{$router_ip}->{id}=$row->{id};
  101. if ($config_ref{save_detail}) {
  102. $routers_by_ip{$router_ip}->{save}=$row->{netflow_save};
  103. } else { $routers_by_ip{$router_ip}->{save}=0; }
  104. }
  105. }
  106. #snmp index for WAN/LAN interface by device id
  107. foreach my $row (@interfaces) {
  108. if ($row->{interface_type}) { $wan_dev{$row->{device_id}}{$row->{snmpin}}=1; } else { $lan_dev{$row->{device_id}}{$row->{snmpin}}=1; }
  109. }
  110. #get userid list
  111. my @auth_list_ref = get_records_sql($hdb,"SELECT id,ip,save_traf FROM User_auth where deleted=0 ORDER by id");
  112. foreach my $row (@auth_list_ref) {
  113. $user_stats{$row->{ip}}{auth_id}=$row->{id};
  114. if ($config_ref{save_detail}) {
  115. $user_stats{$row->{ip}}{save_traf}=$row->{save_traf};
  116. } else {
  117. $user_stats{$row->{ip}}{save_traf}=0;
  118. }
  119. }
  120. $hdb->disconnect();
  121. }
  122. ############### MAIN ##########################
  123. #close default database
  124. $dbh->disconnect();
  125. INIT();
  126. my $lsn_nflow;
  127. my $sel = IO::Select->new();
  128. # prepare to listen for NetFlow UDP packets
  129. if ($server_port > 0) {
  130. $lsn_nflow = IO::Socket::INET->new(LocalPort => $server_port, Proto => "udp")
  131. or die "Couldn't be a NetFlow UDP server on port $server_port : $@\n";
  132. $sel->add($lsn_nflow);
  133. }
  134. my ($him,$datagram,$flags);
  135. # main datagram receive loop
  136. while (1) {
  137. while (my @ready = $sel->can_read) {
  138. foreach my $server (@ready) {
  139. $him = $server->recv($datagram, $MAXREAD);
  140. next if (!$him);
  141. my ($port, $ipaddr) = sockaddr_in($server->peername);
  142. if (defined($lsn_nflow) && $server == $lsn_nflow) {
  143. my ($version) = unpack("n", $datagram);
  144. if ($version == 5) {
  145. parse_netflow_v5($datagram, $ipaddr);
  146. } elsif ($version == 9) {
  147. parse_netflow_v9($datagram, $ipaddr);
  148. } else {
  149. print "unknown NetFlow version: $version\n";
  150. }
  151. }
  152. }
  153. }
  154. }
  155. sub parse_netflow_v5 {
  156. my $datagram = shift;
  157. my $ipaddr = shift;
  158. my ($version, $count, $sysuptime, $unix_secs, $unix_nsecs,
  159. $flow_sequence, $engine_type, $engine_id, $aggregation,
  160. $agg_version) = unpack("nnNNNNCCCC", $datagram);
  161. my $flowrecs = substr($datagram, $netflow5_header_len);
  162. #0 - N 0-3 srcaddr Source IP address
  163. #1 - N 4-7 dstaddr Destination IP address
  164. #2 - N 8-11 nexthop IP address of next hop router
  165. #3 - n 12-13 input SNMP index of input interface
  166. #4 - n 14-15 output SNMP index of output interface
  167. #5 - N 16-19 dPkts Packets in the flow
  168. #6 - N 20-23 dOctets Total number of Layer 3 bytes in the packets of the flow
  169. #7 - N 24-27 First SysUptime at start of flow
  170. #8 - N 28-31 Last SysUptime at the time the last packet of the flow was received
  171. #9 - n 32-33 src_port TCP/UDP source port number or equivalent
  172. #10- n 34-35 dst_port TCP/UDP destination port number or equivalent
  173. #11- C 36 pad1 Unused (zero) byte
  174. #12- C 37 tcp_flags Cumulative OR of TCP flags
  175. #13- C 38 prot IP protocol type (for example, TCP = 6; UDP = 17)
  176. #14- C 39 tos IP type of service (ToS)
  177. #15- n 40-41 src_as Autonomous system number of the source, either origin or peer
  178. #16- n 42-43 dst_as Autonomous system number of the destination, either origin or peer
  179. #17- C 44 src_mask Source address prefix mask bits
  180. #18- C 45 dst_mask Destination address prefix mask bits
  181. #19- n 46-47 pad2 Unused (zero) bytes
  182. for (my $i = 0; $i < $count; $i++) {
  183. my $flowrec = substr($datagram, $netflow5_header_len + ($i*$netflow5_flowrec_len), $netflow5_flowrec_len);
  184. my @flowdata = unpack("NNNnnNNNNnnCCCCnnCCn", $flowrec);
  185. my %flow;
  186. $flow{src_ip} = join '.', unpack 'C4', pack 'N', $flowdata[0];
  187. $flow{dst_ip} = join '.', unpack 'C4', pack 'N', $flowdata[1];
  188. $flow{snmp_in} = $flowdata[3] || 0;
  189. $flow{snmp_out} = $flowdata[4] || 0;
  190. $flow{pkts} = $flowdata[5] || 0;
  191. $flow{octets} = $flowdata[6] || 0;
  192. $flow{src_port} = $flowdata[9] || 0;
  193. $flow{dst_port} = $flowdata[10] || 0;
  194. $flow{proto} = $flowdata[13] || 0;
  195. $flow{xsrc_ip} = $flow{src_ip};
  196. $flow{xdst_ip} = $flow{dst_ip};
  197. $flow{starttime} = time();
  198. $flow{netflow_v} = '5';
  199. $flow{ipv} = '4';
  200. save_flow($ipaddr, \%flow);
  201. }
  202. }
  203. sub parse_netflow_v9 {
  204. my $datagram = shift;
  205. my $ipaddr = shift;
  206. # Parse packet
  207. my ($version, $count, $sysuptime, $unix_secs, $seqno, $source_id, @flowsets) = unpack("nnNNNN(nnX4/a)*", $datagram);
  208. # Loop through FlowSets and take appropriate action
  209. for (my $i = 0; $i < scalar @flowsets; $i += 2) {
  210. my $flowsetid = $flowsets[$i];
  211. my $flowsetdata = substr($flowsets[$i+1], 4); # chop off id/length
  212. if ($flowsetid == 0) {
  213. # 0 = Template FlowSet
  214. parse_netflow_v9_template_flowset($flowsetdata, $ipaddr, $source_id);
  215. } elsif ($flowsetid == 1) {
  216. # 1 - Options Template FlowSet
  217. } elsif ($flowsetid > 255) {
  218. # > 255: Data FlowSet
  219. parse_netflow_v9_data_flowset($flowsetid, $flowsetdata, $ipaddr, $source_id);
  220. } else {
  221. # reserved FlowSet
  222. print "Unknown FlowSet ID $flowsetid found\n";
  223. }
  224. }
  225. }
  226. sub parse_netflow_v9_template_flowset {
  227. my $templatedata = shift;
  228. my $ipaddr = shift;
  229. my $source_id = shift;
  230. # Note: there may be multiple templates in a Template FlowSet
  231. my @template_ints = unpack("n*", $templatedata);
  232. my $i = 0;
  233. while ($i < scalar @template_ints) {
  234. my $template_id = $template_ints[$i];
  235. my $fldcount = $template_ints[$i+1];
  236. last if (!defined($template_id) || !defined($fldcount));
  237. # print "Updated template ID $template_id (source ID $source_id, from " . inet_ntoa($ipaddr) . ")\n" if ($debug);
  238. my $template = [@template_ints[($i+2) .. ($i+2+$fldcount*2-1)]];
  239. $netflow9_templates->{$ipaddr}->{$source_id}->{$template_id}->{'template'} = $template;
  240. # total length of template data
  241. my $totallen = 0;
  242. for (my $j = 1; $j < scalar @$template; $j += 2) {
  243. $totallen += $template->[$j];
  244. }
  245. $netflow9_templates->{$ipaddr}->{$source_id}->{$template_id}->{'len'} = $totallen;
  246. $i += (2 + $fldcount*2);
  247. }
  248. }
  249. sub parse_netflow_v9_data_flowset {
  250. my ($flowsetid, $flowsetdata, $ipaddr, $source_id) = @_;
  251. my $template = $netflow9_templates->{$ipaddr}->{$source_id}->{$flowsetid}->{'template'};
  252. unless (defined $template) {
  253. return;
  254. }
  255. my $len = $netflow9_templates->{$ipaddr}->{$source_id}->{$flowsetid}->{'len'};
  256. my $offset = 0;
  257. my $datalen = length($flowsetdata);
  258. while (($offset + $len) <= $datalen) {
  259. my %flow = (
  260. netflow_v => '9',
  261. starttime => time(),
  262. ipv => '4',
  263. snmp_in => 0,
  264. snmp_out => 0,
  265. octets => 0,
  266. pkts => 0
  267. );
  268. for (my $i = 0; $i < scalar @$template; $i += 2) {
  269. my $field_type = $template->[$i];
  270. my $field_length = $template->[$i+1];
  271. my $value = substr($flowsetdata, $offset, $field_length);
  272. $offset += $field_length;
  273. # IN_BYTES (1)
  274. if ($field_type == 1) {
  275. $flow{octets} = $field_length == 8 ? unpack("Q>", $value) : unpack("N", $value);
  276. }
  277. # IN_PACKETS (2)
  278. elsif ($field_type == 2) {
  279. $flow{pkts} = $field_length == 8 ? unpack("Q>", $value) : unpack("N", $value);
  280. }
  281. # IN_PROTOCOL (4)
  282. elsif ($field_type == 4) {
  283. $flow{proto} = unpack("C", $value);
  284. }
  285. # L4_SRC_PORT (7)
  286. elsif ($field_type == 7) {
  287. $flow{src_port} = unpack("n", $value);
  288. }
  289. # IPV4_SRC_ADDR (8)
  290. elsif ($field_type == 8) {
  291. $flow{src_ip} = inet_ntop(AF_INET, $value);
  292. }
  293. # INPUT_SNMP (10)
  294. elsif ($field_type == 10) {
  295. $flow{snmp_in} = $field_length == 4 ? unpack("N", $value) : unpack("n", $value);
  296. }
  297. # L4_DST_PORT (11)
  298. elsif ($field_type == 11) {
  299. $flow{dst_port} = unpack("n", $value);
  300. }
  301. # IPV4_DST_ADDR (12)
  302. elsif ($field_type == 12) {
  303. $flow{dst_ip} = inet_ntop(AF_INET, $value);
  304. }
  305. # OUTPUT_SNMP (14)
  306. elsif ($field_type == 14) {
  307. $flow{snmp_out} = $field_length == 4 ? unpack("N", $value) : unpack("n", $value);
  308. }
  309. # ICMP_TYPE (32)
  310. elsif ($field_type == 32) {
  311. $flow{icmp_type} = unpack("C", $value);
  312. }
  313. # ICMP_CODE (33)
  314. elsif ($field_type == 33) {
  315. $flow{icmp_code} = unpack("C", $value);
  316. }
  317. # IP_PROTOCOL_VERSION (60)
  318. elsif ($field_type == 60) {
  319. my $ipversion = unpack("C", $value);
  320. if ($ipversion == 6) {
  321. %flow = ();
  322. last;
  323. }
  324. $flow{ipv} = $ipversion;
  325. }
  326. # XLATE_SRC_ADDR_IPV4 (225)
  327. elsif ($field_type == 225) {
  328. $flow{xsrc_ip} = inet_ntop(AF_INET, $value);
  329. }
  330. # XLATE_DST_ADDR_IPV4 (226)
  331. elsif ($field_type == 226) {
  332. $flow{xdst_ip} = inet_ntop(AF_INET, $value);
  333. }
  334. }
  335. # Обработка не-TCP/UDP трафика
  336. if ($flow{proto} == 1) { # ICMP
  337. $flow{src_port} = $flow{icmp_type} || 0;
  338. $flow{dst_port} = $flow{icmp_code} || 0;
  339. }
  340. elsif ($flow{proto} == 2) { # IGMP
  341. $flow{src_port} = $flow{igmp_type} || 0;
  342. }
  343. elsif ($flow{proto} == 47) { # GRE
  344. $flow{src_port} = $flow{gre_version} || 0;
  345. $flow{dst_port} = $flow{gre_key} || 0;
  346. }
  347. elsif ($flow{proto} == 50 || # ESP
  348. $flow{proto} == 51) { # AH
  349. $flow{src_port} = $flow{dst_port} = 0; # Нет портов
  350. }
  351. elsif ($flow{proto} == 89) { # OSPF
  352. $flow{src_port} = $flow{dst_port} = 0;
  353. }
  354. # Сохраняем только валидные потоки
  355. if (%flow && exists $flow{src_ip} && exists $flow{dst_ip}) {
  356. save_flow($ipaddr, \%flow);
  357. }
  358. }
  359. }
  360. sub get_proto_name {
  361. my ($proto_num) = @_;
  362. return $proto_map{$proto_num} || "Proto-$proto_num";
  363. }
  364. sub save_flow {
  365. my $router_ip = shift;
  366. my $flow = shift;
  367. $router_ip = inet_ntoa($router_ip);
  368. #direction for user, 0 - in, 1 - out
  369. $flow->{direction} = '0';
  370. my $router_id;
  371. #skip unknown router
  372. if (exists $routers_by_ip{$router_ip}) {
  373. $router_id = $routers_by_ip{$router_ip}{id};
  374. $flow->{router_ip} = $router_ip;
  375. $flow->{device_id} = $router_id;
  376. $flow->{save} = $routers_by_ip{$router_ip}{save};
  377. } else {
  378. if (!exists $mute{$router_ip}) { $mute{$router_ip} = time(); }
  379. if (time() - $mute{$router_ip} >=3600) {
  380. $mute{$router_ip} = time();
  381. log_warning("Found unknown router ip [".$router_ip."] in netflow!");
  382. }
  383. return;
  384. }
  385. #skip local traffic for router
  386. if (!exists $wan_dev{$router_id}->{$flow->{snmp_out}} and ! exists $wan_dev{$router_id}->{$flow->{snmp_in}}) { return; }
  387. #detect traffic direction
  388. if (exists $wan_dev{$router_id}->{$flow->{snmp_out}}) { $flow->{direction} = 1; }
  389. push(@traffic,$flow);
  390. flush_traffic(0);
  391. }
  392. sub flush_traffic {
  393. my $force = shift || 0;
  394. if (!$force && ($saving || ((time - $traf_lastflush) < $timeshift))) { return; }
  395. $saving++;
  396. my $pid = fork();
  397. INIT();
  398. #log_debug("ROUTERS-SVI:".Dumper(\%routers_svi));
  399. #log_debug("ROUTERS by IP::".Dumper(\%routers_by_ip));
  400. #log_debug("ROUTERS:".Dumper(\%routers));
  401. #log_debug("WAN-DEVS:".Dumper(\%wan_dev));
  402. #log_debug("LAN-DEVS:".Dumper(\%lan_dev));
  403. if (!defined $pid) {
  404. $saving = 0;
  405. print "cannot fork! Save traffic and exit...\n";
  406. } elsif ($pid != 0) {
  407. # in parent
  408. $traf_lastflush = time();
  409. #clean main cache
  410. @traffic = ();
  411. return;
  412. }
  413. #create oper-cache
  414. my @flush_table = ();
  415. push(@flush_table,@traffic);
  416. my $hdb=init_db();
  417. #saved packet by users
  418. my @detail_traffic = ();
  419. my %saved_netflow = ();
  420. my %routers_found;
  421. #last packet timestamp
  422. my $last_time = time();
  423. my $start_time;
  424. foreach my $traf_record (@flush_table) {
  425. #log_debug("RAW-DATA: ".hash_to_kv_csv($traf_record));
  426. my ($auth_id,$l_src_ip,$l_dst_ip,$user_ip,$router_id);
  427. #skip unknown router
  428. next if (!$traf_record->{device_id});
  429. $router_id = $traf_record->{device_id};
  430. #prepare router traffic detailization data only if traffic retention is enabled globally
  431. if ($config_ref{save_detail} and $traf_record->{save}) {
  432. push(@{$saved_netflow{$traf_record->{device_id}}},join(';',$traf_record->{starttime},$traf_record->{proto},$traf_record->{snmp_in},$traf_record->{snmp_out},$traf_record->{src_ip},$traf_record->{dst_ip},$traf_record->{xsrc_ip},$traf_record->{xdst_ip},$traf_record->{src_port},$traf_record->{dst_port},$traf_record->{octets},$traf_record->{pkts}));
  433. }
  434. $routers_found{$router_id} = 1;
  435. #save start netflow time
  436. if (!$start_time) { $start_time = $traf_record->{starttime}; }
  437. #--- router statistics
  438. #input traffic and traffic originated from router
  439. if (!$traf_record->{snmp_out} or !$traf_record->{snmp_in}) {
  440. #input
  441. if (!$traf_record->{snmp_out} and exists $routers_svi{$router_id}{$traf_record->{snmp_in}}{$traf_record->{dst_ip}}) {
  442. # log_debug("ROUTER id: $router_id I-DATA: ".hash_to_kv_csv($traf_record));
  443. #input
  444. if (!$free_networks->match_string($traf_record->{src_ip})) {
  445. if (exists $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}) {
  446. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}+=$traf_record->{octets};
  447. } else {
  448. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}=$traf_record->{octets};
  449. }
  450. }
  451. next;
  452. }
  453. #output
  454. if (!$traf_record->{snmp_in} and exists $routers_svi{$router_id}{$traf_record->{snmp_out}}{$traf_record->{src_ip}}) {
  455. # log_debug("ROUTER id: $router_id O-DATA: ".hash_to_kv_csv($traf_record));
  456. #output
  457. if (!$free_networks->match_string($traf_record->{dst_ip})) {
  458. if (exists $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}) {
  459. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}+=$traf_record->{octets};
  460. } else {
  461. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}=$traf_record->{octets};
  462. }
  463. }
  464. next;
  465. }
  466. # log_debug("ROUTER id: $router_id U-DATA: ".hash_to_kv_csv($traf_record));
  467. #unknown packet
  468. next;
  469. }
  470. #simple output traffic from router
  471. if (exists $wan_dev{$router_id}->{$traf_record->{snmp_out}} and exists $wan_dev{$router_id}->{$traf_record->{snmp_in}}) {
  472. if (exists $routers_svi{$router_id}{$traf_record->{snmp_out}}{$traf_record->{src_ip}}) {
  473. # log_debug("ROUTER id: $router_id O-SDATA: ".hash_to_kv_csv($traf_record));
  474. #output
  475. if (!$free_networks->match_string($traf_record->{dst_ip})) {
  476. if (exists $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}) {
  477. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}+=$traf_record->{octets};
  478. } else {
  479. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}=$traf_record->{octets};
  480. }
  481. }
  482. next;
  483. }
  484. #It is unlikely that it will ever work out
  485. if (exists $routers_svi{$router_id}{$traf_record->{snmp_in}}{$traf_record->{dst_ip}}) {
  486. # log_debug("ROUTER id: $router_id I-SDATA: ".hash_to_kv_csv($traf_record));
  487. #input
  488. if (!$free_networks->match_string($traf_record->{src_ip})) {
  489. if (exists $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}) {
  490. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}+=$traf_record->{octets};
  491. } else {
  492. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}=$traf_record->{octets};
  493. }
  494. }
  495. next;
  496. }
  497. # log_debug("ROUTER id: $router_id U-SDATA: ".hash_to_kv_csv($traf_record));
  498. #unknown packet
  499. next;
  500. } else {
  501. #forward
  502. if (!$free_networks->match_string($traf_record->{src_ip}) and !$free_networks->match_string($traf_record->{dst_ip})) {
  503. if ($traf_record->{direction}) {
  504. # log_debug("ROUTER id: $router_id FO-DATA: ".hash_to_kv_csv($traf_record));
  505. #out
  506. if (exists $wan_stats{$router_id}{$traf_record->{snmp_out}}{forward_out}) {
  507. $wan_stats{$router_id}{$traf_record->{snmp_out}}{forward_out}+=$traf_record->{octets};
  508. } else {
  509. $wan_stats{$router_id}{$traf_record->{snmp_out}}{forward_out}+=$traf_record->{octets};
  510. }
  511. } else {
  512. # log_debug("ROUTER id: $router_id FI-DATA: ".hash_to_kv_csv($traf_record));
  513. #in
  514. if (exists $wan_stats{$router_id}{$traf_record->{snmp_in}}{forward_in}) {
  515. $wan_stats{$router_id}{$traf_record->{snmp_in}}{forward_in}+=$traf_record->{octets};
  516. } else {
  517. $wan_stats{$router_id}{$traf_record->{snmp_in}}{forward_in}+=$traf_record->{octets};
  518. }
  519. }
  520. } else {
  521. # log_debug("ROUTER id: $router_id FREE-DATA: ".hash_to_kv_csv($traf_record));
  522. }
  523. }
  524. #--- user statistics
  525. my $free = 0;
  526. if ($traf_record->{direction}) {
  527. #outbound traffic
  528. if (exists $user_stats{$traf_record->{src_ip}}) {
  529. $user_ip = $traf_record->{src_ip};
  530. $l_src_ip = $traf_record->{src_ip};
  531. $l_dst_ip = $traf_record->{dst_ip};
  532. $free = $free_networks->match_string($l_dst_ip);
  533. #skip calculate free net
  534. if (!$free) {
  535. if (exists $user_stats{$user_ip}{$router_id}{out}) {
  536. $user_stats{$user_ip}{$router_id}{out}+=$traf_record->{octets};
  537. } else {
  538. $user_stats{$user_ip}{$router_id}{out}=$traf_record->{octets};
  539. }
  540. if (exists $user_stats{$user_ip}{$router_id}{pkt_out}) {
  541. $user_stats{$user_ip}{$router_id}{pkt_out}+=$traf_record->{pkts};
  542. } else {
  543. $user_stats{$user_ip}{$router_id}{pkt_out}=$traf_record->{pkts};
  544. }
  545. }
  546. }
  547. #a new user is created only by the presence of outgoing traffic
  548. if (!$user_ip and $config_ref{add_unknown_user}) {
  549. #skip create router interface as user
  550. if (exists $routers_by_ip{$traf_record->{src_ip}}) { next; }
  551. if (!$office_networks->match_string($traf_record->{src_ip})) {
  552. log_debug("Unknown src network ".hash_to_kv_csv($traf_record));
  553. next;
  554. }
  555. $user_ip = $traf_record->{src_ip};
  556. $auth_id = new_auth($hdb,$user_ip);
  557. if (!$auth_id) { next; }
  558. $l_src_ip = $traf_record->{src_ip};
  559. $l_dst_ip = $traf_record->{dst_ip};
  560. $user_stats{$user_ip}{auth_id}=$auth_id;
  561. $user_stats{$user_ip}{$router_id}{in}=0;
  562. $user_stats{$user_ip}{$router_id}{pkt_in}=0;
  563. $user_stats{$user_ip}{$router_id}{out}=0;
  564. $user_stats{$user_ip}{$router_id}{pkt_out}=0;
  565. $user_stats{$user_ip}{save_traf}=$config_ref{save_detail};
  566. $free = $free_networks->match_string($l_dst_ip);
  567. #skip calculate free net
  568. if (!$free) {
  569. $user_stats{$user_ip}{$router_id}{out}=$traf_record->{octets};
  570. $user_stats{$user_ip}{$router_id}{pkt_out}=$traf_record->{pkts};
  571. }
  572. }
  573. } else {
  574. #inbound traffic
  575. if (exists $user_stats{$traf_record->{xdst_ip}}) {
  576. $user_ip = $traf_record->{xdst_ip};
  577. $l_src_ip = $traf_record->{src_ip};
  578. $l_dst_ip = $traf_record->{xdst_ip};
  579. $free = $free_networks->match_string($l_src_ip);
  580. #skip calculate free net
  581. if (!$free) {
  582. if (exists $user_stats{$user_ip}{$router_id}{in}) {
  583. $user_stats{$user_ip}{$router_id}{in}+=$traf_record->{octets};
  584. } else {
  585. $user_stats{$user_ip}{$router_id}{in}=$traf_record->{octets};
  586. }
  587. if (exists $user_stats{$user_ip}{$router_id}{pkt_in}) {
  588. $user_stats{$user_ip}{$router_id}{pkt_in}+=$traf_record->{pkts};
  589. } else {
  590. $user_stats{$user_ip}{$router_id}{pkt_in}=$traf_record->{pkts};
  591. }
  592. }
  593. }
  594. }
  595. if (!$user_ip) {
  596. log_debug("Unknown USER: ".hash_to_kv_csv($traf_record));
  597. next;
  598. }
  599. $last_time = $traf_record->{starttime};
  600. $user_stats{$user_ip}{last_found} = $last_time;
  601. next if (!$config_ref{save_detail} and !$user_stats{$user_ip}{save_traf});
  602. my $l_src_ip_aton=StrToIp($l_src_ip);
  603. my $l_dst_ip_aton=StrToIp($l_dst_ip);
  604. my ($sec,$min,$hour,$day,$month,$year,$zone) = (localtime($last_time))[0,1,2,3,4,5];
  605. $month++;
  606. $year += 1900;
  607. my $full_time = sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  608. my @detail_array = ($user_stats{$user_ip}->{auth_id},$router_id,$full_time,$traf_record->{proto},$l_src_ip_aton,$l_dst_ip_aton,$traf_record->{src_port},$traf_record->{dst_port},$traf_record->{octets},$traf_record->{pkts});
  609. push(@detail_traffic,\@detail_array);
  610. }
  611. @flush_table=();
  612. #start hour
  613. my ($sec,$min,$hour,$day,$month,$year) = (localtime($last_time))[0,1,2,3,4,5];
  614. #save netflow
  615. if ($config_ref{save_detail}) {
  616. $save_path=~s/\/$//;
  617. foreach my $dev_id (keys %saved_netflow) {
  618. my $netflow_file_path = $save_path.'/'.$dev_id.'/'.sprintf "%04d/%02d/%02d/%02d/",$year+1900,$month+1,$day,$hour;
  619. my $nmin = int($min/10)*10;
  620. my $netflow_file_name = $netflow_file_path.sprintf "%04d%02d%02d-%02d%02d.csv",$year+1900,$month+1,$day,$hour,$nmin;
  621. if ($saved_netflow{$dev_id} and scalar @{$saved_netflow{$dev_id}}) {
  622. use File::Path;
  623. File::Path::make_path($netflow_file_path);
  624. if ( -e $netflow_file_name) {
  625. open (ND,">>$netflow_file_name") || die("Error open file $netflow_file_name!!! die...");
  626. binmode(ND,':utf8');
  627. } else {
  628. open (ND,">$netflow_file_name") || die("Error open file $netflow_file_name!!! die...");
  629. binmode(ND,':utf8');
  630. print ND join(';',"time","proto","snmp_in","snmp_out","src_ip","dst_ip","xsrc_ip","xdst_ip","src_port","dst_port","octets","pkts")."\n";
  631. }
  632. foreach my $row (@{$saved_netflow{$dev_id}}) {
  633. next if (!$row);
  634. print ND $row."\n";
  635. }
  636. close ND;
  637. @{$saved_netflow{$dev_id}}=();
  638. }
  639. }
  640. }
  641. undef %saved_netflow;
  642. #save statistics
  643. #start stat time
  644. my $hour_date1 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
  645. #end hour
  646. ($hour,$day,$month,$year) = (localtime($last_time+3600))[2,3,4,5];
  647. my $hour_date2 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
  648. my @batch_sql_traf=();
  649. #log_debug("User STATS: ".Dumper(\%user_stats));
  650. # update database
  651. foreach my $user_ip (keys %user_stats) {
  652. next if (!exists $user_stats{$user_ip}{last_found});
  653. my $user_ip_aton=StrToIp($user_ip);
  654. my $auth_id = $user_stats{$user_ip}{auth_id};
  655. #last flow for user
  656. my ($sec,$min,$hour,$day,$month,$year) = (localtime($user_stats{$user_ip}{last_found}))[0,1,2,3,4,5];
  657. #flow time string
  658. my $flow_date = $hdb->quote(sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec);
  659. #last found timestamp
  660. my $tSQL="UPDATE User_auth SET `last_found`=$flow_date WHERE id='$auth_id'";
  661. push (@batch_sql_traf,$tSQL);
  662. #per router stats
  663. foreach my $router_id (keys %routers_found) {
  664. next if (!exists $user_stats{$user_ip}{$router_id});
  665. if (!exists $user_stats{$user_ip}{$router_id}{in}) { $user_stats{$user_ip}{$router_id}{in} = 0; }
  666. if (!exists $user_stats{$user_ip}{$router_id}{out}) { $user_stats{$user_ip}{$router_id}{out} = 0; }
  667. #skip empty stats
  668. if ($user_stats{$user_ip}{$router_id}{in} + $user_stats{$user_ip}{$router_id}{out} ==0) { next; }
  669. #packet count per router
  670. if (!exists $user_stats{$user_ip}{$router_id}{pkt_in}) { $user_stats{$user_ip}{$router_id}{pkt_in} = 0; }
  671. if (!exists $user_stats{$user_ip}{$router_id}{pkt_out}) { $user_stats{$user_ip}{$router_id}{pkt_out} = 0; }
  672. #current stats
  673. my $tSQL="INSERT INTO User_stats_full (timestamp,auth_id,router_id,byte_in,byte_out,pkt_in,pkt_out,step) VALUES($flow_date,'$auth_id','$router_id','$user_stats{$user_ip}{$router_id}{in}','$user_stats{$user_ip}{$router_id}{out}','$user_stats{$user_ip}{$router_id}{pkt_in}','$user_stats{$user_ip}{$router_id}{pkt_out}','$timeshift')";
  674. push (@batch_sql_traf,$tSQL);
  675. #hour stats
  676. # get current stats
  677. my $sql = "SELECT id, byte_in, byte_out FROM User_stats WHERE `timestamp`>=$hour_date1 AND `timestamp`<$hour_date2 AND router_id=$router_id AND auth_id=$auth_id";
  678. my $hour_stat = get_record_sql($hdb,$sql);
  679. if (!$hour_stat) {
  680. my $dSQL="INSERT INTO User_stats (timestamp,auth_id,router_id,byte_in,byte_out) VALUES($flow_date,'$auth_id','$router_id','$user_stats{$user_ip}{$router_id}{in}','$user_stats{$user_ip}{$router_id}{out}')";
  681. push (@batch_sql_traf,$dSQL);
  682. next;
  683. }
  684. if (!$hour_stat->{byte_in}) { $hour_stat->{byte_in}=0; }
  685. if (!$hour_stat->{byte_out}) { $hour_stat->{byte_out}=0; }
  686. $hour_stat->{byte_in} += $user_stats{$user_ip}{$router_id}{in};
  687. $hour_stat->{byte_out} += $user_stats{$user_ip}{$router_id}{out};
  688. $tSQL="UPDATE User_stats SET byte_in='".$hour_stat->{byte_in}."', byte_out='".$hour_stat->{byte_out}."' WHERE id='".$auth_id."' AND router_id='".$router_id."'";
  689. push (@batch_sql_traf,$tSQL);
  690. }
  691. }
  692. #print Dumper(\%wan_stats) if ($debug);
  693. # update database
  694. foreach my $router_id (keys %wan_stats) {
  695. #last flow for user
  696. my ($sec,$min,$hour,$day,$month,$year) = (localtime($start_time))[0,1,2,3,4,5];
  697. #flow time string
  698. my $flow_date = $hdb->quote(sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec);
  699. #per interface stats
  700. foreach my $int_id (keys %{$wan_stats{$router_id}}) {
  701. if (!$wan_stats{$router_id}{$int_id}{in}) { $wan_stats{$router_id}{$int_id}{in} = 0; }
  702. if (!$wan_stats{$router_id}{$int_id}{out}) { $wan_stats{$router_id}{$int_id}{out} = 0; }
  703. if (!$wan_stats{$router_id}{$int_id}{forward_in}) { $wan_stats{$router_id}{$int_id}{forward_in} = 0; }
  704. if (!$wan_stats{$router_id}{$int_id}{forward_out}) { $wan_stats{$router_id}{$int_id}{forward_out} = 0; }
  705. #skip empty stats
  706. if ($wan_stats{$router_id}{$int_id}{in} + $wan_stats{$router_id}{$int_id}{out} + $wan_stats{$router_id}{$int_id}{forward_in} + $wan_stats{$router_id}{$int_id}{forward_out} ==0) { next; }
  707. #current stats
  708. my $tSQL="INSERT INTO Wan_stats (`time`,`router_id`,`interface_id`,`in`,`out`,`forward_in`,`forward_out`) VALUES($flow_date,'$router_id','$int_id','$wan_stats{$router_id}{$int_id}{in}','$wan_stats{$router_id}{$int_id}{out}','$wan_stats{$router_id}{$int_id}{forward_in}','$wan_stats{$router_id}{$int_id}{forward_out}')";
  709. push (@batch_sql_traf,$tSQL);
  710. }
  711. }
  712. #update statistics in DB
  713. batch_db_sql($hdb,\@batch_sql_traf);
  714. @batch_sql_traf = ();
  715. if ($config_ref{enable_quotes}) {
  716. db_log_debug($hdb,"Recalc quotes started");
  717. foreach my $router_id (keys %routers_found) { recalc_quotes($hdb,$router_id); }
  718. db_log_debug($hdb,"Recalc quotes stopped");
  719. }
  720. if (scalar(@detail_traffic)) {
  721. db_log_debug($hdb,"Start write traffic detail to DB. ".scalar @detail_traffic." lines count") if ($debug);
  722. #mysql dont work at parallel table lock
  723. batch_db_sql_csv("Traffic_detail", \@detail_traffic);
  724. @detail_traffic = ();
  725. db_log_debug($hdb,"Write traffic detail to DB stopped") if ($debug);
  726. }
  727. $hdb->disconnect();
  728. $saving = 0;
  729. exit;
  730. }
  731. if (IsMyPID($pid_file)) { Remove_PID($pid_file); }
  732. exit;