1
0

database.pm 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207
  1. package eyelib::database;
  2. #
  3. # Copyright (C) Roman Dmitiriev, 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 DateTime;
  19. use POSIX qw(mktime ctime strftime);
  20. use File::Temp qw(tempfile);
  21. use DBI;
  22. our @ISA = qw(Exporter);
  23. our @EXPORT = qw(
  24. batch_db_sql
  25. batch_db_sql_cached
  26. batch_db_sql_csv
  27. db_log_warning
  28. db_log_debug
  29. db_log_error
  30. db_log_info
  31. db_log_verbose
  32. delete_record
  33. do_sql
  34. Get_Variable
  35. Set_Variable
  36. Del_Variable
  37. get_count_records
  38. get_record_sql
  39. get_records_sql
  40. get_device_by_ip
  41. get_diff_rec
  42. get_id_record
  43. get_new_user_id
  44. is_hotspot
  45. GetNowTime
  46. GetUnixTimeByStr
  47. GetTimeStrByUnixTime
  48. get_option
  49. get_subnets_ref
  50. init_db
  51. init_option
  52. insert_record
  53. apply_device_lock
  54. set_lock_discovery
  55. unset_lock_discovery
  56. IpToStr
  57. unbind_ports
  58. resurrection_auth
  59. new_auth
  60. StrToIp
  61. get_first_line
  62. is_ad_computer
  63. get_dynamic_ou
  64. is_dynamic_ou
  65. get_default_ou
  66. is_default_ou
  67. update_dns_record
  68. update_dns_record_by_dhcp
  69. create_dns_cname
  70. delete_dns_cname
  71. create_dns_hostname
  72. delete_dns_hostname
  73. create_dns_ptr
  74. delete_dns_ptr
  75. update_record
  76. delete_user_auth
  77. delete_user
  78. delete_device
  79. write_db_log
  80. set_changed
  81. recalc_quotes
  82. clean_variables
  83. $add_rules
  84. $L_WARNING
  85. $L_INFO
  86. $L_DEBUG
  87. $L_ERROR
  88. $L_VERBOSE
  89. );
  90. BEGIN
  91. {
  92. #---------------------------------------------------------------------------------------------------------------
  93. our $add_rules;
  94. our $L_ERROR = 0;
  95. our $L_WARNING = 1;
  96. our $L_INFO = 2;
  97. our $L_VERBOSE = 3;
  98. our $L_DEBUG = 255;
  99. our %acl_fields = (
  100. 'ip' => '1',
  101. 'ip_int' => '1',
  102. 'enabled'=>'1',
  103. 'dhcp'=>'1',
  104. 'filter_group_id'=>'1',
  105. 'deleted'=>'1',
  106. 'dhcp_acl'=>'1',
  107. 'queue_id'=>'1',
  108. 'mac'=>'1',
  109. 'blocked'=>'1'
  110. );
  111. our %dhcp_fields = (
  112. 'ip' => '1',
  113. 'dhcp'=>'1',
  114. 'deleted'=>'1',
  115. 'mac'=>'1',
  116. );
  117. our %dns_fields = (
  118. 'ip' => '1',
  119. 'dns_name'=>'1',
  120. 'alias'=>'1',
  121. );
  122. #---------------------------------------------------------------------------------------------------------------
  123. sub StrToIp{
  124. return unpack('N',pack('C4',split(/\./,$_[0])));
  125. }
  126. #---------------------------------------------------------------------------------------------------------------
  127. sub IpToStr{
  128. my $nIP = shift;
  129. my $res = (($nIP>>24) & 255) .".". (($nIP>>16) & 255) .".". (($nIP>>8) & 255) .".". ($nIP & 255);
  130. return $res;
  131. }
  132. #---------------------------------------------------------------------------------------------------------------
  133. sub batch_db_sql {
  134. my $db=shift;
  135. my $batch_sql=shift;
  136. return if (!$db);
  137. $db->{AutoCommit} = 0;
  138. my $apply = 0;
  139. my $sth;
  140. my @msg = ();
  141. if (ref($batch_sql) eq 'ARRAY') { @msg = @$batch_sql; } else { @msg = split("\n",$batch_sql); }
  142. foreach my $sSQL (@msg) {
  143. next if (!$sSQL);
  144. $sth = $db->prepare($sSQL) or die "Unable to prepare $sSQL" . $db->errstr;
  145. $sth->execute() or die "Unable to prepare $sSQL" . $db->errstr;
  146. $apply = 1;
  147. }
  148. if ($apply) { $sth->finish(); }
  149. $db->{AutoCommit} = 1;
  150. }
  151. #---------------------------------------------------------------------------------------------------------------
  152. sub batch_db_sql_cached {
  153. my $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 0, AutoCommit => 0 });
  154. if ( !defined $db ) { die "Cannot connect to $config_ref{DBTYPE} server: $DBI::errstr\n"; }
  155. if ($config_ref{DBTYPE} eq 'mysql') {
  156. $db->do('SET NAMES utf8mb4');
  157. $db->{'mysql_enable_utf8'} = 1;
  158. $db->{'mysql_auto_reconnect'} = 1;
  159. }
  160. my $table= shift;
  161. my $batch_sql=shift;
  162. return if (!$db);
  163. my @msg = ();
  164. if (ref($batch_sql) eq 'ARRAY') { @msg = @$batch_sql; } else { @msg = split("\n",$batch_sql); }
  165. my $sth = $db->prepare_cached($table) or die "Unable to prepare:" . $db->errstr;
  166. foreach my $sSQL (@msg) {
  167. next if (!$sSQL);
  168. $sth->execute(@$sSQL) or die "Unable to execute:" . $db->errstr;
  169. }
  170. $db->commit();
  171. $db->disconnect();
  172. }
  173. #---------------------------------------------------------------------------------------------------------------
  174. sub batch_db_sql_csv {
  175. my $db;
  176. if ($config_ref{DBTYPE} eq 'mysql') {
  177. $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 1, mysql_local_infile=> 1 });
  178. } else {
  179. $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 1 });
  180. }
  181. if ( !defined $db ) { die "Cannot connect to $config_ref{DBTYPE} server: $DBI::errstr\n"; }
  182. return if (!$db);
  183. if ($config_ref{DBTYPE} eq 'mysql') {
  184. $db->do('SET NAMES utf8mb4');
  185. $db->{'mysql_enable_utf8'} = 1;
  186. $db->{'mysql_auto_reconnect'} = 1;
  187. }
  188. my $table= shift;
  189. my $data = shift;
  190. my $fh = File::Temp->new(UNLINK=>1);
  191. my $fname = $fh->filename;
  192. binmode($fh,':utf8');
  193. foreach my $row (@$data) {
  194. next if (!$row);
  195. my @tmp = @$row;
  196. my $values = 'NULL';
  197. for (my $i = 0; $i <@tmp ; $i++) {
  198. $values.=',"'.$tmp[$i].'"';
  199. }
  200. $values =~s/,$//;
  201. print $fh $values."\r\n";
  202. }
  203. close $fh;
  204. my $query = qq{ LOAD DATA LOCAL INFILE '$fname' INTO TABLE $table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n'; };
  205. $db->do($query);
  206. $db->disconnect;
  207. File::Temp::cleanup();
  208. }
  209. #---------------------------------------------------------------------------------------------------------------
  210. sub do_sql {
  211. my $db=shift;
  212. my $sql=shift;
  213. return if (!$db);
  214. return if (!$sql);
  215. if ($sql!~/^select /i) { log_debug($sql); }
  216. my $sql_prep = $db->prepare($sql) or die "Unable to prepare $sql: " . $db->errstr;
  217. my $sql_ref;
  218. my $rv = $sql_prep->execute() or die "Unable to execute $sql: " . $db->errstr;
  219. if ($sql=~/^insert/i) {
  220. if ($config_ref{DBTYPE} eq 'mysql') {
  221. $sql_ref = $sql_prep->{mysql_insertid};
  222. } else {
  223. ($sql_ref) = $db->selectrow_array("SELECT lastval()");
  224. }
  225. }
  226. if ($sql=~/^select /i) { $sql_ref = $sql_prep->fetchall_arrayref() or die "Unable to select $sql: " . $db->errstr; };
  227. $sql_prep->finish();
  228. return $sql_ref;
  229. }
  230. #---------------------------------------------------------------------------------------------------------------
  231. sub get_first_line {
  232. my $msg = shift;
  233. if (!$msg) { return; }
  234. if ($msg=~ /(.*)(\n|\<br\>)/) {
  235. $msg = $1 if ($1);
  236. chomp($msg);
  237. }
  238. return $msg;
  239. }
  240. #---------------------------------------------------------------------------------------------------------------
  241. sub write_db_log {
  242. my $db=shift;
  243. my $msg=shift;
  244. my $level = shift || $L_VERBOSE;
  245. my $auth_id = shift || 0;
  246. return if (!$db);
  247. return if (!$msg);
  248. $msg=~s/[\'\"]//g;
  249. my $db_log = 0;
  250. if (!$db) { $db_log = 0; }
  251. if ($level eq $L_ERROR and $log_level >= $L_ERROR) { log_error($msg); $db_log = 1; }
  252. if ($level eq $L_WARNING and $log_level >= $L_WARNING) { log_warning($msg); $db_log = 1; }
  253. if ($level eq $L_INFO and $log_level >= $L_INFO) { log_info($msg); $db_log = 1; }
  254. if ($level eq $L_VERBOSE and $log_level >= $L_VERBOSE) { log_verbose($msg); $db_log = 1; }
  255. if ($level eq $L_DEBUG and $log_level >= $L_DEBUG) { log_debug($msg); $db_log = 1; }
  256. if ($db_log) {
  257. my $history_sql="INSERT INTO worklog(customer,message,level,auth_id) VALUES(".$db->quote($MY_NAME).",".$db->quote($msg).",$level,$auth_id)";
  258. my $history_rf=$db->prepare($history_sql) or die "Unable to prepare $history_sql:" . $db->errstr;
  259. $history_rf->execute() or die "Unable to execute $history_sql: " . $db->errstr;
  260. }
  261. }
  262. #---------------------------------------------------------------------------------------------------------------
  263. sub db_log_debug {
  264. my $db = shift;
  265. my $msg = shift;
  266. my $id = shift;
  267. if ($debug) { write_db_log($db,$msg,$L_DEBUG,$id); }
  268. }
  269. #---------------------------------------------------------------------------------------------------------------
  270. sub db_log_error {
  271. my $db = shift;
  272. my $msg = shift;
  273. if ($log_level >= $L_ERROR) {
  274. sendEmail("ERROR! ".get_first_line($msg),$msg,1);
  275. write_db_log($db,$msg,$L_ERROR);
  276. }
  277. }
  278. #---------------------------------------------------------------------------------------------------------------
  279. sub db_log_info {
  280. my $db = shift;
  281. my $msg = shift;
  282. my $id = shift;
  283. if ($log_level >= $L_INFO) { write_db_log($db,$msg,$L_INFO,$id); }
  284. }
  285. #---------------------------------------------------------------------------------------------------------------
  286. sub db_log_verbose {
  287. my $db = shift;
  288. my $msg = shift;
  289. my $id = shift;
  290. if ($log_level >= $L_VERBOSE) { write_db_log($db,$msg,$L_VERBOSE,$id); }
  291. }
  292. #---------------------------------------------------------------------------------------------------------------
  293. sub db_log_warning {
  294. my $db = shift;
  295. my $msg = shift;
  296. my $id = shift;
  297. if ($log_level >= $L_WARNING) {
  298. sendEmail("WARN! ".get_first_line($msg),$msg,1);
  299. write_db_log($db,$msg,$L_WARNING,$id);
  300. }
  301. }
  302. #---------------------------------------------------------------------------------------------------------------
  303. sub init_db {
  304. # Create new database handle. If we can't connect, die()
  305. my $db = DBI->connect("dbi:$config_ref{DBTYPE}:database=$DBNAME;host=$DBHOST","$DBUSER","$DBPASS", { RaiseError => 0, AutoCommit => 1 });
  306. if ( !defined $db ) { die "Cannot connect to mySQL server: $DBI::errstr\n"; }
  307. if ($config_ref{DBTYPE} eq 'mysql') {
  308. $db->do('SET NAMES utf8mb4');
  309. $db->{'mysql_enable_utf8'} = 1;
  310. $db->{'mysql_auto_reconnect'} = 1;
  311. }
  312. return $db;
  313. }
  314. #---------------------------------------------------------------------------------------------------------------
  315. sub get_count_records {
  316. my $db = shift;
  317. my $table = shift;
  318. my $filter = shift;
  319. my $result = 0;
  320. return $result if (!$db);
  321. return $result if (!$table);
  322. my $sSQL='SELECT COUNT(*) as rec_cnt FROM '.$table;
  323. if ($filter) { $sSQL=$sSQL." WHERE ".$filter; }
  324. my $record = get_record_sql($db,$sSQL);
  325. if ($record->{rec_cnt}) { $result = $record->{rec_cnt}; }
  326. return $result;
  327. }
  328. #---------------------------------------------------------------------------------------------------------------
  329. sub get_id_record {
  330. my $db = shift;
  331. my $table = shift;
  332. my $filter = shift;
  333. my $result = 0;
  334. return $result if (!$db);
  335. return $result if (!$table);
  336. my $record = get_record_sql($db,"SELECT id FROM $table WHERE $filter");
  337. if ($record->{id}) { $result = $record->{id}; }
  338. return $result;
  339. }
  340. #---------------------------------------------------------------------------------------------------------------
  341. sub get_records_sql {
  342. my $db = shift;
  343. my $table = shift;
  344. my @result;
  345. return @result if (!$db);
  346. return @result if (!$table);
  347. my $list = $db->prepare( $table ) or die "Unable to prepare $table:" . $db->errstr;
  348. $list->execute() or die "Unable to execute $table: " . $db->errstr;
  349. while(my $row_ref = $list->fetchrow_hashref()) { push(@result,$row_ref); }
  350. $list->finish();
  351. return @result;
  352. }
  353. #---------------------------------------------------------------------------------------------------------------
  354. sub get_record_sql {
  355. my $db = shift;
  356. my $tsql = shift;
  357. my @result;
  358. return @result if (!$db);
  359. return @result if (!$tsql);
  360. $tsql.=' LIMIT 1';
  361. my $row_ref;
  362. eval {
  363. my $list = $db->prepare($tsql) or die "Unable to prepare $tsql: " . $db->errstr;
  364. $list->execute() or die "Unable to execute $tsql: " . $db->errstr;
  365. $row_ref = $list->fetchrow_hashref();
  366. $list->finish();
  367. };
  368. if ($@) {
  369. log_error("Error apply sql: $tsql err:".$@);
  370. die "Error apply sql: $tsql";
  371. }
  372. return $row_ref;
  373. }
  374. #---------------------------------------------------------------------------------------------------------------
  375. sub unbind_ports {
  376. my $db = shift;
  377. my $device_id = shift;
  378. return if (!$db);
  379. return if (!$device_id);
  380. my @target = get_records_sql($db, "SELECT U.target_port_id,U.id FROM device_ports U WHERE U.device_id=".$device_id);
  381. foreach my $row (@target) {
  382. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE target_port_id=".$row->{id});
  383. do_sql($db, "UPDATE device_ports SET target_port_id=0 WHERE id=".$row->{id});
  384. }
  385. }
  386. #---------------------------------------------------------------------------------------------------------------
  387. sub get_diff_rec {
  388. my $db = shift;
  389. my $table = shift;
  390. my $value = shift;
  391. my $filter = shift;
  392. return if (!$db);
  393. return if (!$table);
  394. return if (!$filter);
  395. my $old_value = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  396. my $result='';
  397. foreach my $field (keys %$value) {
  398. if (!$value->{$field}) { $value->{$field}=''; }
  399. if (!$old_value->{$field}) { $old_value->{$field}=''; }
  400. if ($value->{$field}!~/^$old_value->{$field}$/) { $result = $result." $field => $value->{$field} (old: $old_value->{$field}),"; }
  401. }
  402. $result=~s/,$//;
  403. return $result;
  404. }
  405. #---------------------------------------------------------------------------------------------------------------
  406. sub get_dns_name {
  407. my $db = shift;
  408. my $id = shift;
  409. my $auth_record = get_record_sql($db,"SELECT dns_name FROM User_auth WHERE deleted=0 AND id=".$id);
  410. if ($auth_record and $auth_record->{'dns_name'}) { return $auth_record->{'dns_name'}; }
  411. return;
  412. }
  413. #---------------------------------------------------------------------------------------------------------------
  414. sub update_record {
  415. my $db = shift;
  416. my $table = shift;
  417. my $record = shift;
  418. my $filter = shift;
  419. return if (!$db);
  420. return if (!$table);
  421. return if (!$filter);
  422. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  423. my $diff='';
  424. my $change_str='';
  425. my $found_changed=0;
  426. my $rec_id = 0;
  427. my $dns_changed = 0;
  428. $rec_id = $old_record->{'id'} if ($old_record->{'id'});
  429. if ($table eq "User_auth") {
  430. #disable update field 'created_by'
  431. if ($old_record->{'created_by'} and exists ($record->{'created_by'})) { delete $record->{'created_by'}; }
  432. foreach my $field (keys %$record) {
  433. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  434. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  435. if (exists $dns_fields{$field}) { $dns_changed=1; }
  436. }
  437. }
  438. foreach my $field (keys %$record) {
  439. if (!defined $record->{$field}) { $record->{$field}=''; }
  440. if (!defined $old_record->{$field}) { $old_record->{$field}=''; }
  441. my $old_value = quotemeta($old_record->{$field});
  442. my $new_value = $record->{$field};
  443. $new_value=~s/\'//g;
  444. $new_value=~s/\"//g;
  445. if ($new_value!~/^$old_value$/) {
  446. $diff = $diff." $field => $record->{$field} (old: $old_record->{$field}),";
  447. $change_str = $change_str." `$field`=".$db->quote($record->{$field}).",";
  448. $found_changed++;
  449. }
  450. }
  451. if ($found_changed) {
  452. $change_str=~s/\,$//;
  453. $diff=~s/\,$//;
  454. if ($table eq 'User_auth') {
  455. $change_str .= ", `changed_time`='".GetNowTime()."'";
  456. if ($dns_changed) {
  457. my $del_dns;
  458. if ($old_record->{'dns_name'} and $old_record->{'ip'}) {
  459. $del_dns->{'name_type'}='A';
  460. $del_dns->{'name'}=$old_record->{'dns_name'};
  461. $del_dns->{'value'}=$old_record->{'ip'};
  462. $del_dns->{'type'}='del';
  463. if ($rec_id) { $del_dns->{'auth_id'}=$rec_id; }
  464. insert_record($db,'dns_queue',$del_dns);
  465. }
  466. my $new_dns;
  467. my $dns_rec_ip = $old_record->{ip};
  468. my $dns_rec_name = $old_record->{dns_name};
  469. if ($record->{'dns_name'}) { $dns_rec_name = $record->{'dns_name'}; }
  470. if ($record->{'ip'}) { $dns_rec_ip = $record->{'ip'}; }
  471. if ($dns_rec_name and $dns_rec_ip) {
  472. $new_dns->{'name_type'}='A';
  473. $new_dns->{'name'}=$dns_rec_name;
  474. $new_dns->{'value'}=$dns_rec_ip;
  475. $new_dns->{'type'}='add';
  476. if ($rec_id) { $new_dns->{'auth_id'}=$rec_id; }
  477. insert_record($db,'dns_queue',$new_dns);
  478. }
  479. }
  480. }
  481. if ($table eq 'User_auth_alias') {
  482. if ($dns_changed) {
  483. my $del_dns;
  484. if ($old_record->{'alias'}) {
  485. $del_dns->{'name_type'}='CNAME';
  486. $del_dns->{'name'}=$old_record->{'alias'};
  487. $del_dns->{'type'}='del';
  488. $del_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  489. $del_dns->{'auth_id'}=$old_record->{auth_id};
  490. insert_record($db,'dns_queue',$del_dns);
  491. }
  492. my $new_dns;
  493. my $dns_rec_name = $old_record->{alias};
  494. if ($record->{'alias'}) { $dns_rec_name = $record->{'alias'}; }
  495. if ($dns_rec_name) {
  496. $new_dns->{'name_type'}='CNAME';
  497. $new_dns->{'name'}=$dns_rec_name;
  498. $new_dns->{'type'}='add';
  499. $new_dns->{'value'}=get_dns_name($db,$old_record->{auth_id});
  500. $new_dns->{'auth_id'}=$rec_id;
  501. insert_record($db,'dns_queue',$new_dns);
  502. }
  503. }
  504. }
  505. my $sSQL = "UPDATE $table SET $change_str WHERE $filter";
  506. db_log_debug($db,'Change table '.$table.' for '.$filter.' set: '.$diff, $rec_id);
  507. do_sql($db,$sSQL);
  508. } else {
  509. db_log_debug($db,'Nothing change. Skip update.');
  510. }
  511. return 1;
  512. }
  513. #---------------------------------------------------------------------------------------------------------------
  514. sub insert_record {
  515. my $db = shift;
  516. my $table = shift;
  517. my $record = shift;
  518. return if (!$db);
  519. return if (!$table);
  520. my $change_str='';
  521. my $fields='';
  522. my $values='';
  523. my $new_str='';
  524. my $dns_changed = 0;
  525. if ($table eq "User_auth") {
  526. foreach my $field (keys %$record) {
  527. if (exists $acl_fields{$field}) { $record->{changed}="1"; }
  528. if (exists $dhcp_fields{$field}) { $record->{dhcp_changed}="1"; }
  529. if (exists $dns_fields{$field}) { $dns_changed=1; }
  530. }
  531. }
  532. foreach my $field (keys %$record) {
  533. if (!defined $record->{$field}) { $record->{$field}=''; }
  534. my $new_value = $record->{$field};
  535. $new_value=~s/\'//g;
  536. $new_value=~s/\"//g;
  537. $record->{$field} = $new_value;
  538. $fields = $fields."`$field`,";
  539. $values = $values." ".$db->quote($record->{$field}).",";
  540. $new_str = $new_str." $field => $record->{$field},";
  541. }
  542. $fields=~s/,$//;
  543. $values=~s/,$//;
  544. $new_str=~s/,$//;
  545. my $sSQL = "INSERT INTO $table($fields) VALUES($values)";
  546. my $result = do_sql($db,$sSQL);
  547. if ($result) {
  548. $new_str='id: '.$result.' '.$new_str;
  549. if ($table eq 'User_auth_alias' and $dns_changed) {
  550. if ($record->{'alias'}) {
  551. my $add_dns;
  552. $add_dns->{'name_type'}='CNAME';
  553. $add_dns->{'name'}=$record->{'alias'};
  554. $add_dns->{'value'}=get_dns_name($db,$record->{'auth_id'});
  555. $add_dns->{'type'}='add';
  556. $add_dns->{'auth_id'}=$record->{'auth_id'};
  557. insert_record($db,'dns_queue',$add_dns);
  558. }
  559. }
  560. if ($table eq 'User_auth' and $dns_changed) {
  561. if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed) {
  562. my $add_dns;
  563. $add_dns->{'name_type'}='A';
  564. $add_dns->{'name'}=$record->{'dns_name'};
  565. $add_dns->{'value'}=$record->{'ip'};
  566. $add_dns->{'type'}='add';
  567. $add_dns->{'auth_id'}=$result;
  568. insert_record($db,'dns_queue',$add_dns);
  569. }
  570. }
  571. }
  572. db_log_debug($db,'Add record to table '.$table.' '.$new_str);
  573. return $result;
  574. }
  575. #---------------------------------------------------------------------------------------------------------------
  576. sub delete_record {
  577. my $db = shift;
  578. my $table = shift;
  579. my $filter = shift;
  580. return if (!$db);
  581. return if (!$table);
  582. return if (!$filter);
  583. my $old_record = get_record_sql($db,"SELECT * FROM $table WHERE $filter");
  584. my $diff='';
  585. foreach my $field (keys %$old_record) {
  586. if (!$old_record->{$field}) { $old_record->{$field}=''; }
  587. $diff = $diff." $field => $old_record->{$field},";
  588. }
  589. $diff=~s/,$//;
  590. db_log_debug($db,'Delete record from table '.$table.' value: '.$diff);
  591. #never delete user ip record!
  592. if ($table eq 'User_auth') {
  593. my $sSQL = "UPDATE User_auth SET changed=1, deleted=1, changed_time='".GetNowTime()."' WHERE ".$filter;
  594. do_sql($db,$sSQL);
  595. if ($old_record->{'dns_name'} and $old_record->{'ip'}) {
  596. my $del_dns;
  597. $del_dns->{'name_type'}='A';
  598. $del_dns->{'name'}=$old_record->{'dns_name'};
  599. $del_dns->{'value'}=$old_record->{'ip'};
  600. $del_dns->{'type'}='del';
  601. $del_dns->{'auth_id'}=$old_record->{'id'};
  602. insert_record($db,'dns_queue',$del_dns);
  603. }
  604. }
  605. if ($table eq 'User_list' and $old_record->{'permanent'}) { return; }
  606. if ($table eq 'User_auth_alias') {
  607. if ($old_record->{'alias'} and $old_record->{'auth_id'}) {
  608. my $del_dns;
  609. $del_dns->{'name_type'}='CNAME';
  610. $del_dns->{'name'}=$old_record->{'alias'};
  611. $del_dns->{'value'}=get_dns_name($db,$old_record->{'auth_id'});
  612. $del_dns->{'type'}='del';
  613. $del_dns->{'auth_id'}=$old_record->{'auth_id'};
  614. insert_record($db,'dns_queue',$del_dns);
  615. }
  616. }
  617. my $sSQL = "DELETE FROM ".$table." WHERE ".$filter;
  618. return do_sql($db,$sSQL);
  619. }
  620. #---------------------------------------------------------------------------------------------------------------
  621. sub delete_user_auth {
  622. my $db = shift;
  623. my $id = shift;
  624. #remove aliases
  625. my @t_User_auth_alias = get_records_sql($db,'SELECT * FROM User_auth_alias WHERE auth_id='.$id);
  626. if (@t_User_auth_alias and scalar @t_User_auth_alias) {
  627. foreach my $row ( @t_User_auth_alias) { delete_record($db,'User_auth_alias','id='.$row->{'id'}); }
  628. }
  629. #remove connections
  630. do_sql($db,'DELETE FROM connections WHERE auth_id='.$id);
  631. #remove user auth record
  632. my $changes = delete_record($db, "User_auth", "id=" . $id);
  633. return $changes;
  634. }
  635. #---------------------------------------------------------------------------------------------------------------
  636. sub delete_user {
  637. my $db = shift;
  638. my $id = shift;
  639. #remove user record
  640. my $changes = delete_record($db, "User_list", "id=" . $id);
  641. #if fail - exit
  642. if (!$changes) { return; }
  643. #remove auth records
  644. my @t_User_auth = get_records_sql($db,'SELECT * FROM User_auth WHERE user_id='.$id);
  645. if (@t_User_auth and scalar @t_User_auth) {
  646. foreach my $row ( @t_User_auth ) { delete_user_auth($db,$row->{'id'}); }
  647. }
  648. #remove device
  649. my $device = get_record_sql($db, "SELECT * FROM devices WHERE user_id=".$id);
  650. if ($device) { delete_device($db,$device->{'id'}); }
  651. #remove auth assign rules
  652. do_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  653. return $changes;
  654. }
  655. #---------------------------------------------------------------------------------------------------------------
  656. sub delete_device {
  657. my $db = shift;
  658. my $id = shift;
  659. #remove user record
  660. my $changes = delete_record($db, "devices", "id=" . $id);
  661. #if fail - exit
  662. if (!$changes) { return; }
  663. unbind_ports($db, $id);
  664. do_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  665. do_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  666. do_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  667. do_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  668. do_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  669. return $changes;
  670. }
  671. #---------------------------------------------------------------------------------------------------------------
  672. sub GetNowTime {
  673. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  674. $month += 1;
  675. $year += 1900;
  676. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  677. return $now_str;
  678. }
  679. #---------------------------------------------------------------------------------------------------------------
  680. sub is_hotspot {
  681. my $db = shift;
  682. my $ip = shift;
  683. my $users = new Net::Patricia;
  684. #check hotspot
  685. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  686. foreach my $row (@ip_rules) { $users->add_string($row->{subnet}); }
  687. if ($users->match_string($ip)) { return 1; }
  688. return 0;
  689. }
  690. #---------------------------------------------------------------------------------------------------------------
  691. sub get_new_user_id {
  692. my $db = shift;
  693. my $ip = shift;
  694. my $mac = shift;
  695. my $hostname = shift;
  696. my $result;
  697. #check user rules
  698. $mac = mac_simplify($mac);
  699. $result->{ip} = $ip;
  700. $result->{mac} = mac_splitted($mac);
  701. $result->{dhcp_hostname} = $hostname;
  702. $result->{ou_id}=undef;
  703. $result->{user_id}=undef;
  704. my $hotspot_users = new Net::Patricia;
  705. #check hotspot
  706. my @hotspot_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  707. foreach my $row (@hotspot_rules) { $hotspot_users->add_string($row->{subnet},$default_hotspot_ou_id); }
  708. if ($hotspot_users->match_string($ip)) { $result->{ou_id}=$hotspot_users->match_string($ip); return $result; }
  709. #check ip
  710. if (defined $ip and $ip) {
  711. my $users = new Net::Patricia;
  712. #check ip rules
  713. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL');
  714. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{user_id}); }; }
  715. if ($users->match_string($ip)) { $result->{user_id}=$users->match_string($ip); return $result; }
  716. }
  717. #check mac
  718. if (defined $mac and $mac) {
  719. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  720. foreach my $user (@user_rules) {
  721. my $rule = mac_simplify($user->{rule});
  722. if ($mac=~/$rule/i) { $result->{user_id}=$user->{user_id}; return $result; }
  723. }
  724. }
  725. #check hostname
  726. if (defined $hostname and $hostname) {
  727. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  728. foreach my $user (@user_rules) {
  729. if ($hostname=~/$user->{rule}/i) { $result->{user_id}=$user->{user_id}; return $result; }
  730. }
  731. }
  732. #check ou rules
  733. #check ip
  734. if (defined $ip and $ip) {
  735. my $users = new Net::Patricia;
  736. #check ip rules
  737. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL');
  738. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{ou_id}); }; }
  739. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); return $result; }
  740. }
  741. #check mac
  742. if (defined $mac and $mac) {
  743. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  744. foreach my $user (@user_rules) {
  745. my $rule = mac_simplify($user->{rule});
  746. if ($mac=~/$rule/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  747. }
  748. }
  749. #check hostname
  750. if (defined $hostname and $hostname) {
  751. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  752. foreach my $user (@user_rules) {
  753. if ($hostname=~/$user->{rule}/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  754. }
  755. }
  756. if (!$result->{ou_id}) { $result->{ou_id}=$default_user_ou_id; }
  757. return $result;
  758. }
  759. #---------------------------------------------------------------------------------------------------------------
  760. sub set_changed {
  761. my $db = shift;
  762. my $id = shift;
  763. return if (!$db or !$id);
  764. my $update_record;
  765. $update_record->{changed}=1;
  766. update_record($db,'User_auth',$update_record,"id=$id");
  767. }
  768. #---------------------------------------------------------------------------------------------------------------
  769. sub update_dns_record {
  770. my $hdb = shift;
  771. my $auth_id = shift;
  772. return if (!$config_ref{enable_dns_updates});
  773. #get domain
  774. my $ad_zone = get_option($hdb,33);
  775. #get dns server
  776. my $ad_dns = get_option($hdb,3);
  777. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $config_ref{enable_dns_updates});
  778. log_debug("Auth id: ".$auth_id);
  779. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  780. log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
  781. my @dns_queue = get_records_sql($hdb,"SELECT * FROM dns_queue WHERE auth_id=".$auth_id." ORDER BY id ASC");
  782. if (!@dns_queue or !scalar @dns_queue) { return; }
  783. foreach my $dns_cmd (@dns_queue) {
  784. my $fqdn = '';
  785. my $fqdn_ip = '';
  786. my $fqdn_parent = '';
  787. my $static_exists = 0;
  788. my $static_ref = '';
  789. my $static_ok = 0;
  790. eval {
  791. if ($dns_cmd->{name_type}=~/^cname$/i) {
  792. $fqdn=lc($dns_cmd->{name});
  793. $fqdn=~s/\.$ad_zone$//i;
  794. $fqdn=~s/\.$//;
  795. if ($dns_cmd->{value}) {
  796. $fqdn_parent=lc($dns_cmd->{value});
  797. $fqdn_parent=~s/\.$ad_zone$//i;
  798. $fqdn_parent=~s/\.$//;
  799. }
  800. #skip update unknown domain
  801. if ($fqdn =~/\./ or $fqdn_parent =~/\./) { next; }
  802. $fqdn = $fqdn.".".$ad_zone;
  803. $fqdn_parent = $fqdn_parent.".".$ad_zone;
  804. #remove cname
  805. if ($dns_cmd->{type} eq 'del') {
  806. delete_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  807. }
  808. #create cname
  809. if ($dns_cmd->{type} eq 'add') {
  810. create_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  811. }
  812. }
  813. if ($dns_cmd->{name_type}=~/^a$/i) {
  814. $fqdn=lc($dns_cmd->{name});
  815. $fqdn=~s/\.$ad_zone$//i;
  816. $fqdn=~s/\.$//;
  817. if (!$dns_cmd->{value}) { next; }
  818. $fqdn_ip=lc($dns_cmd->{value});
  819. #skip update unknown domain
  820. if ($fqdn =~/\./) { next; }
  821. $fqdn = $fqdn.".".$ad_zone;
  822. #dns update disabled?
  823. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  824. if (!$maybe_update_dns) {
  825. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  826. next;
  827. }
  828. #get aliases
  829. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_id);
  830. #remove A & PTR
  831. if ($dns_cmd->{type} eq 'del') {
  832. #remove aliases
  833. if (@aliases and scalar @aliases) {
  834. foreach my $alias (@aliases) {
  835. delete_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  836. delete_dns_hostname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  837. }
  838. }
  839. #remove main record
  840. delete_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  841. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  842. }
  843. #create A & PTR
  844. if ($dns_cmd->{type} eq 'add') {
  845. my @dns_record=ResolveNames($fqdn,$dns_server);
  846. $static_exists = (scalar @dns_record>0);
  847. if ($static_exists) {
  848. $static_ref = join(' ',@dns_record);
  849. foreach my $dns_a (@dns_record) {
  850. if ($dns_a=~/^$fqdn_ip$/) { $static_ok = 1; }
  851. }
  852. db_log_debug($hdb,"Dns record for static record $fqdn: $static_ref");
  853. }
  854. #skip update if already exists
  855. if ($static_ok) {
  856. db_log_debug($hdb,"Static record for $fqdn [$static_ok] correct.");
  857. next;
  858. }
  859. #create record
  860. create_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  861. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  862. #create aliases
  863. if (@aliases and scalar @aliases) {
  864. foreach my $alias (@aliases) {
  865. create_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  866. }
  867. }
  868. }
  869. }
  870. };
  871. if ($@) { log_error("Error dns commands: $@"); }
  872. }
  873. }
  874. #---------------------------------------------------------------------------------------------------------------
  875. sub is_ad_computer {
  876. my $hdb = shift;
  877. my $computer_name = shift;
  878. if (!$computer_name or $computer_name =~/UNDEFINED/i) { return 0; }
  879. my $ad_check = get_option($hdb,73);
  880. if (!$ad_check) { return 1; }
  881. my $ad_zone = get_option($hdb,33);
  882. if ($computer_name =~/\./) {
  883. if ($computer_name!~/\.$ad_zone$/i) {
  884. db_log_verbose($hdb,"The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  885. return 0;
  886. }
  887. }
  888. if ($computer_name =~/^(.+)\./) {
  889. $computer_name = $1;
  890. }
  891. my $ad_computer_name = trim($computer_name).'$';
  892. my $name_in_cache = get_record_sql($hdb,"SELECT * FROM ad_comp_cache WHERE name='".$computer_name."'");
  893. if ($name_in_cache) { return 1; }
  894. my %name_found=do_exec_ref('/usr/bin/getent passwd '.$ad_computer_name);
  895. if (!$name_found{output} or $name_found{status} ne 0) {
  896. db_log_verbose($hdb,"The computer ".uc($ad_computer_name)." was not found in the domain $ad_zone. Skip update.");
  897. return 0;
  898. }
  899. do_sql($hdb,"INSERT INTO ad_comp_cache(name) VALUES('".$computer_name."') ON DUPLICATE KEY UPDATE name='".$computer_name."';");
  900. return 1;
  901. }
  902. #---------------------------------------------------------------------------------------------------------------
  903. sub update_dns_record_by_dhcp {
  904. my $hdb = shift;
  905. my $dhcp_record = shift;
  906. my $auth_record = shift;
  907. return if (!$config_ref{enable_dns_updates});
  908. my $ad_zone = get_option($hdb,33);
  909. my $ad_dns = get_option($hdb,3);
  910. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  911. my $subnets_dhcp = get_subnets_ref($hdb);
  912. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  913. log_debug("Dhcp record: ".Dumper($dhcp_record));
  914. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  915. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  916. 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);
  917. my $maybe_update_dns=(is_ad_computer($hdb,$dhcp_record->{hostname_utf8}) and ($dhcp_record->{type}=~/add/i or $dhcp_record->{type}=~/old/i) and $enable_ad_dns_update and $subnets_dhcp->{$dhcp_record->{network}->{subnet}}->{dhcp_update_hostname});
  918. if (!$maybe_update_dns) {
  919. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  920. return 0;
  921. }
  922. log_debug("DNS update enabled.");
  923. #update dns block
  924. my $fqdn_static;
  925. if ($auth_record->{dns_name}) {
  926. $fqdn_static=lc($auth_record->{dns_name});
  927. if ($fqdn_static!~/\.$ad_zone$/i) {
  928. $fqdn_static=~s/\.$//;
  929. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  930. }
  931. }
  932. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  933. if ($fqdn!~/\.$ad_zone$/i) {
  934. $fqdn=~s/\.$//;
  935. $fqdn=lc($fqdn.'.'.$ad_zone);
  936. }
  937. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  938. #check exists static dns name
  939. my $static_exists = 0;
  940. my $dynamic_exists = 0;
  941. my $static_ok = 0;
  942. my $dynamic_ok = 0;
  943. my $static_ref;
  944. my $dynamic_ref;
  945. if ($fqdn_static ne '') {
  946. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  947. $static_exists = (scalar @dns_record>0);
  948. if ($static_exists) {
  949. $static_ref = join(' ',@dns_record);
  950. foreach my $dns_a (@dns_record) {
  951. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  952. }
  953. }
  954. } else { $static_ok = 1; }
  955. if ($fqdn ne '') {
  956. my @dns_record=ResolveNames($fqdn,$dns_server);
  957. $dynamic_exists = (scalar @dns_record>0);
  958. if ($dynamic_exists) {
  959. $dynamic_ref = join(' ',@dns_record);
  960. foreach my $dns_a (@dns_record) {
  961. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  962. }
  963. }
  964. }
  965. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  966. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  967. if ($fqdn_static ne '') {
  968. if (!$static_ok) {
  969. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  970. if (!$static_exists) {
  971. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  972. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  973. }
  974. } else {
  975. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  976. }
  977. }
  978. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  979. if ($fqdn ne '' and !$dynamic_ok) {
  980. #log event without email alert
  981. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  982. #check exists hostname
  983. my $another_hostname_exists = 0;
  984. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  985. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  986. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  987. }
  988. #check exists another records with some static hostname
  989. my $filter_sql = 'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  990. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  991. my $name_record = get_record_sql($hdb,$filter_sql);
  992. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  993. $another_hostname_exists = 1;
  994. }
  995. if (!$another_hostname_exists) {
  996. if ($fqdn_static and $fqdn_static ne '') {
  997. if ($fqdn_static!~/$fqdn/) {
  998. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  999. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1000. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1001. }
  1002. } else {
  1003. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  1004. #get and remove aliases
  1005. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_record->{id});
  1006. if (@aliases and scalar @aliases) {
  1007. foreach my $alias (@aliases) {
  1008. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1009. }
  1010. }
  1011. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  1012. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1013. if (@aliases and scalar @aliases) {
  1014. foreach my $alias (@aliases) {
  1015. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1016. }
  1017. }
  1018. }
  1019. } else {
  1020. 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.");
  1021. }
  1022. }
  1023. #end update dns block
  1024. }
  1025. #------------------------------------------------------------------------------------------------------------
  1026. sub apply_device_lock {
  1027. my $db = shift;
  1028. my $device_id = shift;
  1029. my $iteration = shift || 0;
  1030. $iteration++;
  1031. if ($iteration>2) { return 0; }
  1032. my $dev = get_record_sql($db,"SELECT `discovery_locked`, `locked_timestamp`, UNIX_TIMESTAMP(`locked_timestamp`) as u_locked_timestamp FROM devices WHERE id=".$device_id);
  1033. if (!$dev) { return 0; }
  1034. if (!$dev->{'discovery_locked'}) { return set_lock_discovery($db,$device_id); }
  1035. #if timestamp undefined, set and return
  1036. if (!$dev->{'locked_timestamp'}) { return set_lock_discovery($db,$device_id); }
  1037. #wait for discovery
  1038. my $wait_time = $dev->{'locked_timestamp'} + 30 - time();
  1039. if ($wait_time<0) { return set_lock_discovery($db,$device_id); }
  1040. sleep($wait_time);
  1041. return apply_device_lock($db,$device_id,$iteration);
  1042. }
  1043. #------------------------------------------------------------------------------------------------------------
  1044. sub set_lock_discovery {
  1045. my $db = shift;
  1046. my $device_id = shift;
  1047. my $new;
  1048. $new->{'discovery_locked'} = 1;
  1049. $new->{'locked_timestamp'} = GetNowTime();
  1050. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1051. return 0;
  1052. }
  1053. #------------------------------------------------------------------------------------------------------------
  1054. sub unset_lock_discovery {
  1055. my $db = shift;
  1056. my $device_id = shift;
  1057. my $new;
  1058. $new->{'discovery_locked'} = 0;
  1059. $new->{'locked_timestamp'} = GetNowTime();
  1060. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1061. return 0;
  1062. }
  1063. #------------------------------------------------------------------------------------------------------------
  1064. sub create_dns_cname {
  1065. my $fqdn = shift;
  1066. my $alias = shift;
  1067. my $zone = shift;
  1068. my $server = shift;
  1069. my $db = shift;
  1070. #skip update domain controllers
  1071. if (!$db) {
  1072. log_info("DNS-UPDATE: Zone $zone Server: $server CNAME: $alias for $fqdn");
  1073. } else {
  1074. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1075. }
  1076. my $ad_zone = get_option($db,33);
  1077. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1078. my @add_dns;
  1079. if ($config_ref{dns_server_type}=~/windows/i) {
  1080. push(@add_dns,"gsstsig");
  1081. push(@add_dns,"server $server");
  1082. push(@add_dns,"zone $zone");
  1083. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1084. push(@add_dns,"send");
  1085. write_to_file($nsupdate_file,\@add_dns);
  1086. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1087. }
  1088. if ($config_ref{dns_server_type}=~/bind/i) {
  1089. push(@add_dns,"server $server");
  1090. push(@add_dns,"zone $zone");
  1091. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1092. push(@add_dns,"send");
  1093. write_to_file($nsupdate_file,\@add_dns);
  1094. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1095. }
  1096. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1097. }
  1098. #---------------------------------------------------------------------------------------------------------------
  1099. sub delete_dns_cname {
  1100. my $fqdn = shift;
  1101. my $alias = shift;
  1102. my $zone = shift;
  1103. my $server = shift;
  1104. my $db = shift;
  1105. if (!$db) {
  1106. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1107. } else {
  1108. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  1109. }
  1110. my $ad_zone = get_option($db,33);
  1111. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1112. my @add_dns;
  1113. if ($config_ref{dns_server_type}=~/windows/i) {
  1114. push(@add_dns,"gsstsig");
  1115. push(@add_dns,"server $server");
  1116. push(@add_dns,"zone $zone");
  1117. push(@add_dns,"update delete $alias cname ");
  1118. push(@add_dns,"send");
  1119. write_to_file($nsupdate_file,\@add_dns);
  1120. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1121. }
  1122. if ($config_ref{dns_server_type}=~/bind/i) {
  1123. push(@add_dns,"server $server");
  1124. push(@add_dns,"zone $zone");
  1125. push(@add_dns,"update delete $alias cname");
  1126. push(@add_dns,"send");
  1127. write_to_file($nsupdate_file,\@add_dns);
  1128. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1129. }
  1130. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1131. }
  1132. #------------------------------------------------------------------------------------------------------------
  1133. sub create_dns_hostname {
  1134. my $fqdn = shift;
  1135. my $ip = shift;
  1136. my $zone = shift;
  1137. my $server = shift;
  1138. my $db = shift;
  1139. #skip update domain controllers
  1140. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1141. if (!$db) {
  1142. log_info("DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  1143. } else {
  1144. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn IP: $ip");
  1145. }
  1146. my $ad_zone = get_option($db,33);
  1147. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1148. my @add_dns;
  1149. if ($config_ref{dns_server_type}=~/windows/i) {
  1150. push(@add_dns,"gsstsig");
  1151. push(@add_dns,"server $server");
  1152. push(@add_dns,"zone $zone");
  1153. push(@add_dns,"update add $fqdn 3600 A $ip");
  1154. push(@add_dns,"send");
  1155. write_to_file($nsupdate_file,\@add_dns);
  1156. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1157. }
  1158. if ($config_ref{dns_server_type}=~/bind/i) {
  1159. push(@add_dns,"server $server");
  1160. push(@add_dns,"zone $zone");
  1161. push(@add_dns,"update add $fqdn 3600 A $ip");
  1162. push(@add_dns,"send");
  1163. write_to_file($nsupdate_file,\@add_dns);
  1164. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1165. }
  1166. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1167. }
  1168. #---------------------------------------------------------------------------------------------------------------
  1169. sub delete_dns_hostname {
  1170. my $fqdn = shift;
  1171. my $ip = shift;
  1172. my $zone = shift;
  1173. my $server = shift;
  1174. my $db = shift;
  1175. #skip update domain controllers
  1176. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1177. if (!$db) {
  1178. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1179. } else {
  1180. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1181. }
  1182. my $ad_zone = get_option($db,33);
  1183. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1184. my @add_dns;
  1185. if ($config_ref{dns_server_type}=~/windows/i) {
  1186. push(@add_dns,"gsstsig");
  1187. push(@add_dns,"server $server");
  1188. push(@add_dns,"zone $zone");
  1189. push(@add_dns,"update delete $fqdn A");
  1190. push(@add_dns,"send");
  1191. write_to_file($nsupdate_file,\@add_dns);
  1192. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1193. }
  1194. if ($config_ref{dns_server_type}=~/bind/i) {
  1195. push(@add_dns,"server $server");
  1196. push(@add_dns,"zone $zone");
  1197. push(@add_dns,"update delete $fqdn A");
  1198. push(@add_dns,"send");
  1199. write_to_file($nsupdate_file,\@add_dns);
  1200. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1201. }
  1202. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1203. }
  1204. #---------------------------------------------------------------------------------------------------------------
  1205. sub create_dns_ptr {
  1206. my $fqdn = shift;
  1207. my $ip = shift;
  1208. my $ad_zone = shift;
  1209. my $server = shift;
  1210. my $db = shift;
  1211. my $radr;
  1212. my $zone;
  1213. #skip update domain controllers
  1214. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1215. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1216. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1217. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1218. $zone = "$3.$2.$1.in-addr.arpa";
  1219. }
  1220. if (!$radr or !$zone) { return 0; }
  1221. if (!$db) { return 0; }
  1222. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  1223. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1224. my @add_dns;
  1225. if ($config_ref{dns_server_type}=~/windows/i) {
  1226. push(@add_dns,"gsstsig");
  1227. push(@add_dns,"server $server");
  1228. push(@add_dns,"zone $zone");
  1229. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1230. push(@add_dns,"send");
  1231. write_to_file($nsupdate_file,\@add_dns);
  1232. 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.'"';
  1233. do_exec($run_cmd);
  1234. }
  1235. if ($config_ref{dns_server_type}=~/bind/i) {
  1236. push(@add_dns,"server $server");
  1237. push(@add_dns,"zone $zone");
  1238. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1239. push(@add_dns,"send");
  1240. write_to_file($nsupdate_file,\@add_dns);
  1241. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1242. do_exec($run_cmd);
  1243. }
  1244. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1245. }
  1246. #---------------------------------------------------------------------------------------------------------------
  1247. sub delete_dns_ptr {
  1248. my $fqdn = shift;
  1249. my $ip = shift;
  1250. my $ad_zone = shift;
  1251. my $server = shift;
  1252. my $db = shift;
  1253. my $radr;
  1254. my $zone;
  1255. #skip update domain controllers
  1256. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1257. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1258. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1259. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1260. $zone = "$3.$2.$1.in-addr.arpa";
  1261. }
  1262. if (!$radr or !$zone) { return 0; }
  1263. if (!$db) { return 0 ; }
  1264. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  1265. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1266. my @add_dns;
  1267. if ($config_ref{dns_server_type}=~/windows/i) {
  1268. push(@add_dns,"gsstsig");
  1269. push(@add_dns,"server $server");
  1270. push(@add_dns,"zone $zone");
  1271. push(@add_dns,"update delete $radr PTR");
  1272. push(@add_dns,"send");
  1273. write_to_file($nsupdate_file,\@add_dns);
  1274. 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.'"';
  1275. do_exec($run_cmd);
  1276. }
  1277. if ($config_ref{dns_server_type}=~/bind/i) {
  1278. push(@add_dns,"server $server");
  1279. push(@add_dns,"zone $zone");
  1280. push(@add_dns,"update delete $radr PTR");
  1281. push(@add_dns,"send");
  1282. write_to_file($nsupdate_file,\@add_dns);
  1283. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1284. do_exec($run_cmd);
  1285. }
  1286. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1287. }
  1288. #---------------------------------------------------------------------------------------------------------------
  1289. sub new_user {
  1290. my $db = shift;
  1291. my $user_info = shift;
  1292. my $user;
  1293. if ($user_info->{mac}) {
  1294. $user->{login}=mac_splitted($user_info->{mac});
  1295. } else {
  1296. $user->{login}=$user_info->{ip};
  1297. }
  1298. if ($user_info->{dhcp_hostname}) { $user->{fio}=$user_info->{dhcp_hostname}; }
  1299. if (!$user->{fio}) { $user->{fio}=$user_info->{ip}; }
  1300. my $login_count = get_count_records($db,"User_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  1301. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  1302. $user->{ou_id} = $user_info->{ou_id};
  1303. my $ou_info = get_record_sql($db,"SELECT * FROM OU WHERE id=".$user_info->{'ou_id'});
  1304. if ($ou_info) {
  1305. $user->{'enabled'} = $ou_info->{'enabled'};
  1306. $user->{'queue_id'} = $ou_info->{'queue_id'};
  1307. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  1308. }
  1309. my $result = insert_record($db,"User_list",$user);
  1310. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  1311. my $auth_rule;
  1312. $auth_rule->{user_id} = $result;
  1313. $auth_rule->{type} = 2;
  1314. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  1315. insert_record($db,"auth_rules",$auth_rule);
  1316. }
  1317. return $result;
  1318. }
  1319. #---------------------------------------------------------------------------------------------------------------
  1320. sub get_ip_subnet {
  1321. my $db = shift;
  1322. my $ip = shift;
  1323. if (!$ip) { return; }
  1324. my $ip_aton = StrToIp($ip);
  1325. 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)");
  1326. return $user_subnet;
  1327. }
  1328. #---------------------------------------------------------------------------------------------------------------
  1329. sub find_mac_in_subnet {
  1330. my $db = shift;
  1331. my $ip = shift;
  1332. my $mac = shift;
  1333. if (!$ip or !$mac) { return; }
  1334. my $ip_subnet = get_ip_subnet($db, $ip);
  1335. if (!$ip_subnet) { return; }
  1336. my @t_auth = get_records_sql($db, "SELECT id,mac,user_id 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");
  1337. my $auth_count = 0;
  1338. my $result;
  1339. $result->{'count'} = 0;
  1340. foreach my $row (@t_auth) {
  1341. next if (!$row);
  1342. $auth_count++;
  1343. $result->{'count'} = $auth_count;
  1344. $result->{$auth_count} = $row->{'id'};
  1345. push(@{$result->{'users_id'}}, $row->{'user_id'});
  1346. }
  1347. return $result;
  1348. }
  1349. #---------------------------------------------------------------------------------------------------------------
  1350. sub resurrection_auth {
  1351. my $db = shift;
  1352. my $ip_record = shift;
  1353. my $ip = $ip_record->{'ip'};
  1354. my $mac = $ip_record->{'mac'};
  1355. my $action = $ip_record->{'type'};
  1356. my $hostname = $ip_record->{'hostname_utf8'};
  1357. my $client_id = $ip_record->{'client-id'};
  1358. if (!exists $ip_record->{ip_aton}) { $ip_record->{ip_aton}=StrToIp($ip); }
  1359. if (!exists $ip_record->{hotspot}) { $ip_record->{hotspot}=is_hotspot($db,$ip); }
  1360. my $ip_aton=$ip_record->{ip_aton};
  1361. my $timestamp=GetNowTime();
  1362. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  1363. my $new_record;
  1364. $new_record->{last_found}=$timestamp;
  1365. $new_record->{arp_found}=$timestamp;
  1366. if ($client_id) { $new_record->{'client-id'} = $client_id; }
  1367. #auth found?
  1368. if ($record->{user_id}) {
  1369. #update timestamp and return
  1370. if ($action=~/^(add|old|del)$/i) {
  1371. $new_record->{dhcp_action}=$action;
  1372. $new_record->{created_by}='dhcp';
  1373. $new_record->{dhcp_time}=$timestamp;
  1374. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1375. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1376. } else {
  1377. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1378. }
  1379. return $record->{id};
  1380. }
  1381. my $user_subnet=$office_networks->match_string($ip);
  1382. if ($user_subnet->{static}) {
  1383. db_log_warning($db,"Unknown ip+mac found in static subnet! Abort create record for ip: $ip mac: [".$mac."]");
  1384. return 0;
  1385. }
  1386. #search changed mac
  1387. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  1388. if ($record->{id}) {
  1389. #if found record with same ip but another mac
  1390. if (!$record->{mac}) {
  1391. db_log_verbose($db,"use empty auth record...");
  1392. $new_record->{mac}=$mac;
  1393. if ($action=~/^(add|old|del)$/i) {
  1394. $new_record->{dhcp_action}=$action;
  1395. $new_record->{dhcp_time}=$timestamp;
  1396. $new_record->{created_by}='dhcp';
  1397. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1398. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1399. } else {
  1400. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1401. }
  1402. return $record->{id};
  1403. }
  1404. if ($record->{mac}) {
  1405. db_log_warning($db,"For ip: $ip mac change detected! Old mac: [".$record->{mac}."] New mac: [".$mac."]. Disable old auth_id: $record->{id}") if (!$ip_record->{hotspot});
  1406. my $disable_record;
  1407. $disable_record->{deleted}="1";
  1408. update_record($db,'User_auth',$disable_record,"id=".$record->{id});
  1409. }
  1410. }
  1411. #default user
  1412. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  1413. my $new_user_id;
  1414. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1415. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  1416. my $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1417. #disable dhcp for same mac in one ip subnet
  1418. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1419. #seek old auth with same ip and mac
  1420. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1421. $new_record->{ip_int}=$ip_aton;
  1422. $new_record->{ip}=$ip;
  1423. $new_record->{mac}=$mac;
  1424. $new_record->{user_id}=$new_user_id;
  1425. $new_record->{save_traf}="$save_detail";
  1426. $new_record->{deleted}="0";
  1427. if ($action=~/^(add|old|del)$/i) {
  1428. $new_record->{dhcp_action}=$action;
  1429. $new_record->{dhcp_time}=$timestamp;
  1430. $new_record->{created_by}='dhcp';
  1431. } else {
  1432. $new_record->{created_by}=$action;
  1433. }
  1434. if ($auth_exists) {
  1435. #found ->Resurrection old record
  1436. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1437. if (!$ip_record->{hotspot}) { db_log_warning($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  1438. else { db_log_info($db,"Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac"); }
  1439. update_record($db,'User_auth',$new_record,"id=$resurrection_id");
  1440. } else {
  1441. #not found ->create new record
  1442. if (!$ip_record->{hotspot}) { db_log_warning($db,"New ip created! ip: $ip mac: $mac"); } else { db_log_info($db,"New ip created! ip: $ip mac: $mac"); }
  1443. insert_record($db,'User_auth',$new_record);
  1444. }
  1445. #filter and status
  1446. my $cur_auth_id=get_id_record($db,'User_auth',"ip='$ip' and mac='$mac' and deleted=0 ORDER BY last_found DESC");
  1447. if ($cur_auth_id) {
  1448. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1449. if ($user_record) {
  1450. my $ou_info = get_record_sql($db,'SELECT * FROM OU WHERE id='.$user_record->{ou_id});
  1451. if ($ou_info and $ou_info->{'dynamic'}) {
  1452. if (!$ou_info->{'life_duration'}) { $ou_info->{'life_duration'} = 24; }
  1453. my $now = DateTime->now(time_zone=>'local');
  1454. my $hours_dur = DateTime::Duration->new( hours => $ou_info->{'life_duration'} );
  1455. my $eof = $now + $hours_dur;
  1456. $new_record->{'dynamic'} = 1;
  1457. $new_record->{'eof'}=$eof->strftime('%Y-%m-%d %H:%M:%S');
  1458. }
  1459. $new_record->{ou_id}=$user_record->{ou_id};
  1460. $new_record->{comments}=$user_record->{fio};
  1461. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1462. $new_record->{queue_id}=$user_record->{queue_id};
  1463. $new_record->{enabled}="$user_record->{enabled}";
  1464. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  1465. }
  1466. } else { return; }
  1467. return $cur_auth_id;
  1468. }
  1469. #---------------------------------------------------------------------------------------------------------------
  1470. sub new_auth {
  1471. my $db = shift;
  1472. my $ip = shift;
  1473. my $ip_aton=StrToIp($ip);
  1474. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  1475. if ($record->{id}) { return $record->{id}; }
  1476. #default user
  1477. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  1478. my $new_user_id;
  1479. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1480. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  1481. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1482. my $timestamp=GetNowTime();
  1483. my $new_record;
  1484. $new_record->{ip_int}=$ip_aton;
  1485. $new_record->{ip}=$ip;
  1486. $new_record->{user_id}=$new_user_id;
  1487. $new_record->{save_traf}="$save_detail";
  1488. $new_record->{deleted}="0";
  1489. $new_record->{created_by}='netflow';
  1490. $new_record->{ou_id}=$user_record->{ou_id};
  1491. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1492. $new_record->{queue_id}=$user_record->{queue_id};
  1493. $new_record->{enabled}="$user_record->{enabled}";
  1494. if ($user_record->{fio}) { $new_record->{comments}=$user_record->{fio}; }
  1495. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  1496. db_log_warning($db,"New ip created by netflow! ip: $ip") if ($cur_auth_id);
  1497. return $cur_auth_id;
  1498. }
  1499. #---------------------------------------------------------------------------------------------------------------
  1500. sub get_option {
  1501. my $db=shift;
  1502. my $option_id=shift;
  1503. return if (!$option_id);
  1504. return if (!$db);
  1505. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  1506. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  1507. my $result;
  1508. if (!$config_options) {
  1509. if ($default_option->{'type'}=~/^(int|bool)/i) { $result = $default_option->{'default_value'}*1; };
  1510. if ($default_option->{'type'}=~/^(string|text)/i) { $result = $default_option->{'default_value'}; }
  1511. if ($default_option->{'type'}=~/^list/i) { $result = $default_option->{'default_value'}; }
  1512. return $result;
  1513. }
  1514. $result = $config_options->{'value'};
  1515. return $result;
  1516. }
  1517. #---------------------------------------------------------------------------------------------------------------
  1518. sub init_option {
  1519. my $db=shift;
  1520. $last_refresh_config = time();
  1521. $config_ref{version}='';
  1522. my $version_record = get_record_sql($db,"SELECT version FROM version WHERE version is NOT NULL");
  1523. if ($version_record) { $config_ref{version}=$version_record->{version}; }
  1524. $config_ref{dbh}=$db;
  1525. $config_ref{save_detail}=get_option($db,23);
  1526. $config_ref{add_unknown_user}=get_option($db,22);
  1527. $config_ref{dhcp_server}=get_option($db,5);
  1528. $config_ref{snmp_default_version}=get_option($db,9);
  1529. $config_ref{snmp_default_community}=get_option($db,11);
  1530. $config_ref{KB}=get_option($db,1);
  1531. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  1532. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  1533. $config_ref{admin_email}=get_option($db,21);
  1534. $config_ref{sender_email}=get_option($db,52);
  1535. $config_ref{send_email}=get_option($db,51);
  1536. $config_ref{history}=get_option($db,26);
  1537. $config_ref{history_dhcp}=get_option($db,27);
  1538. $config_ref{router_login}=get_option($db,28);
  1539. $config_ref{router_password}=get_option($db,29);
  1540. $config_ref{router_port}=get_option($db,30);
  1541. $config_ref{org_name}=get_option($db,32);
  1542. $config_ref{domain_name}=get_option($db,33);
  1543. $config_ref{connections_history}=get_option($db,35);
  1544. $config_ref{debug}=get_option($db,34);
  1545. $config_ref{log_level} = get_option($db,53);
  1546. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  1547. $config_ref{urgent_sync}=get_option($db,50);
  1548. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  1549. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  1550. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  1551. $config_ref{history_log_day}=get_option($db,47);
  1552. $config_ref{history_syslog_day} = get_option($db,48);
  1553. $config_ref{history_trafstat_day} = get_option($db,49);
  1554. $config_ref{enable_quotes} = get_option($db,54);
  1555. $config_ref{netflow_step} = get_option($db,55);
  1556. $config_ref{traffic_ipstat_history} = get_option($db,56);
  1557. $config_ref{nagios_url} = get_option($db,57);
  1558. $config_ref{cacti_url} = get_option($db,58);
  1559. $config_ref{torrus_url} = get_option($db,59);
  1560. $config_ref{wiki_url} = get_option($db,60);
  1561. $config_ref{stat_url} = get_option($db,62);
  1562. $config_ref{wiki_path} = get_option($db,61);
  1563. $config_ref{auto_mac_rule} = get_option($db,64);
  1564. #network configuration mode
  1565. $config_ref{config_mode}=get_option($db,68);
  1566. #auto clean old user record
  1567. $config_ref{clean_empty_user}=get_option($db,69);
  1568. #dns_server_type
  1569. $config_ref{dns_server}=get_option($db,3);
  1570. $config_ref{dns_server_type}=get_option($db,70);
  1571. $config_ref{enable_dns_updates}=get_option($db,71);
  1572. #$save_detail = 1; id=23
  1573. $save_detail=get_option($db,23);
  1574. #$add_unknown_user = 1; id=22
  1575. $add_unknown_user=get_option($db,22);
  1576. #$dns_server='192.168.2.12'; id=3
  1577. $dns_server=get_option($db,3);
  1578. #$dhcp_server='192.168.2.12'; id=5
  1579. $dhcp_server=get_option($db,5);
  1580. #$snmp_default_version='2'; id=9
  1581. $snmp_default_version=get_option($db,9);
  1582. #$snmp_default_community='public'; id=11
  1583. $snmp_default_community=get_option($db,11);
  1584. #$KB=1024; id=1
  1585. $KB=$config_ref{KB};
  1586. #$admin_email; id=21
  1587. $admin_email=get_option($db,21);
  1588. #sender email
  1589. $sender_email=get_option($db,52);
  1590. #send email
  1591. $send_email=get_option($db,51);
  1592. #$history=15; id=26
  1593. $history=get_option($db,26);
  1594. #$history_dhcp=7; id=27
  1595. $history_dhcp=get_option($db,27);
  1596. #$router_login="admin"; id=28
  1597. $router_login=get_option($db,28);
  1598. #$router_password="admin"; id=29
  1599. $router_password=get_option($db,29);
  1600. #$router_port=23; id=30
  1601. $router_port=get_option($db,30);
  1602. #32
  1603. $org_name=get_option($db,32);
  1604. #33
  1605. $domain_name=get_option($db,33);
  1606. #35
  1607. $connections_history=get_option($db,35);
  1608. #debug
  1609. $debug=get_option($db,34);
  1610. #log level
  1611. $log_level = get_option($db,53);
  1612. if ($debug) { $log_level = 255; }
  1613. #urgent sync access
  1614. $urgent_sync=get_option($db,50);
  1615. $ignore_hotspot_dhcp_log = get_option($db,44);
  1616. $ignore_update_dhcp_event = get_option($db,45);
  1617. $update_hostname_from_dhcp = get_option($db,46);
  1618. $history_log_day=get_option($db,47);
  1619. $history_syslog_day = get_option($db,48);
  1620. $history_trafstat_day = get_option($db,49);
  1621. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1622. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  1623. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1624. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  1625. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1626. if (defined $office_networks) { undef $office_networks; }
  1627. if (defined $free_networks) { undef $free_networks; }
  1628. if (defined $vpn_networks) { undef $vpn_networks; }
  1629. if (defined $hotspot_networks) { undef $hotspot_networks; }
  1630. if (defined $all_networks) { undef $all_networks; }
  1631. $office_networks = new Net::Patricia;
  1632. $free_networks = new Net::Patricia;
  1633. $vpn_networks = new Net::Patricia;
  1634. $hotspot_networks = new Net::Patricia;
  1635. $all_networks = new Net::Patricia;
  1636. @office_network_list=();
  1637. @free_network_list=();
  1638. @free_network_list=();
  1639. @vpn_network_list=();
  1640. @hotspot_network_list=();
  1641. @all_network_list=();
  1642. foreach my $net (@subnets) {
  1643. next if (!$net->{subnet});
  1644. $subnets_ref{$net->{subnet}}=$net;
  1645. if ($net->{office}) {
  1646. push(@office_network_list,$net->{subnet});
  1647. $office_networks->add_string($net->{subnet},$net);
  1648. }
  1649. if ($net->{free}) {
  1650. push(@free_network_list,$net->{subnet});
  1651. $free_networks->add_string($net->{subnet},$net);
  1652. }
  1653. if ($net->{vpn}) {
  1654. push(@vpn_network_list,$net->{subnet});
  1655. $vpn_networks->add_string($net->{subnet},$net);
  1656. }
  1657. if ($net->{hotspot}) {
  1658. push(@hotspot_network_list,$net->{subnet});
  1659. push(@all_network_list,$net->{subnet});
  1660. $hotspot_networks->add_string($net->{subnet},$net);
  1661. }
  1662. push(@all_network_list,$net->{subnet});
  1663. $all_networks->add_string($net->{subnet},$net);
  1664. }
  1665. }
  1666. #--------------------------------------------------------------------------------------------------------------
  1667. sub get_dynamic_ou {
  1668. my $db = shift;
  1669. my @dynamic=();
  1670. my @ou_list = get_records_sql($db,"SELECT id FROM OU WHERE dynamic = 1");
  1671. foreach my $group (@ou_list) {
  1672. next if (!$group);
  1673. push(@dynamic,$group->{id});
  1674. }
  1675. return wantarray ? @dynamic : \@dynamic;
  1676. }
  1677. #--------------------------------------------------------------------------------------------------------------
  1678. sub get_default_ou {
  1679. my $db = shift;
  1680. my @dynamic=();
  1681. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1682. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1683. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1684. if ($ou) { push(@dynamic,$ou->{id}); }
  1685. return wantarray ? @dynamic : \@dynamic;
  1686. }
  1687. #--------------------------------------------------------------------------------------------------------------
  1688. sub is_dynamic_ou {
  1689. my $db = shift;
  1690. my $ou_id = shift;
  1691. my @dynamic=get_dynamic_ou($db);
  1692. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1693. return 0;
  1694. }
  1695. #--------------------------------------------------------------------------------------------------------------
  1696. sub is_default_ou {
  1697. my $db = shift;
  1698. my $ou_id = shift;
  1699. my @dynamic=get_default_ou($db);
  1700. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1701. return 0;
  1702. }
  1703. #---------------------------------------------------------------------------------------------------------------
  1704. sub get_subnets_ref {
  1705. my $db = shift;
  1706. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1707. my $list_ref;
  1708. foreach my $net (@list) {
  1709. next if (!$net->{subnet});
  1710. $list_ref->{$net->{subnet}}=$net;
  1711. }
  1712. return $list_ref;
  1713. }
  1714. #---------------------------------------------------------------------------------------------------------------
  1715. sub get_device_by_ip {
  1716. my $db = shift;
  1717. my $ip = shift;
  1718. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  1719. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1720. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  1721. if ($auth_rec and $auth_rec->{user_id}>0) {
  1722. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1723. return $netdev;
  1724. }
  1725. return;
  1726. }
  1727. #---------------------------------------------------------------------------------------------------------------
  1728. sub GetUnixTimeByStr {
  1729. my $time_str = shift;
  1730. $time_str =~s/\//-/g;
  1731. $time_str = trim($time_str);
  1732. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  1733. $year+=1900;
  1734. $mon++;
  1735. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  1736. $year = $1; $mon = $2; $day = $3;
  1737. }
  1738. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  1739. $hour = $1; $min = $2; $sec = $3;
  1740. }
  1741. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  1742. return $result;
  1743. }
  1744. #---------------------------------------------------------------------------------------------------------------
  1745. sub GetTimeStrByUnixTime {
  1746. my $time = shift || time();
  1747. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  1748. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  1749. return $result;
  1750. }
  1751. #---------------------------------------------------------------------------------------------------------------
  1752. sub Set_Variable {
  1753. my $db = shift;
  1754. my $name = shift || $MY_NAME;
  1755. my $value = shift || $$;
  1756. my $timeshift = shift || 60;
  1757. Del_Variable($db,$name);
  1758. my $clean_variables = time() + $timeshift;
  1759. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1760. $month++;
  1761. $year += 1900;
  1762. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1763. my $clean_variables_date=$db->quote($clean_str);
  1764. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  1765. }
  1766. #---------------------------------------------------------------------------------------------------------------
  1767. sub Get_Variable {
  1768. my $db = shift;
  1769. my $name = shift || $MY_NAME;
  1770. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  1771. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  1772. return;
  1773. }
  1774. #---------------------------------------------------------------------------------------------------------------
  1775. sub Del_Variable {
  1776. my $db = shift;
  1777. my $name = shift || $MY_NAME;
  1778. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  1779. }
  1780. #---------------------------------------------------------------------------------------------------------------
  1781. sub recalc_quotes {
  1782. my $db = shift;
  1783. my $calc_id = shift || $$;
  1784. return if (!get_option($db,54));
  1785. clean_variables($db);
  1786. return if (Get_Variable($db,'RECALC'));
  1787. my $timeshift = get_option($db,55);
  1788. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  1789. my $now = DateTime->now(time_zone=>'local');
  1790. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  1791. my $day_dur = DateTime::Duration->new( days => 1 );
  1792. my $tomorrow = $now+$day_dur;
  1793. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  1794. $now->set(day=>1);
  1795. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  1796. my $month_dur = DateTime::Duration->new( months => 1 );
  1797. my $next_month = $now + $month_dur;
  1798. $next_month->set(day=>1);
  1799. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  1800. #get user limits
  1801. 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";
  1802. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  1803. my %user_stats;
  1804. my %auth_info;
  1805. foreach my $row (@authlist_ref) {
  1806. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  1807. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  1808. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  1809. $auth_info{$row->{auth_id}}{day}=0;
  1810. $auth_info{$row->{auth_id}}{month}=0;
  1811. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  1812. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  1813. $user_stats{$row->{id}}{day}=0;
  1814. $user_stats{$row->{id}}{month}=0;
  1815. }
  1816. #recalc quotes - global
  1817. #day
  1818. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1819. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  1820. my @day_stats = get_records_sql($db,$day_sql);
  1821. foreach my $row (@day_stats) {
  1822. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1823. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  1824. $user_stats{$user_id}{day}+=$row->{traf_all};
  1825. }
  1826. #month
  1827. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  1828. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  1829. my @month_stats = get_records_sql($db,$month_sql);
  1830. foreach my $row (@month_stats) {
  1831. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  1832. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  1833. $user_stats{$user_id}{month}+=$row->{traf_all};
  1834. }
  1835. foreach my $auth_id (keys %auth_info) {
  1836. next if (!$auth_info{$auth_id}{day_limit});
  1837. next if (!$auth_info{$auth_id}{month_limit});
  1838. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  1839. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  1840. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  1841. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  1842. if ($blocked_d or $blocked_m) {
  1843. my $history_msg;
  1844. 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; }
  1845. 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; }
  1846. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  1847. db_log_verbose($db,$history_msg);
  1848. }
  1849. }
  1850. foreach my $user_id (keys %user_stats) {
  1851. next if (!$user_stats{$user_id}{day_limit});
  1852. next if (!$user_stats{$user_id}{month_limit});
  1853. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  1854. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  1855. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  1856. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  1857. if ($blocked_d or $blocked_m) {
  1858. my $history_msg;
  1859. 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; }
  1860. 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; }
  1861. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  1862. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  1863. db_log_verbose($db,$history_msg);
  1864. }
  1865. }
  1866. Del_Variable($db,'RECALC');
  1867. }
  1868. #---------------------------------------------------------------------------------------------------------------
  1869. sub clean_variables {
  1870. my $db = shift;
  1871. #clean temporary variables
  1872. my $clean_variables = time();
  1873. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1874. $month++;
  1875. $year += 1900;
  1876. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1877. my $clean_variables_date=$db->quote($now_str);
  1878. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  1879. #clean old AD computer cache
  1880. my $now = DateTime->now(time_zone=>'local');
  1881. my $day_dur = DateTime::Duration->new( days => 1 );
  1882. my $clean_date = $now - $day_dur;
  1883. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  1884. do_sql($db,"DELETE FROM `ad_comp_cache` WHERE last_found<=$clean_str");
  1885. }
  1886. #---------------------------------------------------------------------------------------------------------------
  1887. #skip init for upgrade
  1888. if ($MY_NAME!~/upgrade.pl/) {
  1889. $dbh=init_db();
  1890. init_option($dbh);
  1891. clean_variables($dbh);
  1892. Set_Variable($dbh);
  1893. }
  1894. 1;
  1895. }