database.pm 74 KB

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