eye-statd.pl 28 KB

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