mysql.pm 66 KB

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