database.pm 74 KB

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