mysql.pm 66 KB

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