database.pm 69 KB

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