dhcp-log.pl 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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 Data::Dumper;
  14. use eyelib::config;
  15. use eyelib::main;
  16. use eyelib::database;
  17. use eyelib::net_utils;
  18. use strict;
  19. use warnings;
  20. use Getopt::Long;
  21. use Proc::Daemon;
  22. use POSIX;
  23. use Net::Netmask;
  24. use Text::Iconv;
  25. use File::Tail;
  26. my $mute_time=300;
  27. my $log_file='/var/log/dhcp.log';
  28. my $proc_name = $MY_NAME;
  29. $proc_name =~ s/\.[^.]+$//;
  30. my $pid_file = '/run/eye/'.$proc_name;
  31. my $pf = $pid_file.'.pid';
  32. my $daemon = Proc::Daemon->new(
  33. pid_file => $pf,
  34. work_dir => $HOME_DIR
  35. );
  36. # are you running? Returns 0 if not.
  37. my $pid = $daemon->Status($pf);
  38. my $daemonize = 1;
  39. GetOptions(
  40. 'daemon!' => \$daemonize,
  41. "help" => \&usage,
  42. "reload" => \&reload,
  43. "restart" => \&restart,
  44. "start" => \&run,
  45. "status" => \&status,
  46. "stop" => \&stop
  47. ) or &usage;
  48. exit(0);
  49. sub stop {
  50. if ($pid) {
  51. print "Stopping pid $pid...";
  52. if ($daemon->Kill_Daemon($pf)) {
  53. print "Successfully stopped.\n";
  54. } else {
  55. print "Could not find $pid. Was it running?\n";
  56. }
  57. } else {
  58. print "Not running, nothing to stop.\n";
  59. }
  60. }
  61. sub status {
  62. if ($pid) {
  63. print "Running with pid $pid.\n";
  64. } else {
  65. print "Not running.\n";
  66. }
  67. }
  68. sub run {
  69. if (!$pid) {
  70. print "Starting...";
  71. if ($daemonize) {
  72. # when Init happens, everything under it runs in the child process.
  73. # this is important when dealing with file handles, due to the fact
  74. # Proc::Daemon shuts down all open file handles when Init happens.
  75. # Keep this in mind when laying out your program, particularly if
  76. # you use filehandles.
  77. $daemon->Init;
  78. }
  79. setpriority(0,0,19);
  80. my $converter = Text::Iconv->new("cp866", "utf8");
  81. while (1) {
  82. eval {
  83. my %leases;
  84. # Create new database handle. If we can't connect, die()
  85. my $hdb = init_db();
  86. #parse log
  87. my $dhcp_log=File::Tail->new(name=>$log_file,maxinterval=>5,interval=>1,ignore_nonexistant=>1) || die "$log_file not found!";
  88. #truncate current log file
  89. truncate $log_file, 0;
  90. while (my $logline=$dhcp_log->read) {
  91. next if (!$logline);
  92. chomp($logline);
  93. log_verbose("GET CLIENT REQUEST: $logline");
  94. my ($type,$mac,$ip,$hostname,$timestamp,$tags,$sup_hostname,$old_hostname,$circuit_id,$remote_id,$client_id,$decoded_circuit_id,$decoded_remote_id) = split (/\;/, $logline);
  95. next if (!$type);
  96. next if ($type!~/(old|add|del)/i);
  97. if (exists $leases{$ip} and $leases{$ip}{'type'} eq $type and time()-$leases{$ip}{'last_time'} <= $mute_time) { next; }
  98. if (time()-$last_refresh_config>=60) { init_option($hdb); }
  99. my $client_hostname='';
  100. if ($hostname and $hostname ne "undef") { $client_hostname=$hostname; } else {
  101. if ($sup_hostname) { $client_hostname=$sup_hostname; } else {
  102. if ($old_hostname) { $client_hostname=$old_hostname; }
  103. }
  104. }
  105. my $auth_network = $office_networks->match_string($ip);
  106. if (!$auth_network) {
  107. log_error("Unknown network in dhcp request! IP: $ip");
  108. next;
  109. }
  110. if (!$timestamp) { $timestamp=time(); }
  111. my $ip_aton=StrToIp($ip);
  112. $mac=mac_splitted(isc_mac_simplify($mac));
  113. my $dhcp_event_time = GetNowTime($timestamp);
  114. my $dhcp_record;
  115. $dhcp_record->{'mac'}=$mac;
  116. $dhcp_record->{'ip'}=$ip;
  117. $dhcp_record->{'ip_aton'}=$ip_aton;
  118. $dhcp_record->{'hostname'}=$client_hostname;
  119. $dhcp_record->{'tags'}=$tags;
  120. $dhcp_record->{'network'}=$auth_network;
  121. $dhcp_record->{'type'}=$type;
  122. $dhcp_record->{'hostname_utf8'}=$converter->convert($client_hostname);
  123. $dhcp_record->{'timestamp'} = $timestamp;
  124. $dhcp_record->{'last_time'} = time();
  125. $dhcp_record->{'circuit-id'} = $circuit_id;
  126. $dhcp_record->{'client-id'} = $client_id;
  127. $dhcp_record->{'remote-id'} = $remote_id;
  128. $dhcp_record->{'hotspot'}=is_hotspot($dbh,$dhcp_record->{ip});
  129. #save record for mute
  130. $leases{$ip}=$dhcp_record;
  131. my $auth_record = get_record_sql($hdb,'SELECT * FROM User_auth WHERE ip="'.$dhcp_record->{ip}.'" and mac="'.$mac.'" and deleted=0 ORDER BY last_found DESC');
  132. if (!$auth_record and $type eq 'old' ) { $type='add'; }
  133. if ($type eq 'add') {
  134. my $res_id = resurrection_auth($hdb,$dhcp_record);
  135. if (!$res_id) {
  136. db_log_error($hdb,"Error creating an ip address record for ip=".$dhcp_record->{ip}." and mac=".$mac."!");
  137. next;
  138. }
  139. $auth_record = get_record_sql($hdb,'SELECT * FROM User_auth WHERE id='.$res_id);
  140. db_log_info($hdb,"Check for new auth. Found id: $res_id",$res_id);
  141. } else {
  142. $auth_record = get_record_sql($hdb,'SELECT * FROM User_auth WHERE ip="'.$dhcp_record->{ip}.'" and mac="'.$mac.'" and deleted=0 ORDER BY last_found DESC');
  143. }
  144. #create new record for refresh dhcp packet
  145. if (!$auth_record) {
  146. #don't create record by del request!
  147. #because when the host address is changed, the new address will be overwritten by the old one being released
  148. if ($type=~/old/i) {
  149. db_log_warning($hdb,"Record for dhcp request type: ".$type." ip=".$dhcp_record->{ip}." and mac=".$mac." does not exists!");
  150. my $res_id = resurrection_auth($hdb,$dhcp_record);
  151. if (!$res_id) {
  152. db_log_error($hdb,"Error creating an ip address record for ip=".$dhcp_record->{ip}." and mac=".$mac."!");
  153. next;
  154. }
  155. $auth_record = get_record_sql($hdb,'SELECT * FROM User_auth WHERE id='.$res_id);
  156. db_log_info($hdb,"Check for new auth. Found id: $res_id",$res_id);
  157. } else { next; }
  158. }
  159. my $auth_id = $auth_record->{id};
  160. my $auth_ou_id = $auth_record->{ou_id};
  161. my $switch;
  162. my $switch_port;
  163. my $t_remote_id;
  164. my $t_circuit_id = $circuit_id;
  165. #detect connection
  166. if ($type =~/(add|old)/) {
  167. #detect switch by decoded remote-id
  168. if ($decoded_remote_id) {
  169. $t_remote_id = $decoded_remote_id;
  170. #fill '0' to remote-id for full mac lenght
  171. if (length($t_remote_id)<12) {
  172. for (my $i = length($decoded_remote_id); $i < 12; $i++) { $t_remote_id = $t_remote_id."0"; }
  173. }
  174. $t_remote_id=mac_splitted(isc_mac_simplify($t_remote_id));
  175. my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac FROM `devices` AS D,`User_auth` AS A WHERE D.user_id=A.User_id AND D.ip=A.ip AND A.deleted=0 AND A.mac='".$t_remote_id."'";
  176. log_debug($devSQL);
  177. $switch = get_record_sql($hdb,$devSQL);
  178. if ($switch) {
  179. $remote_id = $t_remote_id;
  180. $circuit_id = $decoded_circuit_id;
  181. $dhcp_record->{'circuit-id'} = $circuit_id;
  182. $dhcp_record->{'remote-id'} = $remote_id;
  183. }
  184. }
  185. #detect switch by original remote-id
  186. if (!$switch and $remote_id) {
  187. $t_remote_id = $remote_id;
  188. #fill '0' to remote-id for full mac lenght
  189. if (length($t_remote_id)<12) {
  190. for (my $i = length($decoded_remote_id); $i < 12; $i++) { $t_remote_id = $t_remote_id."0"; }
  191. }
  192. $t_remote_id=mac_splitted(isc_mac_simplify($t_remote_id));
  193. my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac FROM `devices` AS D,`User_auth` AS A WHERE D.user_id=A.User_id AND D.ip=A.ip AND A.deleted=0 AND A.mac='".$t_remote_id."'";
  194. log_debug($devSQL);
  195. $switch = get_record_sql($hdb,$devSQL);
  196. if ($switch) {
  197. $remote_id = $t_remote_id;
  198. $dhcp_record->{'circuit-id'} = $circuit_id;
  199. $dhcp_record->{'remote-id'} = $remote_id;
  200. }
  201. }
  202. #maybe remote-id is string name device?
  203. if (!$switch and $remote_id) {
  204. my @id_words = split(/ /,$remote_id);
  205. if ($id_words[0]) {
  206. my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac FROM `devices` AS D,`User_auth` AS A WHERE D.user_id=A.User_id AND D.ip=A.ip AND A.deleted=0 AND D.device_name like '".$id_words[0]."%'";
  207. log_debug($devSQL);
  208. $switch = get_record_sql($hdb,$devSQL);
  209. }
  210. }
  211. #maybe mikrotik?!
  212. if (!$switch and $circuit_id) {
  213. my @id_words = split(/ /,$circuit_id);
  214. if ($id_words[0]) {
  215. my $devSQL = "SELECT D.id, D.device_name, D.ip, A.mac FROM `devices` AS D,`User_auth` AS A WHERE D.user_id=A.User_id AND D.ip=A.ip AND A.deleted=0 AND D.device_name like '".$id_words[0]."%'";
  216. log_debug($devSQL);
  217. $switch = get_record_sql($hdb,$devSQL);
  218. #fucking mikrotik - swap variables
  219. if ($switch) {
  220. $circuit_id = $remote_id;
  221. $remote_id = $t_circuit_id;
  222. $dhcp_record->{'circuit-id'} = $circuit_id;
  223. $dhcp_record->{'remote-id'} = $remote_id;
  224. }
  225. }
  226. }
  227. if ($switch) {
  228. $t_circuit_id=~s/[\+\-\s]+/ /g;
  229. #detect port by name
  230. my @device_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=".$switch->{id});
  231. my %device_ports_h;
  232. foreach my $port_data (@device_ports) {
  233. if (!$port_data->{snmp_index}) { $port_data->{snmp_index} = $port_data->{port}; }
  234. $device_ports_h{$port_data->{port}} = $port_data;
  235. if ($t_circuit_id=~/\s*$port_data->{'ifName'}$/i or $t_circuit_id=~/^$port_data->{'ifName'}\s+/i ) { $switch_port = $port_data; last; }
  236. }
  237. #detect hex - get last 2 byte
  238. if (!$switch_port) {
  239. my $hex_port = substr($decoded_circuit_id, -2);
  240. if ($hex_port) {
  241. my $t_port = hex($hex_port);
  242. #try find port by index
  243. if (exists $device_ports_h{$t_port}) { $switch_port =$device_ports_h{$t_port}; }
  244. }
  245. }
  246. if ($switch_port) {
  247. db_log_verbose($hdb,"Dhcp request type: ".$type." ip=".$ip." and mac=".$mac." from ".$switch->{'device_name'}." and port ".$switch_port->{'ifName'});
  248. #check connection
  249. my $connection=get_records_sql($dbh,"SELECT * FROM connections WHERE auth_id=".$auth_id);
  250. my $new_connection;
  251. if (!$connection) {
  252. $new_connection->{port_id} = $switch_port->{id};
  253. $new_connection->{device_id} = $switch->{id};
  254. $new_connection->{auth_id} = $auth_id;
  255. insert_record($hdb,'connections',$new_connection);
  256. }
  257. # else
  258. # {
  259. # $new_connection->{port_id} = $switch_port->{id};
  260. # $new_connection->{device_id} = $switch->{id};
  261. # update_record($hdb,'connections',$new_connection,"id=".$connection->{id});
  262. # }
  263. } else {
  264. db_log_verbose($hdb,"Dhcp request type: ".$type." ip=".$ip." and mac=".$mac." from ".$switch->{'device_name'}." from unknown port");
  265. }
  266. }
  267. }
  268. log_debug(uc($type).">>");
  269. log_debug("MAC: ".$dhcp_record->{'mac'});
  270. log_debug("IP: ".$dhcp_record->{'ip'});
  271. log_debug("TAGS: ".$dhcp_record->{'tags'});
  272. log_debug("CIRCUIT-ID: ".$dhcp_record->{'circuit-id'});
  273. log_debug("REMOTE-ID: ".$dhcp_record->{'remote-id'});
  274. log_debug("HOSTNAME: ".$dhcp_record->{'hostname'});
  275. log_debug("TYPE: ".$dhcp_record->{'type'});
  276. log_debug("TIME: ".$dhcp_event_time);
  277. log_debug("UTF8 NAME: ".$dhcp_record->{'hostname_utf8'});
  278. log_debug("SWITCH: ".$switch->{'device_name'}) if ($switch);
  279. log_debug("SWITCH PORT:".$switch_port->{'ifName'}) if ($switch_port);
  280. log_debug("END GET");
  281. update_dns_record_by_dhcp($hdb,$dhcp_record,$auth_record);
  282. if ($type=~/add/i and $dhcp_record->{hostname_utf8} and $dhcp_record->{hostname_utf8} !~/UNDEFINED/i) {
  283. my $auth_rec;
  284. $auth_rec->{dhcp_hostname} = $dhcp_record->{hostname_utf8};
  285. $auth_rec->{dhcp_time}=$dhcp_event_time;
  286. $auth_rec->{arp_found}=$dhcp_event_time;
  287. $auth_rec->{created_by}='dhcp';
  288. db_log_verbose($hdb,"Add lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  289. update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
  290. }
  291. if ($type=~/old/i) {
  292. my $auth_rec;
  293. $auth_rec->{dhcp_action}=$type;
  294. $auth_rec->{dhcp_time}=$dhcp_event_time;
  295. $auth_rec->{created_by}='dhcp';
  296. $auth_rec->{arp_found}=$dhcp_event_time;
  297. db_log_verbose($hdb,"Update lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  298. update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
  299. }
  300. if ($type=~/del/i and $auth_id) {
  301. if ($auth_record->{dhcp_time} =~ /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/) {
  302. my $d_time = mktime($6,$5,$4,$3,$2-1,$1-1900);
  303. if (time()-$d_time>60 and ($auth_ou_id == $default_user_ou_id or $auth_ou_id==$default_hotspot_ou_id)) {
  304. db_log_info($hdb,"Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  305. my $auth_rec;
  306. $auth_rec->{deleted}="1";
  307. $auth_rec->{dhcp_action}=$type;
  308. $auth_rec->{dhcp_time}=$dhcp_event_time;
  309. update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
  310. my $u_count=get_count_records($hdb,'User_auth','deleted=0 and user_id='.$auth_record->{'user_id'});
  311. if (!$u_count) {
  312. delete_record($hdb,"User_list","id=".$auth_record->{'user_id'});
  313. db_log_info($hdb,"Remove dynamic user id: $auth_record->{'user_id'} by dhcp request",$auth_id);
  314. }
  315. }
  316. }
  317. }
  318. if ($dhcp_record->{hotspot} and $ignore_hotspot_dhcp_log) { next; }
  319. if ($ignore_update_dhcp_event and $type=~/old/i) { next; }
  320. my $dhcp_log;
  321. if (!$auth_id) { $auth_id=0; }
  322. $dhcp_log->{'auth_id'} = $auth_id;
  323. $dhcp_log->{'ip'} = $dhcp_record->{'ip'};
  324. $dhcp_log->{'ip_int'} = $dhcp_record->{'ip_aton'};
  325. $dhcp_log->{'mac'} = $dhcp_record->{'mac'};
  326. $dhcp_log->{'action'} = $type;
  327. $dhcp_log->{'dhcp_hostname'} = $dhcp_record->{'hostname_utf8'};
  328. $dhcp_log->{'timestamp'} = $dhcp_event_time;
  329. $dhcp_log->{'circuit-id'} = $circuit_id;
  330. $dhcp_log->{'client-id'} = $client_id;
  331. $dhcp_log->{'remote-id'} = $remote_id;
  332. insert_record($hdb,'dhcp_log',$dhcp_log);
  333. }
  334. };
  335. if ($@) { log_error("Exception found: $@"); sleep(60); }
  336. }
  337. } else {
  338. print "Already Running with pid $pid\n";
  339. }
  340. }
  341. sub usage {
  342. print "usage: $MY_NAME (start|stop|status|restart)\n";
  343. exit(0);
  344. }
  345. sub reload {
  346. print "reload process not implemented.\n";
  347. }
  348. sub restart {
  349. stop;
  350. run;
  351. }