database.pm 85 KB

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