dhcp-log.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. #mute doubles
  98. if (exists $leases{$ip} and $leases{$ip}{'type'} eq $type and time()-$leases{$ip}{'last_time'} <= $mute_time) { next; }
  99. #update config variables every 1 minute
  100. if (time()-$last_refresh_config>=60) { init_option($hdb); }
  101. my $client_hostname='';
  102. if ($hostname and $hostname ne "undef") { $client_hostname=$hostname; } else {
  103. if ($sup_hostname) { $client_hostname=$sup_hostname; } else {
  104. if ($old_hostname) { $client_hostname=$old_hostname; }
  105. }
  106. }
  107. my $auth_network = $office_networks->match_string($ip);
  108. if (!$auth_network) {
  109. log_error("Unknown network in dhcp request! IP: $ip");
  110. next;
  111. }
  112. if (!$timestamp) { $timestamp=time(); }
  113. my $ip_aton=StrToIp($ip);
  114. $mac=mac_splitted(isc_mac_simplify($mac));
  115. my $dhcp_event_time = GetNowTime($timestamp);
  116. my $dhcp_record;
  117. $dhcp_record->{'mac'}=$mac;
  118. $dhcp_record->{'ip'}=$ip;
  119. $dhcp_record->{'ip_aton'}=$ip_aton;
  120. $dhcp_record->{'hostname'}=$client_hostname;
  121. $dhcp_record->{'tags'}=$tags;
  122. $dhcp_record->{'network'}=$auth_network;
  123. $dhcp_record->{'type'}=$type;
  124. $dhcp_record->{'hostname_utf8'}=$converter->convert($client_hostname);
  125. $dhcp_record->{'timestamp'} = $timestamp;
  126. $dhcp_record->{'last_time'} = time();
  127. $dhcp_record->{'circuit-id'} = $circuit_id;
  128. $dhcp_record->{'client-id'} = $client_id;
  129. $dhcp_record->{'remote-id'} = $remote_id;
  130. $dhcp_record->{'hotspot'}=is_hotspot($dbh,$dhcp_record->{ip});
  131. #save record for mute
  132. $leases{$ip}=$dhcp_record;
  133. #search actual record
  134. 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');
  135. #if record not found and type del => next event
  136. if (!$type) { next; }
  137. if (!$auth_record and $type eq 'del') {
  138. next;
  139. }
  140. #if record not found - create it
  141. if (!$auth_record and $type=~/(add|old)/i) {
  142. db_log_warning($hdb,"Record for dhcp request type: ".$type." ip=".$dhcp_record->{ip}." and mac=".$mac." does not exists!");
  143. my $res_id = resurrection_auth($hdb,$dhcp_record);
  144. if (!$res_id) {
  145. db_log_error($hdb,"Error creating an ip address record for ip=".$dhcp_record->{ip}." and mac=".$mac."!");
  146. next;
  147. }
  148. $auth_record = get_record_sql($hdb,'SELECT * FROM User_auth WHERE id='.$res_id);
  149. db_log_info($hdb,"Check for new auth. Found id: $res_id",$res_id);
  150. }
  151. my $auth_id = $auth_record->{id};
  152. my $auth_ou_id = $auth_record->{ou_id};
  153. my $switch;
  154. my $switch_port;
  155. my $t_remote_id;
  156. my $t_circuit_id = $circuit_id;
  157. #detect connection
  158. if ($type =~/(add|old)/) {
  159. #detect switch by decoded remote-id
  160. if ($decoded_remote_id) {
  161. $t_remote_id = $decoded_remote_id;
  162. #fill '0' to remote-id for full mac lenght
  163. if (length($t_remote_id)<12) {
  164. for (my $i = length($decoded_remote_id); $i < 12; $i++) { $t_remote_id = $t_remote_id."0"; }
  165. }
  166. $t_remote_id=mac_splitted(isc_mac_simplify($t_remote_id));
  167. 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."'";
  168. log_debug($devSQL);
  169. $switch = get_record_sql($hdb,$devSQL);
  170. if ($switch) {
  171. $remote_id = $t_remote_id;
  172. $circuit_id = $decoded_circuit_id;
  173. $dhcp_record->{'circuit-id'} = $circuit_id;
  174. $dhcp_record->{'remote-id'} = $remote_id;
  175. }
  176. }
  177. #detect switch by original remote-id
  178. if (!$switch and $remote_id) {
  179. $t_remote_id = $remote_id;
  180. #fill '0' to remote-id for full mac lenght
  181. if (length($t_remote_id)<12) {
  182. for (my $i = length($decoded_remote_id); $i < 12; $i++) { $t_remote_id = $t_remote_id."0"; }
  183. }
  184. $t_remote_id=mac_splitted(isc_mac_simplify($t_remote_id));
  185. 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."'";
  186. log_debug($devSQL);
  187. $switch = get_record_sql($hdb,$devSQL);
  188. if ($switch) {
  189. $remote_id = $t_remote_id;
  190. $dhcp_record->{'circuit-id'} = $circuit_id;
  191. $dhcp_record->{'remote-id'} = $remote_id;
  192. }
  193. }
  194. #maybe remote-id is string name device?
  195. if (!$switch and $remote_id) {
  196. my @id_words = split(/ /,$remote_id);
  197. if ($id_words[0]) {
  198. 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]."%'";
  199. log_debug($devSQL);
  200. $switch = get_record_sql($hdb,$devSQL);
  201. }
  202. }
  203. #maybe mikrotik?!
  204. if (!$switch and $circuit_id) {
  205. my @id_words = split(/ /,$circuit_id);
  206. if ($id_words[0]) {
  207. 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]."%'";
  208. log_debug($devSQL);
  209. $switch = get_record_sql($hdb,$devSQL);
  210. #fucking mikrotik - swap variables
  211. if ($switch) {
  212. $circuit_id = $remote_id;
  213. $remote_id = $t_circuit_id;
  214. $dhcp_record->{'circuit-id'} = $circuit_id;
  215. $dhcp_record->{'remote-id'} = $remote_id;
  216. }
  217. }
  218. }
  219. if ($switch) {
  220. $t_circuit_id=~s/[\+\-\s]+/ /g;
  221. #detect port by name
  222. my @device_ports = get_records_sql($dbh,"SELECT * FROM device_ports WHERE device_id=".$switch->{id});
  223. my %device_ports_h;
  224. foreach my $port_data (@device_ports) {
  225. if (!$port_data->{snmp_index}) { $port_data->{snmp_index} = $port_data->{port}; }
  226. $device_ports_h{$port_data->{port}} = $port_data;
  227. if ($t_circuit_id=~/\s*$port_data->{'ifName'}$/i or $t_circuit_id=~/^$port_data->{'ifName'}\s+/i ) { $switch_port = $port_data; last; }
  228. }
  229. #detect hex - get last 2 byte
  230. if (!$switch_port) {
  231. my $hex_port = substr($decoded_circuit_id, -2);
  232. if ($hex_port) {
  233. my $t_port = hex($hex_port);
  234. #try find port by index
  235. if (exists $device_ports_h{$t_port}) { $switch_port =$device_ports_h{$t_port}; }
  236. }
  237. }
  238. if ($switch_port) {
  239. db_log_verbose($hdb,"Dhcp request type: ".$type." ip=".$ip." and mac=".$mac." from ".$switch->{'device_name'}." and port ".$switch_port->{'ifName'});
  240. #check connection
  241. my $connection=get_records_sql($dbh,"SELECT * FROM connections WHERE auth_id=".$auth_id);
  242. my $new_connection;
  243. if (!$connection) {
  244. $new_connection->{port_id} = $switch_port->{id};
  245. $new_connection->{device_id} = $switch->{id};
  246. $new_connection->{auth_id} = $auth_id;
  247. insert_record($hdb,'connections',$new_connection);
  248. }
  249. # else
  250. # {
  251. # $new_connection->{port_id} = $switch_port->{id};
  252. # $new_connection->{device_id} = $switch->{id};
  253. # update_record($hdb,'connections',$new_connection,"id=".$connection->{id});
  254. # }
  255. } else {
  256. db_log_verbose($hdb,"Dhcp request type: ".$type." ip=".$ip." and mac=".$mac." from ".$switch->{'device_name'}." from unknown port");
  257. }
  258. }
  259. }
  260. log_debug(uc($type).">>");
  261. log_debug("MAC: ".$dhcp_record->{'mac'});
  262. log_debug("IP: ".$dhcp_record->{'ip'});
  263. log_debug("TAGS: ".$dhcp_record->{'tags'});
  264. log_debug("CIRCUIT-ID: ".$dhcp_record->{'circuit-id'});
  265. log_debug("REMOTE-ID: ".$dhcp_record->{'remote-id'});
  266. log_debug("HOSTNAME: ".$dhcp_record->{'hostname'});
  267. log_debug("TYPE: ".$dhcp_record->{'type'});
  268. log_debug("TIME: ".$dhcp_event_time);
  269. log_debug("UTF8 NAME: ".$dhcp_record->{'hostname_utf8'});
  270. log_debug("SWITCH: ".$switch->{'device_name'}) if ($switch);
  271. log_debug("SWITCH PORT:".$switch_port->{'ifName'}) if ($switch_port);
  272. log_debug("END GET");
  273. update_dns_record_by_dhcp($hdb,$dhcp_record,$auth_record);
  274. if ($type=~/add/i and $dhcp_record->{hostname_utf8} and $dhcp_record->{hostname_utf8} !~/UNDEFINED/i) {
  275. my $auth_rec;
  276. $auth_rec->{dhcp_hostname} = $dhcp_record->{hostname_utf8};
  277. $auth_rec->{dhcp_time}=$dhcp_event_time;
  278. $auth_rec->{arp_found}=$dhcp_event_time;
  279. $auth_rec->{created_by}='dhcp';
  280. db_log_verbose($hdb,"Add lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  281. update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
  282. }
  283. if ($type=~/old/i) {
  284. my $auth_rec;
  285. $auth_rec->{dhcp_action}=$type;
  286. $auth_rec->{dhcp_time}=$dhcp_event_time;
  287. $auth_rec->{created_by}='dhcp';
  288. $auth_rec->{arp_found}=$dhcp_event_time;
  289. db_log_verbose($hdb,"Update lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  290. update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
  291. }
  292. if ($type=~/del/i and $auth_id) {
  293. if ($auth_record->{dhcp_time} =~ /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/) {
  294. my $d_time = mktime($6,$5,$4,$3,$2-1,$1-1900);
  295. if (time()-$d_time>60 and ($auth_ou_id == $default_user_ou_id or $auth_ou_id==$default_hotspot_ou_id)) {
  296. db_log_info($hdb,"Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  297. my $auth_rec;
  298. $auth_rec->{dhcp_action}=$type;
  299. $auth_rec->{dhcp_time}=$dhcp_event_time;
  300. update_record($hdb,'User_auth',$auth_rec,"id=$auth_id");
  301. delete_user_auth($hdb,$auth_id);
  302. my $u_count=get_count_records($hdb,'User_auth','deleted=0 and user_id='.$auth_record->{'user_id'});
  303. if (!$u_count) { delete_user($hdb,$auth_record->{'user_id'}); }
  304. }
  305. }
  306. }
  307. if ($dhcp_record->{hotspot} and $ignore_hotspot_dhcp_log) { next; }
  308. if ($ignore_update_dhcp_event and $type=~/old/i) { next; }
  309. my $dhcp_log;
  310. if (!$auth_id) { $auth_id=0; }
  311. $dhcp_log->{'auth_id'} = $auth_id;
  312. $dhcp_log->{'ip'} = $dhcp_record->{'ip'};
  313. $dhcp_log->{'ip_int'} = $dhcp_record->{'ip_aton'};
  314. $dhcp_log->{'mac'} = $dhcp_record->{'mac'};
  315. $dhcp_log->{'action'} = $type;
  316. $dhcp_log->{'dhcp_hostname'} = $dhcp_record->{'hostname_utf8'};
  317. $dhcp_log->{'timestamp'} = $dhcp_event_time;
  318. $dhcp_log->{'circuit-id'} = $circuit_id;
  319. $dhcp_log->{'client-id'} = $client_id;
  320. $dhcp_log->{'remote-id'} = $remote_id;
  321. insert_record($hdb,'dhcp_log',$dhcp_log);
  322. }
  323. };
  324. if ($@) { log_error("Exception found: $@"); sleep(60); }
  325. }
  326. } else {
  327. print "Already Running with pid $pid\n";
  328. }
  329. }
  330. sub usage {
  331. print "usage: $MY_NAME (start|stop|status|restart)\n";
  332. exit(0);
  333. }
  334. sub reload {
  335. print "reload process not implemented.\n";
  336. }
  337. sub restart {
  338. stop;
  339. run;
  340. }