dhcp-log.pl 17 KB

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