dhcp-log.pl 17 KB

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