mysql.pm 66 KB

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