mysql.pm 65 KB

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