database.pm 68 KB

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