common.pm 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. package eyelib::common;
  2. #
  3. # Copyright (C) Roman Dmitriev, rnd@rajven.ru
  4. #
  5. use utf8;
  6. use open ":encoding(utf8)";
  7. use strict;
  8. use English;
  9. use FindBin '$Bin';
  10. use lib "/opt/Eye/scripts";
  11. use base 'Exporter';
  12. use vars qw(@EXPORT @ISA);
  13. use eyelib::config;
  14. use eyelib::main;
  15. use Net::Patricia;
  16. use eyelib::net_utils;
  17. use Data::Dumper;
  18. use eyelib::database;
  19. use DateTime;
  20. use POSIX qw(mktime ctime strftime);
  21. use File::Temp qw(tempfile);
  22. use DBI;
  23. our @ISA = qw(Exporter);
  24. our @EXPORT = qw(
  25. apply_device_lock
  26. create_dns_cname
  27. create_dns_hostname
  28. create_dns_ptr
  29. delete_device
  30. delete_dns_cname
  31. delete_dns_hostname
  32. delete_dns_ptr
  33. delete_user
  34. delete_user_auth
  35. find_mac_in_subnet
  36. get_default_ou
  37. get_device_by_ip
  38. get_dns_name
  39. get_dynamic_ou
  40. get_first_line
  41. get_ip_subnet
  42. get_new_user_id
  43. get_notify_subnet
  44. GetNowTime
  45. get_office_subnet
  46. get_subnets_ref
  47. GetTimeStrByUnixTime
  48. GetUnixTimeByStr
  49. is_ad_computer
  50. is_default_ou
  51. is_dynamic_ou
  52. is_hotspot
  53. new_auth
  54. new_user
  55. process_dhcp_request
  56. recalc_quotes
  57. record_to_txt
  58. resurrection_auth
  59. set_changed
  60. set_lock_discovery
  61. unbind_ports
  62. unblock_user
  63. unset_lock_discovery
  64. update_dns_record
  65. update_dns_record_by_dhcp
  66. );
  67. BEGIN
  68. {
  69. #---------------------------------------------------------------------------------------------------------------
  70. sub get_first_line {
  71. my $msg = shift;
  72. if (!$msg) { return; }
  73. if ($msg=~ /(.*)(\n|\<br\>)/) {
  74. $msg = $1 if ($1);
  75. chomp($msg);
  76. }
  77. return $msg;
  78. }
  79. #---------------------------------------------------------------------------------------------------------------
  80. sub unbind_ports {
  81. my $db = shift;
  82. my $device_id = shift;
  83. return if (!$db);
  84. return if (!$device_id);
  85. my @target = get_records_sql($db, "SELECT U.target_port_id,U.id FROM device_ports U WHERE U.device_id=".$device_id);
  86. foreach my $row (@target) {
  87. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE target_port_id=".$row->{id});
  88. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE id=".$row->{id});
  89. }
  90. }
  91. #---------------------------------------------------------------------------------------------------------------
  92. sub get_dns_name {
  93. my $db = shift;
  94. my $id = shift;
  95. my $auth_record = get_record_sql($db,"SELECT dns_name FROM user_auth WHERE deleted=0 AND id=".$id);
  96. if ($auth_record and $auth_record->{'dns_name'}) { return $auth_record->{'dns_name'}; }
  97. return;
  98. }
  99. #---------------------------------------------------------------------------------------------------------------
  100. sub record_to_txt {
  101. my $db = shift;
  102. my $table = shift;
  103. my $id = shift;
  104. my $record = get_record_sql($db,'SELECT * FROM '.$table.' WHERE id='.$id);
  105. return hash_to_text($record);
  106. }
  107. #---------------------------------------------------------------------------------------------------------------
  108. sub delete_user_auth {
  109. my $db = shift;
  110. my $id = shift;
  111. my $record = get_record_sql($db,'SELECT * FROM user_auth WHERE id='.$id);
  112. my $auth_ident = $record->{ip};
  113. $auth_ident = $auth_ident . '['.$record->{dns_name} .']' if ($record->{dns_name});
  114. $auth_ident = $auth_ident . ' :: '.$record->{description} if ($record->{dns_name});
  115. my $msg = "";
  116. my $txt_record = hash_to_text($record);
  117. #remove aliases
  118. my @t_user_auth_alias = get_records_sql($db,'SELECT * FROM user_auth_alias WHERE auth_id='.$id);
  119. if (@t_user_auth_alias and scalar @t_user_auth_alias) {
  120. foreach my $row ( @t_user_auth_alias) {
  121. my $alias_txt = record_to_txt($db,'user_auth_alias','id='.$row->{'id'});
  122. if (delete_record($db,'user_auth_alias','id='.$row->{'id'})) {
  123. $msg = "Deleting an alias: ". $alias_txt . "\n::Success!\n" . $msg;
  124. } else {
  125. $msg = "Deleting an alias: ". $alias_txt . "\n::Fail!\n" . $msg;
  126. }
  127. }
  128. }
  129. #remove connections
  130. do_sql($db,'DELETE FROM connections WHERE auth_id='.$id);
  131. #remove user auth record
  132. my $changes = delete_record($db, "user_auth", "id=" . $id);
  133. if ($changes) {
  134. $msg = "Deleting ip-record: ". $txt_record . "\n::Success!\n" . $msg;
  135. } else {
  136. $msg = "Deleting ip-record: ". $txt_record . "\n::Fail!\n" . $msg;
  137. }
  138. $msg = "Deleting user ip record $auth_ident\n\n".$msg;
  139. db_log_warning($db, $msg, $id);
  140. my $send_alert = isNotifyDelete(get_notify_subnet($db,$record->{ip}));
  141. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  142. return $changes;
  143. }
  144. #---------------------------------------------------------------------------------------------------------------
  145. sub unblock_user {
  146. my $db = shift;
  147. my $user_id = shift;
  148. my $user_record = get_record_sql($db,'SELECT * FROM user_list WHERE id='.$user_id);
  149. my $user_ident = 'id:'. $user_record->{'id'} . ' '. $user_record->{'login'};
  150. $user_ident = $user_ident . '[' . $user_record->{'fio'} . ']' if ($user_record->{'fio'});
  151. my $msg = "Amnistuyemo blocked by traffic user $user_ident \nInternet access for the user's IP address has been restored:\n";
  152. my @user_auth = get_records_sql($db,'SELECT * FROM user_auth WHERE deleted=0 AND user_id='.$user_id);
  153. my $send_alert = 0;
  154. if (@user_auth and scalar @user_auth) {
  155. foreach my $record (@user_auth) {
  156. $send_alert = ($send_alert or isNotifyUpdate(get_notify_subnet($db,$record->{ip})));
  157. my $auth_ident = $record->{ip};
  158. $auth_ident = $auth_ident . '['.$record->{dns_name} .']' if ($record->{dns_name});
  159. $auth_ident = $auth_ident . ' :: '.$record->{description} if ($record->{dns_name});
  160. my $new;
  161. $new->{'blocked'}=0;
  162. $new->{'changed'}=1;
  163. my $ret_id = update_record($db,'user_auth',$new,'id='.$record->{'id'});
  164. if ($ret_id) {
  165. $msg = $msg ."\n".$auth_ident;
  166. }
  167. }
  168. }
  169. my $new;
  170. $new->{'blocked'}=0;
  171. my $ret_id = update_record($db,'user_list','id='.$user_id);
  172. if ($ret_id) {
  173. db_log_info($db,$msg);
  174. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  175. }
  176. return $ret_id;
  177. }
  178. #---------------------------------------------------------------------------------------------------------------
  179. sub delete_user {
  180. my $db = shift;
  181. my $id = shift;
  182. #remove user record
  183. my $changes = delete_record($db, "user_list", "id=" . $id);
  184. #if fail - exit
  185. if (!$changes) { return; }
  186. #remove auth records
  187. my @t_user_auth = get_records_sql($db,'SELECT * FROM user_auth WHERE user_id='.$id);
  188. if (@t_user_auth and scalar @t_user_auth) {
  189. foreach my $row ( @t_user_auth ) { delete_user_auth($db,$row->{'id'}); }
  190. }
  191. #remove device
  192. my $device = get_record_sql($db, "SELECT * FROM devices WHERE user_id=".$id);
  193. if ($device) { delete_device($db,$device->{'id'}); }
  194. #remove auth assign rules
  195. do_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  196. return $changes;
  197. }
  198. #---------------------------------------------------------------------------------------------------------------
  199. sub delete_device {
  200. my $db = shift;
  201. my $id = shift;
  202. #remove user record
  203. my $changes = delete_record($db, "devices", "id=" . $id);
  204. #if fail - exit
  205. if (!$changes) { return; }
  206. unbind_ports($db, $id);
  207. do_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  208. do_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  209. do_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  210. do_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  211. do_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  212. return $changes;
  213. }
  214. #---------------------------------------------------------------------------------------------------------------
  215. sub is_hotspot {
  216. my $db = shift;
  217. my $ip = shift;
  218. my $users = new Net::Patricia;
  219. #check hotspot
  220. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  221. foreach my $row (@ip_rules) { $users->add_string($row->{subnet}); }
  222. if ($users->match_string($ip)) { return 1; }
  223. return 0;
  224. }
  225. #---------------------------------------------------------------------------------------------------------------
  226. sub get_office_subnet {
  227. my $db = shift;
  228. my $ip = shift;
  229. my $subnets = new Net::Patricia;
  230. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE office=1 AND LENGTH(subnet)>0');
  231. foreach my $row (@ip_rules) { $subnets->add_string($row->{subnet},$row); }
  232. return $subnets->match_string($ip);
  233. }
  234. #---------------------------------------------------------------------------------------------------------------
  235. sub get_notify_subnet {
  236. my $db = shift;
  237. my $ip = shift;
  238. my $notify_flag = get_office_subnet($db,$ip);
  239. if ($notify_flag) { return $notify_flag->{notify}; }
  240. return 0;
  241. }
  242. #---------------------------------------------------------------------------------------------------------------
  243. sub get_new_user_id {
  244. my $db = shift;
  245. my $ip = shift;
  246. my $mac = shift;
  247. my $hostname = shift;
  248. my $result;
  249. #check user rules
  250. $mac = mac_simplify($mac);
  251. $result->{ip} = $ip;
  252. $result->{mac} = mac_splitted($mac);
  253. $result->{dhcp_hostname} = $hostname;
  254. $result->{ou_id}=undef;
  255. $result->{user_id}=undef;
  256. my $hotspot_users = new Net::Patricia;
  257. #check hotspot
  258. my @hotspot_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  259. foreach my $row (@hotspot_rules) { $hotspot_users->add_string($row->{subnet},$default_hotspot_ou_id); }
  260. if ($hotspot_users->match_string($ip)) { $result->{ou_id}=$hotspot_users->match_string($ip); return $result; }
  261. #check ip
  262. if (defined $ip and $ip) {
  263. my $users = new Net::Patricia;
  264. #check ip rules
  265. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE rule_type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL');
  266. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{user_id}); }; }
  267. if ($users->match_string($ip)) { $result->{user_id}=$users->match_string($ip); return $result; }
  268. }
  269. #check mac
  270. if (defined $mac and $mac) {
  271. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE rule_type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  272. foreach my $user (@user_rules) {
  273. my $rule = mac_simplify($user->{rule});
  274. if ($mac=~/$rule/i) { $result->{user_id}=$user->{user_id}; return $result; }
  275. }
  276. }
  277. #check hostname
  278. if (defined $hostname and $hostname) {
  279. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE rule_type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  280. foreach my $user (@user_rules) {
  281. if ($hostname=~/$user->{rule}/i) { $result->{user_id}=$user->{user_id}; return $result; }
  282. }
  283. }
  284. #check ou rules
  285. #check ip
  286. if (defined $ip and $ip) {
  287. my $users = new Net::Patricia;
  288. #check ip rules
  289. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE rule_type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL');
  290. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{ou_id}); }; }
  291. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); return $result; }
  292. }
  293. #check mac
  294. if (defined $mac and $mac) {
  295. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE rule_type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  296. foreach my $user (@user_rules) {
  297. my $rule = mac_simplify($user->{rule});
  298. if ($mac=~/$rule/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  299. }
  300. }
  301. #check hostname
  302. if (defined $hostname and $hostname) {
  303. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE rule_type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  304. foreach my $user (@user_rules) {
  305. if ($hostname=~/$user->{rule}/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  306. }
  307. }
  308. if (!$result->{ou_id}) { $result->{ou_id}=$default_user_ou_id; }
  309. return $result;
  310. }
  311. #---------------------------------------------------------------------------------------------------------------
  312. sub set_changed {
  313. my $db = shift;
  314. my $id = shift;
  315. return if (!$db or !$id);
  316. my $update_record;
  317. $update_record->{changed}=1;
  318. update_record($db,'user_auth',$update_record,"id=$id");
  319. }
  320. #---------------------------------------------------------------------------------------------------------------
  321. sub update_dns_record {
  322. my $hdb = shift;
  323. my $auth_id = shift;
  324. return if (!$config_ref{enable_dns_updates});
  325. # Переподключение
  326. if (!$hdb or !$hdb->ping) { $hdb = init_db(); }
  327. #get domain
  328. my $ad_zone = get_option($hdb,33);
  329. #get dns server
  330. my $ad_dns = get_option($hdb,3);
  331. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $config_ref{enable_dns_updates});
  332. log_debug("Auth id: ".$auth_id);
  333. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  334. log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
  335. my @dns_queue = get_records_sql($hdb,"SELECT * FROM dns_queue WHERE auth_id=".$auth_id." AND value>'' AND value NOT LIKE '%.'ORDER BY id ASC");
  336. if (!@dns_queue or !scalar @dns_queue) { return; }
  337. foreach my $dns_cmd (@dns_queue) {
  338. my $fqdn = '';
  339. my $fqdn_ip = '';
  340. my $fqdn_parent = '';
  341. my $static_exists = 0;
  342. my $static_ref = '';
  343. my $static_ok = 0;
  344. eval {
  345. if ($dns_cmd->{name_type}=~/^cname$/i) {
  346. #skip update unknown domain
  347. if ($dns_cmd->{name} =~/\.$/ or $dns_cmd->{value} =~/\.$/) { next; }
  348. $fqdn=lc($dns_cmd->{name});
  349. $fqdn=~s/\.$ad_zone$//i;
  350. # $fqdn=~s/\.$//;
  351. if ($dns_cmd->{value}) {
  352. $fqdn_parent=lc($dns_cmd->{value});
  353. $fqdn_parent=~s/\.$ad_zone$//i;
  354. # $fqdn_parent=~s/\.$//;
  355. }
  356. $fqdn = $fqdn.".".$ad_zone;
  357. $fqdn_parent = $fqdn_parent.".".$ad_zone;
  358. #remove cname
  359. if ($dns_cmd->{operation_type} eq 'del') {
  360. delete_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  361. }
  362. #create cname
  363. if ($dns_cmd->{operation_type} eq 'add') {
  364. create_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  365. }
  366. }
  367. if ($dns_cmd->{name_type}=~/^a$/i) {
  368. #skip update unknown domain
  369. if ($dns_cmd->{name} =~/\.$/ or $dns_cmd->{value} =~/\.$/) { next; }
  370. $fqdn=lc($dns_cmd->{name});
  371. $fqdn=~s/\.$ad_zone$//i;
  372. # $fqdn=~s/\.$//;
  373. if (!$dns_cmd->{value}) { next; }
  374. $fqdn_ip=lc($dns_cmd->{value});
  375. $fqdn = $fqdn.".".$ad_zone;
  376. #dns update disabled?
  377. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  378. if (!$maybe_update_dns) {
  379. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  380. next;
  381. }
  382. #get aliases
  383. my @aliases = get_records_sql($hdb,"SELECT * FROM user_auth_alias WHERE auth_id=".$auth_id);
  384. #remove A & PTR
  385. if ($dns_cmd->{operation_type} eq 'del') {
  386. #remove aliases
  387. if (@aliases and scalar @aliases) {
  388. foreach my $alias (@aliases) {
  389. delete_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  390. delete_dns_hostname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  391. }
  392. }
  393. #remove main record
  394. delete_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  395. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  396. }
  397. #create A & PTR
  398. if ($dns_cmd->{operation_type} eq 'add') {
  399. my @dns_record=ResolveNames($fqdn,$dns_server);
  400. $static_exists = (scalar @dns_record>0);
  401. if ($static_exists) {
  402. $static_ref = join(' ',@dns_record);
  403. foreach my $dns_a (@dns_record) {
  404. if ($dns_a=~/^$fqdn_ip$/) { $static_ok = 1; }
  405. }
  406. db_log_debug($hdb,"Dns record for static record $fqdn: $static_ref");
  407. }
  408. #skip update if already exists
  409. if ($static_ok) {
  410. db_log_debug($hdb,"Static record for $fqdn [$static_ok] correct.");
  411. next;
  412. }
  413. #create record
  414. create_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  415. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  416. #create aliases
  417. if (@aliases and scalar @aliases) {
  418. foreach my $alias (@aliases) {
  419. create_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  420. }
  421. }
  422. }
  423. }
  424. #PTR
  425. if ($dns_cmd->{name_type}=~/^ptr$/i) {
  426. $fqdn=lc($dns_cmd->{name});
  427. $fqdn=~s/\.$ad_zone$//i;
  428. # $fqdn=~s/\.$//;
  429. if (!$dns_cmd->{value}) { next; }
  430. $fqdn_ip=lc($dns_cmd->{value});
  431. #skip update unknown domain
  432. if ($fqdn =~/\.$/) { next; }
  433. $fqdn = $fqdn.".".$ad_zone;
  434. #dns update disabled?
  435. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  436. if (!$maybe_update_dns) {
  437. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  438. next;
  439. }
  440. #remove A & PTR
  441. if ($dns_cmd->{operation_type} eq 'del') {
  442. #remove main record
  443. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  444. }
  445. #create A & PTR
  446. if ($dns_cmd->{operation_type} eq 'add') {
  447. #create record
  448. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  449. }
  450. }
  451. };
  452. if ($@) { log_error("Error dns commands: $@"); }
  453. }
  454. }
  455. #---------------------------------------------------------------------------------------------------------------
  456. sub is_ad_computer {
  457. my $hdb = shift;
  458. my $computer_name = shift;
  459. if (!$computer_name or $computer_name =~/UNDEFINED/i) { return 0; }
  460. my $ad_check = get_option($hdb,73);
  461. if (!$ad_check) { return 1; }
  462. my $ad_zone = get_option($hdb,33);
  463. if ($computer_name =~/\./) {
  464. if ($computer_name!~/\.$ad_zone$/i) {
  465. db_log_verbose($hdb,"The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  466. return 0;
  467. }
  468. }
  469. if ($computer_name =~/^(.+)\./) {
  470. $computer_name = $1;
  471. }
  472. my $ad_computer_name = trim($computer_name).'$';
  473. my $name_in_cache = get_record_sql($hdb,"SELECT * FROM ad_comp_cache WHERE name='".$computer_name."'");
  474. if ($name_in_cache) { return 1; }
  475. my %name_found=do_exec_ref('/usr/bin/getent passwd '.$ad_computer_name);
  476. if (!$name_found{output} or $name_found{status} ne 0) {
  477. db_log_verbose($hdb,"The computer ".uc($ad_computer_name)." was not found in the domain $ad_zone. Skip update.");
  478. return 0;
  479. }
  480. do_sql($hdb,"INSERT INTO ad_comp_cache(name) VALUES('".$computer_name."') ON DUPLICATE KEY UPDATE name='".$computer_name."';");
  481. return 1;
  482. }
  483. #---------------------------------------------------------------------------------------------------------------
  484. sub update_dns_record_by_dhcp {
  485. my $hdb = shift;
  486. my $dhcp_record = shift;
  487. my $auth_record = shift;
  488. return if (!$config_ref{enable_dns_updates});
  489. my $ad_zone = get_option($hdb,33);
  490. my $ad_dns = get_option($hdb,3);
  491. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  492. my $subnets_dhcp = get_subnets_ref($hdb);
  493. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  494. log_debug("Dhcp record: ".Dumper($dhcp_record));
  495. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  496. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  497. log_debug("DNS update flags - zone: ".$ad_zone.",dns: ".$ad_dns.", update_hostname_from_dhcp: ".$update_hostname_from_dhcp.", enable_ad_dns_update: ".$enable_ad_dns_update. ", network dns-update enabled: ".$subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname});
  498. my $maybe_update_dns=($enable_ad_dns_update and $subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname} and (is_ad_computer($hdb,$dhcp_record->{hostname_utf8}) and ($dhcp_record->{type}=~/add/i or $dhcp_record->{type}=~/old/i)));
  499. if (!$maybe_update_dns) {
  500. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  501. return 0;
  502. }
  503. log_debug("DNS update enabled.");
  504. #update dns block
  505. my $fqdn_static;
  506. if ($auth_record->{dns_name}) {
  507. $fqdn_static=lc($auth_record->{dns_name});
  508. if ($fqdn_static!~/\.$ad_zone$/i) {
  509. $fqdn_static=~s/\.$//;
  510. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  511. }
  512. }
  513. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  514. if ($fqdn!~/\.$ad_zone$/i) {
  515. $fqdn=~s/\.$//;
  516. $fqdn=lc($fqdn.'.'.$ad_zone);
  517. }
  518. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  519. #check exists static dns name
  520. my $static_exists = 0;
  521. my $dynamic_exists = 0;
  522. my $static_ok = 0;
  523. my $dynamic_ok = 0;
  524. my $static_ref;
  525. my $dynamic_ref;
  526. if ($fqdn_static ne '') {
  527. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  528. $static_exists = (scalar @dns_record>0);
  529. if ($static_exists) {
  530. $static_ref = join(' ',@dns_record);
  531. foreach my $dns_a (@dns_record) {
  532. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  533. }
  534. }
  535. } else { $static_ok = 1; }
  536. if ($fqdn ne '') {
  537. my @dns_record=ResolveNames($fqdn,$dns_server);
  538. $dynamic_exists = (scalar @dns_record>0);
  539. if ($dynamic_exists) {
  540. $dynamic_ref = join(' ',@dns_record);
  541. foreach my $dns_a (@dns_record) {
  542. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  543. }
  544. }
  545. }
  546. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  547. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  548. if ($fqdn_static ne '') {
  549. if (!$static_ok) {
  550. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  551. if (!$static_exists) {
  552. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  553. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  554. }
  555. } else {
  556. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  557. }
  558. }
  559. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  560. if ($fqdn ne '' and !$dynamic_ok) {
  561. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  562. #check exists hostname
  563. my $another_hostname_exists = 0;
  564. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  565. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  566. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  567. }
  568. #check exists another records with some static hostname
  569. my $filter_sql = 'SELECT * FROM user_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  570. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  571. my $name_record = get_record_sql($hdb,$filter_sql);
  572. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  573. $another_hostname_exists = 1;
  574. }
  575. if (!$another_hostname_exists) {
  576. if ($fqdn_static and $fqdn_static ne '') {
  577. if ($fqdn_static!~/$fqdn/) {
  578. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  579. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  580. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  581. }
  582. } else {
  583. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  584. #get and remove aliases
  585. my @aliases = get_records_sql($hdb,"SELECT * FROM user_auth_alias WHERE auth_id=".$auth_record->{id});
  586. if (@aliases and scalar @aliases) {
  587. foreach my $alias (@aliases) {
  588. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  589. }
  590. }
  591. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  592. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  593. if (@aliases and scalar @aliases) {
  594. foreach my $alias (@aliases) {
  595. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  596. }
  597. }
  598. }
  599. } else {
  600. db_log_error($hdb,"Found another record with some hostname id: $name_record->{id} ip: $name_record->{ip} hostname: $name_record->{dns_name}. Skip update.");
  601. }
  602. }
  603. #end update dns block
  604. }
  605. #------------------------------------------------------------------------------------------------------------
  606. use DateTime::Format::Strptime;
  607. sub apply_device_lock {
  608. my $db = shift;
  609. my $device_id = shift;
  610. my $iteration = shift || 0;
  611. $iteration++;
  612. if ($iteration > 2) { return 0; }
  613. my $dev = get_record_sql($db, "SELECT discovery_locked, locked_timestamp FROM devices WHERE id = " . int($device_id));
  614. if (!$dev) { return 0; }
  615. if (!$dev->{'discovery_locked'}) {
  616. return set_lock_discovery($db, $device_id);
  617. }
  618. my $ts_str = $dev->{'locked_timestamp'};
  619. # Если locked_timestamp NULL или пустой — устанавливаем блокировку
  620. if (!defined $ts_str || $ts_str eq '' || $ts_str eq '0000-00-00 00:00:00') {
  621. return set_lock_discovery($db, $device_id);
  622. }
  623. # Удаляем микросекунды (PostgreSQL) для совместимости с форматом
  624. $ts_str =~ s/\.\d+$//;
  625. # Парсим строку в DateTime
  626. my $parser = DateTime::Format::Strptime->new(
  627. pattern => '%Y-%m-%d %H:%M:%S',
  628. on_error => 'croak',
  629. );
  630. my $dt;
  631. eval {
  632. $dt = $parser->parse_datetime($ts_str);
  633. };
  634. if ($@ || !$dt) {
  635. # Ошибка парсинга — считаем блокировку недействительной
  636. return set_lock_discovery($db, $device_id);
  637. }
  638. # Получаем Unix timestamp
  639. my $u_locked_timestamp = $dt->epoch;
  640. # Ждём окончания блокировки (30 секунд)
  641. my $wait_time = ($u_locked_timestamp + 30) - time();
  642. if ($wait_time <= 0) {
  643. return set_lock_discovery($db, $device_id);
  644. }
  645. sleep($wait_time);
  646. return apply_device_lock($db, $device_id, $iteration);
  647. }
  648. #------------------------------------------------------------------------------------------------------------
  649. sub set_lock_discovery {
  650. my $db = shift;
  651. my $device_id = shift;
  652. my $new;
  653. $new->{'discovery_locked'} = 1;
  654. $new->{'locked_timestamp'} = GetNowTime();
  655. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  656. return 0;
  657. }
  658. #------------------------------------------------------------------------------------------------------------
  659. sub unset_lock_discovery {
  660. my $db = shift;
  661. my $device_id = shift;
  662. my $new;
  663. $new->{'discovery_locked'} = 0;
  664. $new->{'locked_timestamp'} = GetNowTime();
  665. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  666. return 0;
  667. }
  668. #------------------------------------------------------------------------------------------------------------
  669. sub create_dns_cname {
  670. my $fqdn = shift;
  671. my $alias = shift;
  672. my $zone = shift;
  673. my $server = shift;
  674. my $db = shift;
  675. #skip update domain controllers
  676. if (!$db) {
  677. log_info("DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn");
  678. } else {
  679. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  680. }
  681. my $ad_zone = get_option($db,33);
  682. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  683. my @add_dns;
  684. if ($config_ref{dns_server_type}=~/windows/i) {
  685. push(@add_dns,"gsstsig");
  686. push(@add_dns,"server $server");
  687. push(@add_dns,"zone $zone");
  688. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  689. push(@add_dns,"send");
  690. write_to_file($nsupdate_file,\@add_dns);
  691. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  692. }
  693. if ($config_ref{dns_server_type}=~/bind/i) {
  694. push(@add_dns,"server $server");
  695. push(@add_dns,"zone $zone");
  696. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  697. push(@add_dns,"send");
  698. write_to_file($nsupdate_file,\@add_dns);
  699. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  700. }
  701. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  702. }
  703. #---------------------------------------------------------------------------------------------------------------
  704. sub delete_dns_cname {
  705. my $fqdn = shift;
  706. my $alias = shift;
  707. my $zone = shift;
  708. my $server = shift;
  709. my $db = shift;
  710. if (!$db) {
  711. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  712. } else {
  713. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  714. }
  715. my $ad_zone = get_option($db,33);
  716. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  717. my @add_dns;
  718. if ($config_ref{dns_server_type}=~/windows/i) {
  719. push(@add_dns,"gsstsig");
  720. push(@add_dns,"server $server");
  721. push(@add_dns,"zone $zone");
  722. push(@add_dns,"update delete $alias cname ");
  723. push(@add_dns,"send");
  724. write_to_file($nsupdate_file,\@add_dns);
  725. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  726. }
  727. if ($config_ref{dns_server_type}=~/bind/i) {
  728. push(@add_dns,"server $server");
  729. push(@add_dns,"zone $zone");
  730. push(@add_dns,"update delete $alias cname");
  731. push(@add_dns,"send");
  732. write_to_file($nsupdate_file,\@add_dns);
  733. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  734. }
  735. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  736. }
  737. #------------------------------------------------------------------------------------------------------------
  738. sub create_dns_hostname {
  739. my $fqdn = shift;
  740. my $ip = shift;
  741. my $zone = shift;
  742. my $server = shift;
  743. my $db = shift;
  744. #skip update domain controllers
  745. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  746. if (!$db) {
  747. log_info("DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  748. } else {
  749. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  750. }
  751. my $ad_zone = get_option($db,33);
  752. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  753. my @add_dns;
  754. if ($config_ref{dns_server_type}=~/windows/i) {
  755. push(@add_dns,"gsstsig");
  756. push(@add_dns,"server $server");
  757. push(@add_dns,"zone $zone");
  758. push(@add_dns,"update add $fqdn 3600 A $ip");
  759. push(@add_dns,"send");
  760. write_to_file($nsupdate_file,\@add_dns);
  761. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  762. }
  763. if ($config_ref{dns_server_type}=~/bind/i) {
  764. push(@add_dns,"server $server");
  765. push(@add_dns,"zone $zone");
  766. push(@add_dns,"update add $fqdn 3600 A $ip");
  767. push(@add_dns,"send");
  768. write_to_file($nsupdate_file,\@add_dns);
  769. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  770. }
  771. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  772. }
  773. #---------------------------------------------------------------------------------------------------------------
  774. sub delete_dns_hostname {
  775. my $fqdn = shift;
  776. my $ip = shift;
  777. my $zone = shift;
  778. my $server = shift;
  779. my $db = shift;
  780. #skip update domain controllers
  781. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  782. if (!$db) {
  783. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  784. } else {
  785. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  786. }
  787. my $ad_zone = get_option($db,33);
  788. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  789. my @add_dns;
  790. if ($config_ref{dns_server_type}=~/windows/i) {
  791. push(@add_dns,"gsstsig");
  792. push(@add_dns,"server $server");
  793. push(@add_dns,"zone $zone");
  794. push(@add_dns,"update delete $fqdn A");
  795. push(@add_dns,"send");
  796. write_to_file($nsupdate_file,\@add_dns);
  797. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  798. }
  799. if ($config_ref{dns_server_type}=~/bind/i) {
  800. push(@add_dns,"server $server");
  801. push(@add_dns,"zone $zone");
  802. push(@add_dns,"update delete $fqdn A");
  803. push(@add_dns,"send");
  804. write_to_file($nsupdate_file,\@add_dns);
  805. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  806. }
  807. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  808. }
  809. #---------------------------------------------------------------------------------------------------------------
  810. sub create_dns_ptr {
  811. my $fqdn = shift;
  812. my $ip = shift;
  813. my $ad_zone = shift;
  814. my $server = shift;
  815. my $db = shift;
  816. my $radr;
  817. my $zone;
  818. #skip update domain controllers
  819. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  820. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  821. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  822. $radr = "$4.$3.$2.$1.in-addr.arpa";
  823. $zone = "$3.$2.$1.in-addr.arpa";
  824. }
  825. if (!$radr or !$zone) { return 0; }
  826. if (!$db) { return 0; }
  827. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  828. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  829. my @add_dns;
  830. if ($config_ref{dns_server_type}=~/windows/i) {
  831. push(@add_dns,"gsstsig");
  832. push(@add_dns,"server $server");
  833. push(@add_dns,"zone $zone");
  834. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  835. push(@add_dns,"send");
  836. write_to_file($nsupdate_file,\@add_dns);
  837. my $run_cmd = '/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"';
  838. do_exec($run_cmd);
  839. }
  840. if ($config_ref{dns_server_type}=~/bind/i) {
  841. push(@add_dns,"server $server");
  842. push(@add_dns,"zone $zone");
  843. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  844. push(@add_dns,"send");
  845. write_to_file($nsupdate_file,\@add_dns);
  846. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  847. do_exec($run_cmd);
  848. }
  849. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  850. }
  851. #---------------------------------------------------------------------------------------------------------------
  852. sub delete_dns_ptr {
  853. my $fqdn = shift;
  854. my $ip = shift;
  855. my $ad_zone = shift;
  856. my $server = shift;
  857. my $db = shift;
  858. my $radr;
  859. my $zone;
  860. #skip update domain controllers
  861. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  862. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  863. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  864. $radr = "$4.$3.$2.$1.in-addr.arpa";
  865. $zone = "$3.$2.$1.in-addr.arpa";
  866. }
  867. if (!$radr or !$zone) { return 0; }
  868. if (!$db) { return 0 ; }
  869. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  870. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  871. my @add_dns;
  872. if ($config_ref{dns_server_type}=~/windows/i) {
  873. push(@add_dns,"gsstsig");
  874. push(@add_dns,"server $server");
  875. push(@add_dns,"zone $zone");
  876. push(@add_dns,"update delete $radr PTR");
  877. push(@add_dns,"send");
  878. write_to_file($nsupdate_file,\@add_dns);
  879. my $run_cmd = '/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"';
  880. do_exec($run_cmd);
  881. }
  882. if ($config_ref{dns_server_type}=~/bind/i) {
  883. push(@add_dns,"server $server");
  884. push(@add_dns,"zone $zone");
  885. push(@add_dns,"update delete $radr PTR");
  886. push(@add_dns,"send");
  887. write_to_file($nsupdate_file,\@add_dns);
  888. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  889. do_exec($run_cmd);
  890. }
  891. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  892. }
  893. #---------------------------------------------------------------------------------------------------------------
  894. sub new_user {
  895. my $db = shift;
  896. my $user_info = shift;
  897. my $user;
  898. if ($user_info->{mac}) {
  899. $user->{login}=mac_splitted($user_info->{mac});
  900. } else {
  901. $user->{login}=$user_info->{ip};
  902. }
  903. if ($user_info->{dhcp_hostname}) { $user->{fio}=$user_info->{dhcp_hostname}; }
  904. if (!$user->{fio}) { $user->{fio}=$user_info->{ip}; }
  905. my $login_count = get_count_records($db,"user_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  906. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  907. $user->{ou_id} = $user_info->{ou_id};
  908. my $ou_info = get_record_sql($db,"SELECT * FROM ou WHERE id=".$user_info->{'ou_id'});
  909. if ($ou_info) {
  910. $user->{'enabled'} = $ou_info->{'enabled'};
  911. $user->{'queue_id'} = $ou_info->{'queue_id'};
  912. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  913. }
  914. my $result = insert_record($db,"user_list",$user);
  915. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  916. my $auth_rule;
  917. $auth_rule->{user_id} = $result;
  918. $auth_rule->{rule_type} = 2;
  919. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  920. insert_record($db,"auth_rules",$auth_rule);
  921. }
  922. return $result;
  923. }
  924. #---------------------------------------------------------------------------------------------------------------
  925. sub get_ip_subnet {
  926. my $db = shift;
  927. my $ip = shift;
  928. if (!$ip) { return; }
  929. my $ip_aton = StrToIp($ip);
  930. my $user_subnet = get_record_sql($db, "SELECT * FROM subnets WHERE hotspot=1 or office=1 and ( ".$ip_aton." >= ip_int_start and ".$ip_aton." <= ip_int_stop)");
  931. return $user_subnet;
  932. }
  933. #---------------------------------------------------------------------------------------------------------------
  934. sub find_mac_in_subnet {
  935. my $db = shift;
  936. my $ip = shift;
  937. my $mac = shift;
  938. if (!$ip or !$mac) { return; }
  939. my $ip_subnet = get_ip_subnet($db, $ip);
  940. if (!$ip_subnet) { return; }
  941. my @t_auth = get_records_sql($db, "SELECT * FROM user_auth WHERE ip_int>=" . $ip_subnet->{'ip_int_start'} . " and ip_int<=" . $ip_subnet->{'ip_int_stop'} . " and mac='" . $mac . "' and deleted=0 ORDER BY id");
  942. my $auth_count = 0;
  943. my $result;
  944. $result->{'count'} = 0;
  945. foreach my $row (@t_auth) {
  946. next if (!$row);
  947. $auth_count++;
  948. $result->{'count'} = $auth_count;
  949. $result->{items}{$auth_count} = $row;
  950. }
  951. return $result;
  952. }
  953. #---------------------------------------------------------------------------------------------------------------
  954. sub resurrection_auth {
  955. my $db = shift;
  956. my $ip_record = shift;
  957. my $ip = $ip_record->{'ip'};
  958. my $mac = $ip_record->{'mac'};
  959. my $action = $ip_record->{'type'};
  960. my $hostname = $ip_record->{'hostname_utf8'};
  961. my $client_id = $ip_record->{'client_id'};
  962. if (!exists $ip_record->{ip_aton}) { $ip_record->{ip_aton}=StrToIp($ip); }
  963. if (!exists $ip_record->{hotspot}) { $ip_record->{hotspot}=is_hotspot($db,$ip); }
  964. my $auth_ident = "Found new ip-address: " . $ip;
  965. $auth_ident = $auth_ident . ' ['.$mac .']' if ($mac);
  966. $auth_ident = $auth_ident . ' :: '.$hostname if ($hostname);
  967. my $ip_aton=$ip_record->{ip_aton};
  968. my $timestamp=GetNowTime();
  969. my $record=get_record_sql($db,'SELECT * FROM user_auth WHERE deleted=0 AND ip_int='.$ip_aton." AND mac='".$mac."'");
  970. my $new_record;
  971. $new_record->{last_found}=$timestamp;
  972. $new_record->{arp_found}=$timestamp;
  973. if ($client_id) { $new_record->{'client_id'} = $client_id; }
  974. #auth found?
  975. if ($record->{user_id}) {
  976. #update timestamp and return
  977. if ($action=~/^(add|old|del)$/i) {
  978. $new_record->{dhcp_action}=$action;
  979. $new_record->{created_by}='dhcp';
  980. $new_record->{dhcp_time}=$timestamp;
  981. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  982. }
  983. update_record($db,'user_auth',$new_record,"id=$record->{id}");
  984. return $record->{id};
  985. }
  986. my $user_subnet=$office_networks->match_string($ip);
  987. if ($user_subnet->{static}) {
  988. db_log_warning($db,"Unknown ip+mac found in static subnet! Abort create record for ip: $ip mac: [".$mac."]");
  989. return 0;
  990. }
  991. my $send_alert_update = isNotifyUpdate(get_notify_subnet($db,$ip));
  992. my $send_alert_create = isNotifyCreate(get_notify_subnet($db,$ip));
  993. #my $send_alert_delete = isNotifyDelete(get_notify_subnet($db,$ip));
  994. my $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  995. my $msg = '';
  996. #search changed mac
  997. $record=get_record_sql($db,'SELECT * FROM user_auth WHERE ip_int='.$ip_aton." and deleted=0");
  998. if ($record->{id}) {
  999. #if found record with same ip but without mac - update it
  1000. if (!$record->{mac}) {
  1001. $msg = $auth_ident. "\nUse auth record with no mac: " . hash_to_text($record);
  1002. db_log_verbose($db,$msg);
  1003. $new_record->{mac}=$mac;
  1004. #disable dhcp for same mac in one ip subnet
  1005. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1006. if ($action=~/^(add|old|del)$/i) {
  1007. $new_record->{dhcp_action}=$action;
  1008. $new_record->{dhcp_time}=$timestamp;
  1009. $new_record->{created_by}='dhcp';
  1010. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1011. }
  1012. update_record($db,'user_auth',$new_record,"id=$record->{id}");
  1013. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert_update);
  1014. return $record->{id};
  1015. }
  1016. #if found record with same ip but another mac - delete old record
  1017. if ($record->{mac}) {
  1018. if (!$ip_record->{hotspot}) {
  1019. my $msg = "For ip: $ip mac change detected! Old mac: [".$record->{mac}."] New mac: [".$mac."]. Disable old auth_id: $record->{id}";
  1020. db_log_warning($db,$msg,$record->{id});
  1021. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert_update);
  1022. }
  1023. delete_user_auth($db,$record->{id});
  1024. }
  1025. }
  1026. #default user
  1027. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  1028. my $new_user_id;
  1029. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1030. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  1031. if ($mac_exists) {
  1032. #deleting the user's entry if the address belongs to a dynamic group
  1033. foreach my $dup_record_id (keys %{$mac_exists->{items}}) {
  1034. my $dup_record = $mac_exists->{items}{$dup_record_id};
  1035. next if (!$dup_record);
  1036. #remove old dynamic record with some mac
  1037. if ($dup_record->{dynamic}) {
  1038. delete_user_auth($db,$dup_record->{id});
  1039. }
  1040. }
  1041. }
  1042. #recheck
  1043. $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1044. #disable dhcp for same mac in one ip subnet
  1045. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1046. #seek old auth with same ip and mac
  1047. my $auth_exists=get_count_records($db,'user_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1048. $new_record->{ip_int}=$ip_aton;
  1049. $new_record->{ip}=$ip;
  1050. $new_record->{mac}=$mac;
  1051. $new_record->{user_id}=$new_user_id;
  1052. $new_record->{save_traf}="$save_detail";
  1053. $new_record->{deleted}="0";
  1054. if ($action=~/^(add|old|del)$/i) {
  1055. $new_record->{dhcp_action}=$action;
  1056. $new_record->{dhcp_time}=$timestamp;
  1057. $new_record->{created_by}='dhcp';
  1058. } else {
  1059. $new_record->{created_by}=$action;
  1060. }
  1061. my $cur_auth_id= 0;
  1062. if ($auth_exists) {
  1063. #found ->Resurrection old record
  1064. my $resurrection_id = get_id_record($db,'user_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1065. $msg = $auth_ident . " Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac";
  1066. if (!$ip_record->{hotspot}) { db_log_warning($db,$msg); } else { db_log_info($db,$msg); }
  1067. if (update_record($db,'user_auth',$new_record,"id=$resurrection_id")) { $cur_auth_id = $resurrection_id; }
  1068. } else {
  1069. #not found ->create new record
  1070. $msg = $auth_ident ."\n";
  1071. $cur_auth_id = insert_record($db,'user_auth',$new_record);
  1072. if ($cur_auth_id) {
  1073. if (!$ip_record->{hotspot}) { db_log_warning($db,$msg); } else { db_log_info($db,$msg); }
  1074. }
  1075. }
  1076. #filter and status
  1077. $cur_auth_id=get_id_record($db,'user_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC") if (!$cur_auth_id);
  1078. if ($cur_auth_id) {
  1079. my $user_record=get_record_sql($db,"SELECT * FROM user_list WHERE id=".$new_user_id);
  1080. if ($user_record) {
  1081. my $ou_info = get_record_sql($db,'SELECT * FROM ou WHERE id='.$user_record->{ou_id});
  1082. if ($ou_info and $ou_info->{'dynamic'}) {
  1083. # Устанавливаем значение по умолчанию, если не задано
  1084. if (!$ou_info->{'life_duration'}) {
  1085. $ou_info->{'life_duration'} = 24.0; # Явно указываем дробное число
  1086. }
  1087. my $now = DateTime->now(time_zone => 'local');
  1088. # Разбиваем life_duration на часы и минуты (для дробного значения)
  1089. my $hours = int($ou_info->{'life_duration'}); # Целая часть (часы)
  1090. my $minutes = ($ou_info->{'life_duration'} - $hours) * 60; # Дробная часть → минуты
  1091. # Создаём продолжительность с учётом дробных часов (в виде часов + минут)
  1092. my $duration = DateTime::Duration->new( hours => $hours, minutes => $minutes);
  1093. my $end_life = $now + $duration;
  1094. $new_record->{'dynamic'} = 1;
  1095. $new_record->{'end_life'} = $end_life->strftime('%Y-%m-%d %H:%M:%S');
  1096. }
  1097. $new_record->{ou_id}=$user_record->{ou_id};
  1098. $new_record->{description}=$user_record->{fio};
  1099. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1100. $new_record->{queue_id}=$user_record->{queue_id};
  1101. $new_record->{enabled}="$user_record->{enabled}";
  1102. update_record($db,'user_auth',$new_record,"id=$cur_auth_id");
  1103. }
  1104. db_log_warning($db, $msg, $cur_auth_id);
  1105. sendEmail("WARN! ".get_first_line($msg),$msg."\n".record_to_txt($db,'user_auth',$cur_auth_id),1) if ($send_alert_create);
  1106. } else { return; }
  1107. return $cur_auth_id;
  1108. }
  1109. #---------------------------------------------------------------------------------------------------------------
  1110. sub new_auth {
  1111. my $db = shift;
  1112. my $ip = shift;
  1113. my $ip_aton=StrToIp($ip);
  1114. my $record=get_record_sql($db,'SELECT id FROM user_auth WHERE deleted=0 AND ip_int='.$ip_aton);
  1115. if ($record->{id}) { return $record->{id}; }
  1116. #default user
  1117. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  1118. my $new_user_id;
  1119. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1120. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  1121. if (is_dynamic_ou($db,$new_user_info->{ou_id})) {
  1122. db_log_debug($db,"The ip-address $ip belongs to a dynamic group - ignore it.");
  1123. return;
  1124. }
  1125. my $send_alert = isNotifyCreate(get_notify_subnet($db,$ip));
  1126. my $user_record=get_record_sql($db,"SELECT * FROM user_list WHERE id=".$new_user_id);
  1127. my $timestamp=GetNowTime();
  1128. my $new_record;
  1129. $new_record->{ip_int}=$ip_aton;
  1130. $new_record->{ip}=$ip;
  1131. $new_record->{user_id}=$new_user_id;
  1132. $new_record->{save_traf}="$save_detail";
  1133. $new_record->{deleted}="0";
  1134. $new_record->{created_by}='netflow';
  1135. $new_record->{ou_id}=$user_record->{ou_id};
  1136. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1137. $new_record->{queue_id}=$user_record->{queue_id};
  1138. $new_record->{enabled}="$user_record->{enabled}";
  1139. if ($user_record->{fio}) { $new_record->{description}=$user_record->{fio}; }
  1140. my $cur_auth_id=insert_record($db,'user_auth',$new_record);
  1141. if ($cur_auth_id) {
  1142. my $msg = "New ip created by netflow! ip: $ip";
  1143. db_log_warning($db,$msg,$cur_auth_id);
  1144. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  1145. }
  1146. return $cur_auth_id;
  1147. }
  1148. #--------------------------------------------------------------------------------------------------------------
  1149. sub get_dynamic_ou {
  1150. my $db = shift;
  1151. my @dynamic=();
  1152. my @ou_list = get_records_sql($db,"SELECT id FROM ou WHERE dynamic = 1");
  1153. foreach my $group (@ou_list) {
  1154. next if (!$group);
  1155. push(@dynamic,$group->{id});
  1156. }
  1157. return wantarray ? @dynamic : \@dynamic;
  1158. }
  1159. #--------------------------------------------------------------------------------------------------------------
  1160. sub get_default_ou {
  1161. my $db = shift;
  1162. my @dynamic=();
  1163. my $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_users = 1");
  1164. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1165. $ou = get_record_sql($db,"SELECT id FROM ou WHERE default_hotspot = 1");
  1166. if ($ou) { push(@dynamic,$ou->{id}); }
  1167. return wantarray ? @dynamic : \@dynamic;
  1168. }
  1169. #--------------------------------------------------------------------------------------------------------------
  1170. sub is_dynamic_ou {
  1171. my $db = shift;
  1172. my $ou_id = shift;
  1173. my @dynamic=get_dynamic_ou($db);
  1174. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1175. return 0;
  1176. }
  1177. #--------------------------------------------------------------------------------------------------------------
  1178. sub is_default_ou {
  1179. my $db = shift;
  1180. my $ou_id = shift;
  1181. my @dynamic=get_default_ou($db);
  1182. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1183. return 0;
  1184. }
  1185. #---------------------------------------------------------------------------------------------------------------
  1186. sub get_subnets_ref {
  1187. my $db = shift;
  1188. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1189. my $list_ref;
  1190. foreach my $net (@list) {
  1191. next if (!$net->{subnet});
  1192. $list_ref->{$net->{subnet}}=$net;
  1193. }
  1194. return $list_ref;
  1195. }
  1196. #---------------------------------------------------------------------------------------------------------------
  1197. sub get_device_by_ip {
  1198. my $db = shift;
  1199. my $ip = shift;
  1200. my $netdev=get_record_sql($db,"SELECT * FROM devices WHERE ip='".$ip."'");
  1201. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1202. my $auth_rec=get_record_sql($db,"SELECT user_id FROM user_auth WHERE ip='".$ip."' and deleted=0");
  1203. if ($auth_rec and $auth_rec->{user_id}>0) {
  1204. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1205. return $netdev;
  1206. }
  1207. return;
  1208. }
  1209. #---------------------------------------------------------------------------------------------------------------
  1210. sub recalc_quotes {
  1211. my $db = shift;
  1212. my $calc_id = shift || $$;
  1213. return if (!get_option($db,54));
  1214. clean_variables($db);
  1215. return if (Get_Variable($db,'RECALC'));
  1216. my $timeshift = get_option($db,55);
  1217. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  1218. my $now = DateTime->now(time_zone=>'local');
  1219. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  1220. my $day_dur = DateTime::Duration->new( days => 1 );
  1221. my $tomorrow = $now+$day_dur;
  1222. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  1223. $now->set(day=>1);
  1224. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  1225. my $month_dur = DateTime::Duration->new( months => 1 );
  1226. my $next_month = $now + $month_dur;
  1227. $next_month->set(day=>1);
  1228. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  1229. #get user limits
  1230. my $user_auth_list_sql="SELECT A.id as auth_id, U.id, U.day_quota, U.month_quota, A.day_quota as auth_day, A.month_quota as auth_month FROM user_auth as A,user_list as U WHERE A.deleted=0 ORDER by user_id";
  1231. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  1232. my %user_stats;
  1233. my %auth_info;
  1234. foreach my $row (@authlist_ref) {
  1235. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  1236. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  1237. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  1238. $auth_info{$row->{auth_id}}{day}=0;
  1239. $auth_info{$row->{auth_id}}{month}=0;
  1240. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  1241. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  1242. $user_stats{$row->{id}}{day}=0;
  1243. $user_stats{$row->{id}}{month}=0;
  1244. }
  1245. #recalc quotes - global
  1246. #day
  1247. my $day_sql="SELECT user_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM user_stats
  1248. WHERE user_stats.ts>= $day_start AND user_stats.ts< $day_stop GROUP BY user_stats.auth_id";
  1249. my @day_stats = get_records_sql($db,$day_sql);
  1250. foreach my $row (@day_stats) {
  1251. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1252. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  1253. $user_stats{$user_id}{day}+=$row->{traf_all};
  1254. }
  1255. #month
  1256. my $month_sql="SELECT user_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM user_stats
  1257. WHERE user_stats.ts>= $month_start AND user_stats.ts< $month_stop GROUP BY user_stats.auth_id";
  1258. my @month_stats = get_records_sql($db,$month_sql);
  1259. foreach my $row (@month_stats) {
  1260. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1261. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  1262. $user_stats{$user_id}{month}+=$row->{traf_all};
  1263. }
  1264. foreach my $auth_id (keys %auth_info) {
  1265. next if (!$auth_info{$auth_id}{day_limit});
  1266. next if (!$auth_info{$auth_id}{month_limit});
  1267. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1268. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1269. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1270. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1271. if ($blocked_d or $blocked_m) {
  1272. my $history_msg;
  1273. if ($blocked_d) { $history_msg=printf "Day quota limit found for auth_id: $auth_id - Current: %d Max: %d",$auth_info{$auth_id}{day},$day_limit; }
  1274. if ($blocked_m) { $history_msg=printf "Month quota limit found for auth_id: $auth_id - Current: %d Max: %d",$auth_info{$auth_id}{month},$month_limit; }
  1275. do_sql($db,"UPDATE user_auth set blocked=1, changed=1 where id=$auth_id");
  1276. db_log_verbose($db,$history_msg);
  1277. }
  1278. }
  1279. foreach my $user_id (keys %user_stats) {
  1280. next if (!$user_stats{$user_id}{day_limit});
  1281. next if (!$user_stats{$user_id}{month_limit});
  1282. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1283. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1284. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1285. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1286. if ($blocked_d or $blocked_m) {
  1287. my $history_msg;
  1288. if ($blocked_d) { $history_msg=printf "Day quota limit found for user_id: $user_id - Current: %d Max: %d",$user_stats{$user_id}{day},$day_limit; }
  1289. if ($blocked_m) { $history_msg=printf "Month quota limit found for user_id: $user_id - Current: %d Max: %d",$user_stats{$user_id}{month},$month_limit; }
  1290. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1291. do_sql($db,"UPDATE user_auth set blocked=1, changed=1 where user_id=$user_id");
  1292. db_log_verbose($db,$history_msg);
  1293. }
  1294. }
  1295. Del_Variable($db,'RECALC');
  1296. }
  1297. #--------------------------------------------------------------------------------
  1298. sub process_dhcp_request {
  1299. my ($db, $type, $mac, $ip, $hostname, $client_id, $circuit_id, $remote_id) = @_;
  1300. return if (!$type);
  1301. return if ($type!~/(old|add|del)/i);
  1302. my $client_hostname='';
  1303. if ($hostname and ($hostname ne "undef" or $hostname !~ /UNDEFINED/i)) { $client_hostname=$hostname; }
  1304. my $auth_network = $office_networks->match_string($ip);
  1305. if (!$auth_network) {
  1306. log_error("Unknown network in dhcp request! IP: $ip");
  1307. return;
  1308. }
  1309. if (!$circuit_id) { $circuit_id=''; }
  1310. if (!$client_id) { $client_id = ''; }
  1311. if (!$remote_id) { $remote_id = ''; }
  1312. my $timestamp=time();
  1313. my $ip_aton=StrToIp($ip);
  1314. $mac=mac_splitted(isc_mac_simplify($mac));
  1315. my $dhcp_event_time = GetNowTime($timestamp);
  1316. my $dhcp_record;
  1317. $dhcp_record->{'mac'}=$mac;
  1318. $dhcp_record->{'ip'}=$ip;
  1319. $dhcp_record->{'ip_aton'}=$ip_aton;
  1320. $dhcp_record->{'hostname'}=$client_hostname;
  1321. $dhcp_record->{'network'}=$auth_network;
  1322. $dhcp_record->{'type'}=$type;
  1323. $dhcp_record->{'hostname_utf8'}=$client_hostname;
  1324. $dhcp_record->{'ts'} = $timestamp;
  1325. $dhcp_record->{'last_time'} = time();
  1326. $dhcp_record->{'circuit_id'} = $circuit_id;
  1327. $dhcp_record->{'client_id'} = $client_id;
  1328. $dhcp_record->{'remote_id'} = $remote_id;
  1329. $dhcp_record->{'hotspot'}=is_hotspot($dbh,$dhcp_record->{ip});
  1330. #search actual record
  1331. my $auth_record = get_record_sql($db,"SELECT * FROM user_auth WHERE ip='".$dhcp_record->{ip}."' and mac='".$mac."' and deleted=0 ORDER BY last_found DESC");
  1332. #if record not found and type del => next event
  1333. if (!$auth_record and $type eq 'del') { return; }
  1334. #if record not found - create it
  1335. if (!$auth_record and $type=~/(add|old)/i) {
  1336. # db_log_warning($db,"Record for dhcp request type: ".$type." ip=".$dhcp_record->{ip}." and mac=".$mac." does not exists!");
  1337. my $res_id = resurrection_auth($db,$dhcp_record);
  1338. if (!$res_id) { db_log_error($db,"Error creating an ip address record for ip=".$dhcp_record->{ip}." and mac=".$mac."!"); return; }
  1339. $auth_record = get_record_sql($db,'SELECT * FROM user_auth WHERE id='.$res_id);
  1340. db_log_info($db,"Check for new auth. Found id: $res_id",$res_id);
  1341. }
  1342. my $auth_id = $auth_record->{id};
  1343. my $auth_ou_id = $auth_record->{ou_id};
  1344. $dhcp_record->{'auth_id'} = $auth_id;
  1345. $dhcp_record->{'auth_ou_id'} = $auth_ou_id;
  1346. log_debug(uc($type).">>");
  1347. log_debug("MAC: ".$dhcp_record->{'mac'});
  1348. log_debug("IP: ".$dhcp_record->{'ip'});
  1349. log_debug("CIRCUIT-ID: ".$dhcp_record->{circuit_id});
  1350. log_debug("REMOTE-ID: ".$dhcp_record->{remote_id});
  1351. log_debug("HOSTNAME: ".$dhcp_record->{'hostname'});
  1352. log_debug("TYPE: ".$dhcp_record->{'type'});
  1353. log_debug("TIME: ".$dhcp_event_time);
  1354. log_debug("AUTH_ID: ".$auth_id);
  1355. log_debug("END GET");
  1356. update_dns_record_by_dhcp($db,$dhcp_record,$auth_record);
  1357. if ($type=~/add/i and $dhcp_record->{hostname_utf8}) {
  1358. my $auth_rec;
  1359. $auth_rec->{dhcp_hostname} = $dhcp_record->{hostname_utf8};
  1360. $auth_rec->{dhcp_time}=$dhcp_event_time;
  1361. $auth_rec->{arp_found}=$dhcp_event_time;
  1362. $auth_rec->{created_by}='dhcp';
  1363. db_log_verbose($db,"Add lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  1364. update_record($db,'user_auth',$auth_rec,"id=$auth_id");
  1365. }
  1366. if ($type=~/old/i) {
  1367. my $auth_rec;
  1368. $auth_rec->{dhcp_action}=$type;
  1369. $auth_rec->{dhcp_time}=$dhcp_event_time;
  1370. $auth_rec->{created_by}='dhcp';
  1371. $auth_rec->{arp_found}=$dhcp_event_time;
  1372. db_log_verbose($db,"Update lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  1373. update_record($db,'user_auth',$auth_rec,"id=$auth_id");
  1374. }
  1375. if ($type=~/del/i and $auth_id) {
  1376. if ($auth_record->{dhcp_time} =~ /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/) {
  1377. my $d_time = mktime($6,$5,$4,$3,$2-1,$1-1900);
  1378. if (time()-$d_time>60 and (is_dynamic_ou($db,$auth_ou_id) or is_default_ou($db,$auth_ou_id))) {
  1379. db_log_info($db,"Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  1380. my $auth_rec;
  1381. $auth_rec->{dhcp_action}=$type;
  1382. $auth_rec->{dhcp_time}=$dhcp_event_time;
  1383. update_record($db,'user_auth',$auth_rec,"id=$auth_id");
  1384. #remove user auth record if it belongs to the default pool or it is dynamic
  1385. if (is_default_ou($db,$auth_ou_id) or (is_dynamic_ou($db,$auth_ou_id) and $auth_record->{dynamic})) {
  1386. delete_user_auth($db,$auth_id);
  1387. my $u_count=get_count_records($db,'user_auth','deleted=0 and user_id='.$auth_record->{'user_id'});
  1388. if (!$u_count) { delete_user($db,$auth_record->{'user_id'}); }
  1389. }
  1390. }
  1391. }
  1392. }
  1393. if ($dhcp_record->{hotspot} and $ignore_hotspot_dhcp_log) { return $dhcp_record; }
  1394. if ($ignore_update_dhcp_event and $type=~/old/i) { return $dhcp_record; }
  1395. my $dhcp_log;
  1396. if (!$auth_id) { $auth_id=0; }
  1397. $dhcp_log->{'auth_id'} = $auth_id;
  1398. $dhcp_log->{'ip'} = $dhcp_record->{'ip'};
  1399. $dhcp_log->{'ip_int'} = $dhcp_record->{'ip_aton'};
  1400. $dhcp_log->{'mac'} = $dhcp_record->{'mac'};
  1401. $dhcp_log->{'action'} = $type;
  1402. $dhcp_log->{'dhcp_hostname'} = $dhcp_record->{'hostname_utf8'};
  1403. $dhcp_log->{'ts'} = $dhcp_event_time;
  1404. $dhcp_log->{'circuit_id'} = $circuit_id;
  1405. $dhcp_log->{'client_id'} = $client_id;
  1406. $dhcp_log->{'remote_id'} = $remote_id;
  1407. insert_record($db,'dhcp_log',$dhcp_log);
  1408. return $dhcp_record;
  1409. }
  1410. 1;
  1411. }