dhcp-log.pl 17 KB

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