database.pm 90 KB

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