eye-statd.pl 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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. if ($traf_record->{save}) {
  399. 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}));
  400. }
  401. $routers_found{$router_id} = 1;
  402. #save start netflow time
  403. if (!$start_time) { $start_time = $traf_record->{starttime}; }
  404. #--- router statistics
  405. #input traffic and traffic originated from router
  406. if (!$traf_record->{snmp_out} or !$traf_record->{snmp_in}) {
  407. #input
  408. if (!$traf_record->{snmp_out} and exists $routers_svi{$router_id}{$traf_record->{snmp_in}}{$traf_record->{dst_ip}}) {
  409. #input
  410. if (!$free_networks->match_string($traf_record->{src_ip})) {
  411. if (exists $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}) {
  412. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}+=$traf_record->{octets};
  413. } else {
  414. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}=$traf_record->{octets};
  415. }
  416. }
  417. next;
  418. }
  419. #output
  420. if (!$traf_record->{snmp_in} and exists $routers_svi{$router_id}{$traf_record->{snmp_out}}{$traf_record->{src_ip}}) {
  421. #output
  422. if (!$free_networks->match_string($traf_record->{dst_ip})) {
  423. if (exists $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}) {
  424. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}+=$traf_record->{octets};
  425. } else {
  426. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}=$traf_record->{octets};
  427. }
  428. }
  429. next;
  430. }
  431. #unknown packet
  432. next;
  433. }
  434. #simple output traffic from router
  435. if (exists $wan_dev{$router_id}->{$traf_record->{snmp_out}} and exists $wan_dev{$router_id}->{$traf_record->{snmp_in}}) {
  436. if (exists $routers_svi{$router_id}{$traf_record->{snmp_out}}{$traf_record->{src_ip}}) {
  437. #output
  438. if (!$free_networks->match_string($traf_record->{dst_ip})) {
  439. if (exists $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}) {
  440. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}+=$traf_record->{octets};
  441. } else {
  442. $wan_stats{$router_id}{$traf_record->{snmp_out}}{out}=$traf_record->{octets};
  443. }
  444. }
  445. next;
  446. }
  447. #It is unlikely that it will ever work out
  448. if (exists $routers_svi{$router_id}{$traf_record->{snmp_in}}{$traf_record->{dst_ip}}) {
  449. #input
  450. if (!$free_networks->match_string($traf_record->{src_ip})) {
  451. if (exists $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}) {
  452. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}+=$traf_record->{octets};
  453. } else {
  454. $wan_stats{$router_id}{$traf_record->{snmp_in}}{in}=$traf_record->{octets};
  455. }
  456. }
  457. next;
  458. }
  459. #unknown packet
  460. next;
  461. } else {
  462. #forward
  463. if (!$free_networks->match_string($traf_record->{src_ip}) and !$free_networks->match_string($traf_record->{dst_ip})) {
  464. if ($traf_record->{direction}) {
  465. #out
  466. if (exists $wan_stats{$router_id}{$traf_record->{snmp_out}}{forward_out}) {
  467. $wan_stats{$router_id}{$traf_record->{snmp_out}}{forward_out}+=$traf_record->{octets};
  468. } else {
  469. $wan_stats{$router_id}{$traf_record->{snmp_out}}{forward_out}+=$traf_record->{octets};
  470. }
  471. } else {
  472. #in
  473. if (exists $wan_stats{$router_id}{$traf_record->{snmp_in}}{forward_in}) {
  474. $wan_stats{$router_id}{$traf_record->{snmp_in}}{forward_in}+=$traf_record->{octets};
  475. } else {
  476. $wan_stats{$router_id}{$traf_record->{snmp_in}}{forward_in}+=$traf_record->{octets};
  477. }
  478. }
  479. }
  480. }
  481. #--- user statistics
  482. my $free = 0;
  483. if ($traf_record->{direction}) {
  484. #outbound traffic
  485. if (exists $user_stats{$traf_record->{src_ip}}) {
  486. $user_ip = $traf_record->{src_ip};
  487. $l_src_ip = $traf_record->{src_ip};
  488. $l_dst_ip = $traf_record->{dst_ip};
  489. $free = $free_networks->match_string($l_dst_ip);
  490. #skip calculate free net
  491. if (!$free) {
  492. if (exists $user_stats{$user_ip}{$router_id}{out}) {
  493. $user_stats{$user_ip}{$router_id}{out}+=$traf_record->{octets};
  494. } else {
  495. $user_stats{$user_ip}{$router_id}{out}=$traf_record->{octets};
  496. }
  497. if (exists $user_stats{$user_ip}{$router_id}{pkt_out}) {
  498. $user_stats{$user_ip}{$router_id}{pkt_out}+=$traf_record->{pkts};
  499. } else {
  500. $user_stats{$user_ip}{$router_id}{pkt_out}=$traf_record->{pkts};
  501. }
  502. }
  503. }
  504. #a new user is created only by the presence of outgoing traffic
  505. if (!$user_ip and $config_ref{add_unknown_user}) {
  506. #skip create router interface as user
  507. if (exists $routers_by_ip{$traf_record->{src_ip}}) { next; }
  508. if (!$office_networks->match_string($traf_record->{src_ip})) {
  509. 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}");
  510. next;
  511. }
  512. $user_ip = $traf_record->{src_ip};
  513. $auth_id = new_auth($hdb,$user_ip);
  514. $l_src_ip = $traf_record->{src_ip};
  515. $l_dst_ip = $traf_record->{dst_ip};
  516. $user_stats{$user_ip}{auth_id}=$auth_id;
  517. $user_stats{$user_ip}{$router_id}{in}=0;
  518. $user_stats{$user_ip}{$router_id}{pkt_in}=0;
  519. $user_stats{$user_ip}{$router_id}{out}=0;
  520. $user_stats{$user_ip}{$router_id}{pkt_out}=0;
  521. $user_stats{$user_ip}{save_traf}=$config_ref{save_detail};
  522. $free = $free_networks->match_string($l_dst_ip);
  523. #skip calculate free net
  524. if (!$free) {
  525. $user_stats{$user_ip}{$router_id}{out}=$traf_record->{octets};
  526. $user_stats{$user_ip}{$router_id}{pkt_out}=$traf_record->{pkts};
  527. }
  528. }
  529. } else {
  530. #inbound traffic
  531. if (exists $user_stats{$traf_record->{xdst_ip}}) {
  532. $user_ip = $traf_record->{xdst_ip};
  533. $l_src_ip = $traf_record->{src_ip};
  534. $l_dst_ip = $traf_record->{xdst_ip};
  535. $free = $free_networks->match_string($l_src_ip);
  536. #skip calculate free net
  537. if (!$free) {
  538. if (exists $user_stats{$user_ip}{$router_id}{in}) {
  539. $user_stats{$user_ip}{$router_id}{in}+=$traf_record->{octets};
  540. } else {
  541. $user_stats{$user_ip}{$router_id}{in}=$traf_record->{octets};
  542. }
  543. if (exists $user_stats{$user_ip}{$router_id}{pkt_in}) {
  544. $user_stats{$user_ip}{$router_id}{pkt_in}+=$traf_record->{pkts};
  545. } else {
  546. $user_stats{$user_ip}{$router_id}{pkt_in}=$traf_record->{pkts};
  547. }
  548. }
  549. }
  550. if (!$user_ip) {
  551. 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}");
  552. }
  553. }
  554. next if (!$user_ip);
  555. $last_time = $traf_record->{starttime};
  556. $user_stats{$user_ip}{last_found} = $last_time;
  557. next if (!$config_ref{save_detail} and !$user_stats{$user_ip}{save_traf});
  558. my $l_src_ip_aton=StrToIp($l_src_ip);
  559. my $l_dst_ip_aton=StrToIp($l_dst_ip);
  560. my ($sec,$min,$hour,$day,$month,$year,$zone) = (localtime($last_time))[0,1,2,3,4,5];
  561. $month++;
  562. $year += 1900;
  563. my $full_time = sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  564. 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});
  565. push(@detail_traffic,\@detail_array);
  566. }
  567. @flush_table=();
  568. #start hour
  569. my ($sec,$min,$hour,$day,$month,$year) = (localtime($last_time))[0,1,2,3,4,5];
  570. #save netflow
  571. if ($config_ref{save_detail}) {
  572. $save_path=~s/\/$//;
  573. foreach my $dev_id (keys %saved_netflow) {
  574. my $netflow_file_path = $save_path.'/'.$dev_id.'/'.sprintf "%04d/%02d/%02d/%02d/",$year+1900,$month+1,$day,$hour;
  575. my $nmin = int($min/10)*10;
  576. my $netflow_file_name = $netflow_file_path.sprintf "%04d%02d%02d-%02d%02d.csv",$year+1900,$month+1,$day,$hour,$nmin;
  577. if ($saved_netflow{$dev_id} and scalar @{$saved_netflow{$dev_id}}) {
  578. use File::Path;
  579. File::Path::make_path($netflow_file_path);
  580. if ( -e $netflow_file_name) {
  581. open (ND,">>$netflow_file_name") || die("Error open file $netflow_file_name!!! die...");
  582. binmode(ND,':utf8');
  583. } else {
  584. open (ND,">$netflow_file_name") || die("Error open file $netflow_file_name!!! die...");
  585. binmode(ND,':utf8');
  586. print ND join(';',"time","proto","snmp_in","snmp_out","src_ip","dst_ip","xsrc_ip","xdst_ip","src_port","dst_port","octets","pkts")."\n";
  587. }
  588. foreach my $row (@{$saved_netflow{$dev_id}}) {
  589. next if (!$row);
  590. print ND $row."\n";
  591. }
  592. close ND;
  593. @{$saved_netflow{$dev_id}}=();
  594. }
  595. }
  596. }
  597. undef %saved_netflow;
  598. #save statistics
  599. #start stat time
  600. my $hour_date1 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
  601. #end hour
  602. ($hour,$day,$month,$year) = (localtime($last_time+3600))[2,3,4,5];
  603. my $hour_date2 = $hdb->quote(sprintf "%04d-%02d-%02d %02d:00:00",$year+1900,$month+1,$day,$hour);
  604. my @batch_sql_traf=();
  605. #print Dumper(\%user_stats) if ($debug);
  606. # update database
  607. foreach my $user_ip (keys %user_stats) {
  608. next if (!exists $user_stats{$user_ip}{last_found});
  609. my $user_ip_aton=StrToIp($user_ip);
  610. my $auth_id = $user_stats{$user_ip}{auth_id};
  611. #last flow for user
  612. my ($sec,$min,$hour,$day,$month,$year) = (localtime($user_stats{$user_ip}{last_found}))[0,1,2,3,4,5];
  613. #flow time string
  614. my $flow_date = $hdb->quote(sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec);
  615. #last found timestamp
  616. my $tSQL="UPDATE User_auth SET `last_found`=$flow_date WHERE id='$auth_id'";
  617. push (@batch_sql_traf,$tSQL);
  618. #per router stats
  619. foreach my $router_id (keys %routers_found) {
  620. next if (!exists $user_stats{$user_ip}{$router_id});
  621. if (!exists $user_stats{$user_ip}{$router_id}{in}) { $user_stats{$user_ip}{$router_id}{in} = 0; }
  622. if (!exists $user_stats{$user_ip}{$router_id}{out}) { $user_stats{$user_ip}{$router_id}{out} = 0; }
  623. #skip empty stats
  624. if ($user_stats{$user_ip}{$router_id}{in} + $user_stats{$user_ip}{$router_id}{out} ==0) { next; }
  625. #packet count per router
  626. if (!exists $user_stats{$user_ip}{$router_id}{pkt_in}) { $user_stats{$user_ip}{$router_id}{pkt_in} = 0; }
  627. if (!exists $user_stats{$user_ip}{$router_id}{pkt_out}) { $user_stats{$user_ip}{$router_id}{pkt_out} = 0; }
  628. #current stats
  629. 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')";
  630. push (@batch_sql_traf,$tSQL);
  631. #hour stats
  632. # get current stats
  633. 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";
  634. my $hour_stat = get_record_sql($hdb,$sql);
  635. if (!$hour_stat) {
  636. 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}')";
  637. push (@batch_sql_traf,$dSQL);
  638. next;
  639. }
  640. if (!$hour_stat->{byte_in}) { $hour_stat->{byte_in}=0; }
  641. if (!$hour_stat->{byte_out}) { $hour_stat->{byte_out}=0; }
  642. $hour_stat->{byte_in} += $user_stats{$user_ip}{$router_id}{in};
  643. $hour_stat->{byte_out} += $user_stats{$user_ip}{$router_id}{out};
  644. $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."'";
  645. push (@batch_sql_traf,$tSQL);
  646. }
  647. }
  648. #print Dumper(\%wan_stats) if ($debug);
  649. # update database
  650. foreach my $router_id (keys %wan_stats) {
  651. #last flow for user
  652. my ($sec,$min,$hour,$day,$month,$year) = (localtime($start_time))[0,1,2,3,4,5];
  653. #flow time string
  654. my $flow_date = $hdb->quote(sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year+1900,$month+1,$day,$hour,$min,$sec);
  655. #per interface stats
  656. foreach my $int_id (keys %{$wan_stats{$router_id}}) {
  657. if (!$wan_stats{$router_id}{$int_id}{in}) { $wan_stats{$router_id}{$int_id}{in} = 0; }
  658. if (!$wan_stats{$router_id}{$int_id}{out}) { $wan_stats{$router_id}{$int_id}{out} = 0; }
  659. if (!$wan_stats{$router_id}{$int_id}{forward_in}) { $wan_stats{$router_id}{$int_id}{forward_in} = 0; }
  660. if (!$wan_stats{$router_id}{$int_id}{forward_out}) { $wan_stats{$router_id}{$int_id}{forward_out} = 0; }
  661. #skip empty stats
  662. 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; }
  663. #current stats
  664. 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}')";
  665. push (@batch_sql_traf,$tSQL);
  666. }
  667. }
  668. #update statistics in DB
  669. batch_db_sql($hdb,\@batch_sql_traf);
  670. if ($config_ref{enable_quotes}) {
  671. db_log_debug($hdb,"Recalc quotes started");
  672. foreach my $router_id (keys %routers_found) { recalc_quotes($hdb,$router_id); }
  673. db_log_debug($hdb,"Recalc quotes stopped");
  674. }
  675. if (scalar(@detail_traffic)) {
  676. db_log_debug($hdb,"Start write traffic detail to DB. ".scalar @detail_traffic." lines count") if ($debug);
  677. #mysql dont work at parallel table lock
  678. if ($config_ref{DBTYPE} eq 'mysql') {
  679. batch_db_sql_csv("Traffic_detail", \@detail_traffic);
  680. } else {
  681. my $index = 0;
  682. my @tmp=();
  683. my $item_per_thread = int(scalar @detail_traffic / $thread_count);
  684. my @threads=();
  685. foreach my $row (@detail_traffic) {
  686. push(@tmp,$row);
  687. $index++;
  688. if ($index<=$item_per_thread) { next; }
  689. my @tmp1=();
  690. push(@tmp1,@tmp);
  691. @tmp=();
  692. push(@threads, threads->create(\&batch_db_sql_csv, "Traffic_detail", \@tmp1));
  693. }
  694. if (scalar(@tmp)) {
  695. push(@threads, threads->create(\&batch_db_sql_csv, "Traffic_detail", \@tmp));
  696. }
  697. foreach my $t (@threads) { $t->join(); }
  698. @tmp=();
  699. }
  700. @detail_traffic = ();
  701. db_log_debug($hdb,"Write traffic detail to DB stopped") if ($debug);
  702. }
  703. $hdb->disconnect();
  704. $saving = 0;
  705. exit;
  706. }
  707. if (IsMyPID($pid_file)) { Remove_PID($pid_file); }
  708. exit;