database.pm 85 KB

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