fetch_new_arp.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. #!/usr/bin/perl
  2. #
  3. # Copyright (C) Roman Dmitiriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use Encode;
  8. no warnings 'utf8';
  9. use English;
  10. use base;
  11. use FindBin '$Bin';
  12. use lib "/opt/Eye/scripts";
  13. use strict;
  14. use DBI;
  15. use Time::Local;
  16. use Net::Patricia;
  17. use Data::Dumper;
  18. use Date::Parse;
  19. use Socket;
  20. use eyelib::config;
  21. use eyelib::main;
  22. use eyelib::net_utils;
  23. use eyelib::snmp;
  24. use eyelib::database;
  25. use NetAddr::IP;
  26. use Fcntl qw(:flock);
  27. use Parallel::ForkManager;
  28. open(SELF,"<",$0) or die "Cannot open $0 - $!";
  29. flock(SELF, LOCK_EX|LOCK_NB) or exit 1;
  30. setpriority(0,0,19);
  31. if ($config_ref{config_mode}) { log_info("System in configuration mode! Skip discovery."); exit; }
  32. my %mac_history;
  33. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  34. $month += 1;
  35. $year += 1900;
  36. my $fork_count = $cpu_count*5;
  37. #disable fork for debug
  38. #if ($debug) { $fork_count = 0; }
  39. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  40. my $now_day=sprintf "%04d-%02d-%02d",$year,$month,$day;
  41. db_log_verbose($dbh,'Arp discovery started.');
  42. if ($ARGV[0]) {
  43. db_log_verbose($dbh,'Active check started!');
  44. my $subnets=get_subnets_ref($dbh);
  45. my @fping_cmd=();
  46. foreach my $net (keys %$subnets) {
  47. next if (!$net);
  48. next if (!$subnets->{$net}{discovery});
  49. my $run_cmd="$fping -g $subnets->{$net}{subnet} -B1.0 -c 1 >/dev/null 2>&1";
  50. db_log_debug($dbh,"Checked network $subnets->{$net}{subnet}") if ($debug);
  51. push(@fping_cmd,$run_cmd);
  52. }
  53. $parallel_process_count = $cpu_count*2;
  54. run_in_parallel(@fping_cmd);
  55. }
  56. my @router_ref = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND (device_type=2 or device_type=0) AND discovery=1 AND snmp_version>0 ORDER by ip" );
  57. $dbh->disconnect;
  58. my @arp_array=();
  59. my $pm_arp = Parallel::ForkManager->new($fork_count);
  60. # data structure retrieval and handling
  61. $pm_arp -> run_on_finish (
  62. sub {
  63. my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
  64. if (defined($data_structure_reference)) {
  65. # children are not forced to send anything
  66. my $result = ${$data_structure_reference};
  67. push(@arp_array,$result);
  68. }
  69. }
  70. );
  71. DATA_LOOP:
  72. foreach my $router (@router_ref) {
  73. my $router_ip=$router->{ip};
  74. setCommunity($router);
  75. if (!HostIsLive($router_ip)) { log_info("Host id: $router->{id} name: $router->{device_name} ip: $router_ip is down! Skip."); next; }
  76. $pm_arp->start() and next DATA_LOOP;
  77. my $arp_table;
  78. my $tmp_dbh=init_db();
  79. if (apply_device_lock($tmp_dbh,$router->{id})) {
  80. $arp_table=get_arp_table($router_ip,$router->{snmp});
  81. unset_lock_discovery($tmp_dbh,$router->{id});
  82. }
  83. $tmp_dbh->disconnect;
  84. $pm_arp->finish(0, \$arp_table);
  85. }
  86. $pm_arp->wait_all_children;
  87. ########################### end fork's #########################
  88. $dbh=init_db();
  89. #get userid list
  90. my @authlist_ref = get_records_sql($dbh,"SELECT * FROM User_auth WHERE deleted=0 ORDER by ip_int" );
  91. my $users = new Net::Patricia;
  92. my %ip_list;
  93. my %oper_arp_list;
  94. foreach my $row (@authlist_ref) {
  95. $users->add_string($row->{ip},$row->{id});
  96. $ip_list{$row->{id}}->{id}=$row->{id};
  97. $ip_list{$row->{id}}->{ip}=$row->{ip};
  98. $ip_list{$row->{id}}->{mac}=mac_splitted($row->{mac}) || '';
  99. }
  100. foreach my $arp_table (@arp_array) {
  101. foreach my $ip (keys %$arp_table) {
  102. next if (!$arp_table->{$ip});
  103. my $mac=trim($arp_table->{$ip});
  104. $mac=mac_splitted($mac);
  105. next if (!$mac);
  106. next if ($mac=~/ff:ff:ff:ff:ff:ff/i);
  107. next if ($mac!~/(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2}):(\S{2})/);
  108. my $simple_mac=mac_simplify($mac);
  109. $ip=trim($ip);
  110. my $ip_aton=StrToIp($ip);
  111. $mac_history{$simple_mac}{changed}=0;
  112. $mac_history{$simple_mac}{ip}=$ip;
  113. $mac_history{$simple_mac}{auth_id}=0;
  114. next if (!$office_networks->match_string($ip));
  115. db_log_debug($dbh,"Analyze ip: $ip mac: $mac") if ($debug);
  116. my $auth_id = $users->match_string($ip);
  117. my $arp_record;
  118. $arp_record->{ip} = $ip;
  119. $arp_record->{mac} = $mac;
  120. $arp_record->{type} = 'arp';
  121. $arp_record->{ip_aton} = $ip_aton;
  122. $arp_record->{hotspot} = is_hotspot($dbh,$ip);
  123. my $cur_auth_id=resurrection_auth($dbh,$arp_record);
  124. if (!$cur_auth_id) {
  125. db_log_warning($dbh,"Unknown record ".Dumper($arp_record));
  126. } else {
  127. $mac_history{$simple_mac}{auth_id}=$cur_auth_id;
  128. $arp_record->{auth_id}=$cur_auth_id;
  129. $arp_record->{updated}=0;
  130. $oper_arp_list{$cur_auth_id}=$arp_record;
  131. if ($auth_id ne $cur_auth_id) { $mac_history{$simple_mac}{changed}=1; }
  132. }
  133. }
  134. }
  135. db_log_verbose($dbh,'Mac discovery started.');
  136. my %connections=();
  137. my @connections_list=get_records_sql($dbh,"SELECT * FROM connections ORDER BY auth_id");
  138. foreach my $connection (@connections_list) {
  139. next if (!$connection);
  140. $connections{$connection->{auth_id}}{port}=$connection->{port_id};
  141. $connections{$connection->{auth_id}}{id}=$connection->{id};
  142. }
  143. my $auth_filter=" AND last_found >='".$now_day."' ";
  144. my $auth_sql="SELECT id,mac FROM User_auth WHERE mac IS NOT NULL AND deleted=0 $auth_filter ORDER BY id ASC";
  145. my @auth_list=get_records_sql($dbh,$auth_sql);
  146. my %auth_table;
  147. foreach my $auth (@auth_list) {
  148. next if (!$auth);
  149. my $auth_mac=mac_simplify($auth->{mac});
  150. $auth_table{oper_table}{$auth_mac}=$auth->{id};
  151. }
  152. $auth_sql="SELECT id,mac FROM User_auth WHERE mac IS NOT NULL AND deleted=0 ORDER BY last_found DESC";
  153. my @auth_full_list=get_records_sql($dbh,$auth_sql);
  154. foreach my $auth (@auth_full_list) {
  155. next if (!$auth);
  156. my $auth_mac=mac_simplify($auth->{mac});
  157. next if (exists $auth_table{full_table}{$auth_mac});
  158. $auth_table{full_table}{$auth_mac}=$auth->{id};
  159. }
  160. my @unknown_list=get_records_sql($dbh,"SELECT id,mac,port_id,device_id FROM Unknown_mac WHERE mac !='' ORDER BY mac");
  161. my %unknown_table;
  162. foreach my $unknown (@unknown_list) {
  163. next if (!$unknown);
  164. my $unknown_mac=mac_simplify($unknown->{mac});
  165. $unknown_table{$unknown_mac}{unknown_id}=$unknown->{id};
  166. $unknown_table{$unknown_mac}{port_id}=$unknown->{port_id};
  167. $unknown_table{$unknown_mac}{device_id}=$unknown->{device_id};
  168. }
  169. my @device_list = get_records_sql($dbh,"SELECT * FROM devices WHERE deleted=0 AND discovery=1 AND device_type<=2 AND snmp_version>0" );
  170. my @fdb_array=();
  171. my $pm_fdb = Parallel::ForkManager->new($fork_count);
  172. # data structure retrieval and handling
  173. $pm_fdb -> run_on_finish (
  174. sub {
  175. my ($pid, $exit_code, $ident, $exit_signal, $core_dump, $data_structure_reference) = @_;
  176. if (defined($data_structure_reference)) { # children are not forced to send anything
  177. my $result = ${$data_structure_reference}; # child passed a string reference
  178. push(@fdb_array,$result);
  179. }
  180. }
  181. );
  182. my %dev_ifindex=();
  183. foreach my $device (@device_list) {
  184. my $dev_id = $device->{id};
  185. my @device_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=$dev_id");
  186. foreach my $port_data (@device_ports) {
  187. if (!$port_data->{snmp_index}) { $port_data->{snmp_index} = $port_data->{port}; }
  188. $dev_ifindex{$dev_id}->{$port_data->{port}}=$port_data->{snmp_index};
  189. }
  190. }
  191. $dbh->disconnect;
  192. FDB_LOOP:
  193. foreach my $device (@device_list) {
  194. setCommunity($device);
  195. if (!HostIsLive($device->{ip})) { log_info("Host id: $device->{id} name: $device->{device_name} ip: $device->{ip} is down! Skip."); next; }
  196. my $int_list = get_snmp_ifindex($device->{ip},$device->{snmp});
  197. if (!$int_list) { log_info("Host id: $device->{id} name: $device->{device_name} ip: $device->{ip} interfaces not found by snmp request! Skip."); next; }
  198. $pm_fdb->start() and next FDB_LOOP;
  199. my $result;
  200. my $tmp_dbh = init_db();
  201. if (apply_device_lock($tmp_dbh,$device->{id})) {
  202. my $fdb=get_fdb_table($device->{ip},$device->{snmp},$dev_ifindex{$device->{id}});
  203. unset_lock_discovery($tmp_dbh,$device->{id});
  204. $result->{id}=$device->{id};
  205. $result->{fdb} = $fdb;
  206. }
  207. $tmp_dbh->disconnect;
  208. $pm_fdb->finish(0, \$result);
  209. }
  210. $pm_fdb->wait_all_children;
  211. my %fdb_ref;
  212. foreach my $fdb_table (@fdb_array){
  213. next if (!$fdb_table);
  214. $fdb_ref{$fdb_table->{id}}{fdb}=$fdb_table->{fdb};
  215. }
  216. ################################ end fork's ##############################
  217. $dbh=init_db();
  218. foreach my $device (@device_list) {
  219. my %port_snmp_index=();
  220. my %port_index=();
  221. my %mac_port_count=();
  222. my %mac_address_table=();
  223. my %port_links=();
  224. my $dev_id = $device->{id};
  225. my $dev_name = $device->{device_name};
  226. my $fdb=$fdb_ref{$dev_id}{fdb};
  227. next if (!$fdb);
  228. my @device_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=$dev_id");
  229. foreach my $port_data (@device_ports) {
  230. my $fdb_port_index=$port_data->{port};
  231. my $port_id = $port_data->{id};
  232. if (!$port_data->{snmp_index}) { $port_data->{snmp_index} = $port_data->{port}; }
  233. $fdb_port_index=$port_data->{snmp_index};
  234. next if ($port_data->{skip});
  235. #snmp-индекс порта = номеру порта
  236. $port_snmp_index{$port_data->{snmp_index}}=$port_data->{port};
  237. # номер порта = id записи порта в таблице
  238. $port_index{$port_data->{port}}=$port_data->{id};
  239. # номер порта = id записи порта аплинка/даунлинка свича
  240. $port_links{$port_data->{port}}=$port_data->{target_port_id};
  241. $mac_port_count{$port_data->{port}}=0;
  242. }
  243. my $sw_mac;
  244. if ($device->{vendor_id} eq '9') {
  245. #get device mac
  246. my $sw_auth = get_record_sql($dbh,"SELECT mac FROM User_auth WHERE deleted=0 and ip='".$device->{ip}."'");
  247. $sw_mac = mac_simplify($sw_auth->{mac});
  248. $sw_mac =~s/.{2}$//s;
  249. }
  250. foreach my $mac (keys %$fdb) {
  251. #port from fdb table
  252. my $port = $fdb->{$mac};
  253. next if (!$port);
  254. #real port number
  255. if (exists $port_snmp_index{$port}) {
  256. #get real port number by snmp our snmp index
  257. $port=$port_snmp_index{$port};
  258. }
  259. if (!exists $port_index{$port}) { next; }
  260. #mikrotik patch - skip mikrotik device mac
  261. if ($sw_mac and $mac=~/^$sw_mac/i) { next; }
  262. $mac_port_count{$port}++;
  263. #мак = номер порта
  264. $mac_address_table{$mac}=$port;
  265. }
  266. # обновляем число маков на порту
  267. foreach my $port (keys %mac_port_count) {
  268. if (!$port) { next; }
  269. if (!exists $port_index{$port}) { next; }
  270. #skip uplink|downlink
  271. if ($port_links{$port}>0) { next; }
  272. my $dev_ports;
  273. $dev_ports->{last_mac_count}=$mac_port_count{$port};
  274. update_record($dbh,'device_ports',$dev_ports,"device_id=$dev_id and port=$port");
  275. }
  276. foreach my $mac (keys %mac_address_table) {
  277. my $port = $mac_address_table{$mac};
  278. if (!$port) { next; }
  279. if (!exists $port_index{$port}) { next; }
  280. #skip uplink|downlink
  281. if ($port_links{$port}>0) { next; }
  282. my $simple_mac=mac_simplify($mac);
  283. my $mac_splitted=mac_splitted($mac);
  284. $mac_history{$simple_mac}{port_id}=$port_index{$port};
  285. $mac_history{$simple_mac}{dev_id}=$dev_id;
  286. if (!$mac_history{$simple_mac}{changed}) { $mac_history{$simple_mac}{changed}=0; }
  287. my $port_id=$port_index{$port};
  288. if (exists $auth_table{full_table}{$simple_mac} or exists $auth_table{oper_table}{$simple_mac}) {
  289. my $auth_id;
  290. if (exists $auth_table{oper_table}{$simple_mac}) {
  291. $auth_id=$auth_table{oper_table}{$simple_mac};
  292. } else {
  293. $auth_id=$auth_table{full_table}{$simple_mac};
  294. db_log_debug($dbh,"Mac not found in oper ARP-table. Use old values auth_id: $auth_id [$simple_mac] at device $dev_name [$port]",$auth_id);
  295. }
  296. if (exists $connections{$auth_id}) {
  297. if ($port_id == $connections{$auth_id}{port}) {
  298. if (exists $auth_table{oper_table}{$simple_mac}) {
  299. my $auth_rec;
  300. $auth_rec->{last_found}=$now_str;
  301. $auth_rec->{arp_found}=$now_str;
  302. $oper_arp_list{$auth_id}{updated}=1;
  303. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  304. }
  305. next;
  306. }
  307. $connections{$auth_id}{port}=$port_id;
  308. $mac_history{$simple_mac}{changed}=1;
  309. $mac_history{$simple_mac}{auth_id}=$auth_id;
  310. db_log_info($dbh,"Found auth_id: $auth_id ip: $mac_history{$simple_mac}{ip} [$mac_splitted] at device $dev_name [$port]. Update connection",$auth_id);
  311. my $auth_rec;
  312. #for exists arp - update arp timestamp
  313. if (exists $auth_table{oper_table}{$simple_mac}) { $auth_rec->{arp_found}=$now_str; }
  314. $auth_rec->{last_found}=$now_str;
  315. $oper_arp_list{$auth_id}{updated}=1;
  316. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  317. my $conn_rec;
  318. $conn_rec->{port_id}=$port_id;
  319. $conn_rec->{device_id}=$dev_id;
  320. update_record($dbh,'connections',$conn_rec,"auth_id=$auth_id");
  321. } else {
  322. $mac_history{$simple_mac}{changed}=1;
  323. $mac_history{$simple_mac}{auth_id}=$auth_id;
  324. $connections{$auth_id}{port}=$port_id;
  325. db_log_info($dbh,"Found auth_id: $auth_id ip: $mac_history{$simple_mac}{ip} [$mac_splitted] at device $dev_name [$port]. Create connection.",$auth_id);
  326. my $auth_rec;
  327. #for exists arp - update arp timestamp
  328. if (exists $auth_table{oper_table}{$simple_mac}) { $auth_rec->{arp_found}=$now_str; }
  329. $auth_rec->{last_found}=$now_str;
  330. $oper_arp_list{$auth_id}{updated}=1;
  331. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  332. my $conn_rec;
  333. $conn_rec->{port_id}=$port_id;
  334. $conn_rec->{device_id}=$dev_id;
  335. $conn_rec->{auth_id}=$auth_id;
  336. insert_record($dbh,'connections',$conn_rec);
  337. }
  338. } else {
  339. if (exists $unknown_table{$simple_mac}{unknown_id}) {
  340. next if ($unknown_table{$simple_mac}{port_id} == $port_id and $unknown_table{$simple_mac}{device_id} == $dev_id);
  341. $mac_history{$simple_mac}{changed}=1;
  342. $mac_history{$simple_mac}{auth_id}=0;
  343. db_log_debug($dbh,"Unknown mac $mac_splitted moved to $dev_name [$port]") if ($debug);
  344. my $unknown_rec;
  345. $unknown_rec->{port_id}=$port_id;
  346. $unknown_rec->{device_id}=$dev_id;
  347. update_record($dbh,'Unknown_mac',$unknown_rec,"id=$unknown_table{$simple_mac}{unknown_id}");
  348. } else {
  349. $mac_history{$simple_mac}{changed}=1;
  350. $mac_history{$simple_mac}{auth_id}=0;
  351. db_log_debug($dbh,"Unknown mac $mac_splitted found at $dev_name [$port]") if ($debug);
  352. my $unknown_rec;
  353. $unknown_rec->{port_id}=$port_id;
  354. $unknown_rec->{device_id}=$dev_id;
  355. $unknown_rec->{mac}=$simple_mac;
  356. insert_record($dbh,'Unknown_mac',$unknown_rec);
  357. }
  358. }
  359. }
  360. }
  361. foreach my $auth_id (keys %oper_arp_list) {
  362. next if ($oper_arp_list{$auth_id}->{updated});
  363. my $auth_rec;
  364. $auth_rec->{last_found}=$now_str;
  365. update_record($dbh,'User_auth',$auth_rec,"id=".$auth_id);
  366. db_log_debug($dbh,"Update by arp at unknown connect place for: ".Dumper($oper_arp_list{$auth_id})) if ($debug);
  367. }
  368. foreach my $mac (keys %mac_history) {
  369. next if (!$mac);
  370. next if (!$mac_history{$mac}->{changed});
  371. my $h_dev_id='';
  372. my $h_port_id='';
  373. my $h_ip='';
  374. $h_dev_id=$mac_history{$mac}->{dev_id} if ($mac_history{$mac}->{dev_id});
  375. $h_port_id=$mac_history{$mac}->{port_id} if ($mac_history{$mac}->{port_id});
  376. $h_ip=$mac_history{$mac}->{ip} if ($mac_history{$mac}->{ip});
  377. my $h_auth_id=$mac_history{$mac}->{auth_id} if ($mac_history{$mac}->{auth_id});
  378. if (!$h_auth_id) { $h_auth_id=0; }
  379. next if (!$h_dev_id);
  380. my $history_rec;
  381. $history_rec->{device_id}=$h_dev_id;
  382. $history_rec->{port_id}=$h_port_id;
  383. $history_rec->{mac}=$mac;
  384. $history_rec->{ip}=$h_ip;
  385. $history_rec->{auth_id}=$h_auth_id;
  386. insert_record($dbh,'mac_history',$history_rec);
  387. }
  388. $dbh->disconnect;
  389. exit 0;