eye-statd.pl 28 KB

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