mysql.pm 66 KB

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