mysql.pm 66 KB

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