mysql.pm 64 KB

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