fetch_new_arp.pl 16 KB

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