eye-statd.pl 27 KB

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