database.pm 77 KB

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