database.pm 78 KB

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