database.pm 72 KB

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