database.pm 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588
  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 $record = get_record_sql($db,'SELECT * FROM User_auth WHERE id='.$id);
  702. my $auth_ident = $record->{ip};
  703. $auth_ident = $auth_ident . '['.$record->{dns_name} .']' if ($record->{dns_name});
  704. $auth_ident = $auth_ident . ' :: '.$record->{comments} if ($record->{dns_name});
  705. my $msg = "";
  706. my $txt_record = hash_to_text($record);
  707. #remove aliases
  708. my @t_User_auth_alias = get_records_sql($db,'SELECT * FROM User_auth_alias WHERE auth_id='.$id);
  709. if (@t_User_auth_alias and scalar @t_User_auth_alias) {
  710. foreach my $row ( @t_User_auth_alias) {
  711. my $alias_txt = record_to_txt($db,'User_auth_alias','id='.$row->{'id'});
  712. if (delete_record($db,'User_auth_alias','id='.$row->{'id'})) {
  713. $msg = "Deleting an alias: ". $alias_txt . "\n::Success!\n" . $msg;
  714. } else {
  715. $msg = "Deleting an alias: ". $alias_txt . "\n::Fail!\n" . $msg;
  716. }
  717. }
  718. }
  719. #remove connections
  720. do_sql($db,'DELETE FROM connections WHERE auth_id='.$id);
  721. #remove user auth record
  722. my $changes = delete_record($db, "User_auth", "id=" . $id);
  723. if ($changes) {
  724. $msg = "Deleting ip-record: ". $txt_record . "\n::Success!\n" . $msg;
  725. } else {
  726. $msg = "Deleting ip-record: ". $txt_record . "\n::Fail!\n" . $msg;
  727. }
  728. $msg = "Deleting user ip record $auth_ident\n\n".$msg;
  729. db_log_warning($db, $msg, $id);
  730. my $send_alert = isNotifyDelete(get_notify_subnet($db,$record->{ip}));
  731. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  732. return $changes;
  733. }
  734. #---------------------------------------------------------------------------------------------------------------
  735. sub unblock_user {
  736. my $db = shift;
  737. my $user_id = shift;
  738. my $user_record = get_record_sql($db,'SELECT * FROM User_list WHERE id='.$user_id);
  739. my $user_ident = 'id:'. $user_record->{'id'} . ' '. $user_record->{'login'};
  740. $user_ident = $user_ident . '[' . $user_record->{'fio'} . ']' if ($user_record->{'fio'});
  741. my $msg = "Amnistuyemo blocked by traffic user $user_ident \nInternet access for the user's IP address has been restored:\n";
  742. my @user_auth = get_records_sql($db,'SELECT * FROM User_auth WHERE deleted=0 AND user_id='.$user_id);
  743. my $send_alert = 0;
  744. if (@user_auth and scalar @user_auth) {
  745. foreach my $record (@user_auth) {
  746. $send_alert = ($send_alert or isNotifyUpdate(get_notify_subnet($db,$record->{ip})));
  747. my $auth_ident = $record->{ip};
  748. $auth_ident = $auth_ident . '['.$record->{dns_name} .']' if ($record->{dns_name});
  749. $auth_ident = $auth_ident . ' :: '.$record->{comments} if ($record->{dns_name});
  750. my $new;
  751. $new->{'blocked'}=0;
  752. $new->{'changed'}=1;
  753. my $ret_id = update_record($db,'User_auth',$new,'id='.$record->{'id'});
  754. if ($ret_id) {
  755. $msg = $msg ."\n".$auth_ident;
  756. }
  757. }
  758. }
  759. my $new;
  760. $new->{'blocked'}=0;
  761. my $ret_id = update_record($db,'User_list','id='.$user_id);
  762. if ($ret_id) {
  763. db_log_info($dbh,$msg);
  764. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  765. }
  766. return $ret_id;
  767. }
  768. #---------------------------------------------------------------------------------------------------------------
  769. sub delete_user {
  770. my $db = shift;
  771. my $id = shift;
  772. #remove user record
  773. my $changes = delete_record($db, "User_list", "id=" . $id);
  774. #if fail - exit
  775. if (!$changes) { return; }
  776. #remove auth records
  777. my @t_User_auth = get_records_sql($db,'SELECT * FROM User_auth WHERE user_id='.$id);
  778. if (@t_User_auth and scalar @t_User_auth) {
  779. foreach my $row ( @t_User_auth ) { delete_user_auth($db,$row->{'id'}); }
  780. }
  781. #remove device
  782. my $device = get_record_sql($db, "SELECT * FROM devices WHERE user_id=".$id);
  783. if ($device) { delete_device($db,$device->{'id'}); }
  784. #remove auth assign rules
  785. do_sql($db, "DELETE FROM auth_rules WHERE user_id=$id");
  786. return $changes;
  787. }
  788. #---------------------------------------------------------------------------------------------------------------
  789. sub delete_device {
  790. my $db = shift;
  791. my $id = shift;
  792. #remove user record
  793. my $changes = delete_record($db, "devices", "id=" . $id);
  794. #if fail - exit
  795. if (!$changes) { return; }
  796. unbind_ports($db, $id);
  797. do_sql($db, "DELETE FROM connections WHERE device_id=" . $id);
  798. do_sql($db, "DELETE FROM device_l3_interfaces WHERE device_id=" . $id);
  799. do_sql($db, "DELETE FROM device_ports WHERE device_id=" . $id);
  800. do_sql($db, "DELETE FROM device_filter_instances WHERE device_id=" . $id);
  801. do_sql($db, "DELETE FROM gateway_subnets WHERE device_id=".$id);
  802. return $changes;
  803. }
  804. #---------------------------------------------------------------------------------------------------------------
  805. sub GetNowTime {
  806. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime(time());
  807. $month += 1;
  808. $year += 1900;
  809. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  810. return $now_str;
  811. }
  812. #---------------------------------------------------------------------------------------------------------------
  813. sub is_hotspot {
  814. my $db = shift;
  815. my $ip = shift;
  816. my $users = new Net::Patricia;
  817. #check hotspot
  818. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  819. foreach my $row (@ip_rules) { $users->add_string($row->{subnet}); }
  820. if ($users->match_string($ip)) { return 1; }
  821. return 0;
  822. }
  823. #---------------------------------------------------------------------------------------------------------------
  824. sub get_office_subnet {
  825. my $db = shift;
  826. my $ip = shift;
  827. my $subnets = new Net::Patricia;
  828. my @ip_rules = get_records_sql($db,'SELECT * FROM subnets WHERE office=1 AND LENGTH(subnet)>0');
  829. foreach my $row (@ip_rules) { $subnets->add_string($row->{subnet},$row); }
  830. return $subnets->match_string($ip);
  831. }
  832. #---------------------------------------------------------------------------------------------------------------
  833. sub get_notify_subnet {
  834. my $db = shift;
  835. my $ip = shift;
  836. my $notify_flag = get_office_subnet($db,$ip);
  837. if ($notify_flag) { return $notify_flag->{notify}; }
  838. return 0;
  839. }
  840. #---------------------------------------------------------------------------------------------------------------
  841. sub get_new_user_id {
  842. my $db = shift;
  843. my $ip = shift;
  844. my $mac = shift;
  845. my $hostname = shift;
  846. my $result;
  847. #check user rules
  848. $mac = mac_simplify($mac);
  849. $result->{ip} = $ip;
  850. $result->{mac} = mac_splitted($mac);
  851. $result->{dhcp_hostname} = $hostname;
  852. $result->{ou_id}=undef;
  853. $result->{user_id}=undef;
  854. my $hotspot_users = new Net::Patricia;
  855. #check hotspot
  856. my @hotspot_rules = get_records_sql($db,'SELECT * FROM subnets WHERE hotspot=1 AND LENGTH(subnet)>0');
  857. foreach my $row (@hotspot_rules) { $hotspot_users->add_string($row->{subnet},$default_hotspot_ou_id); }
  858. if ($hotspot_users->match_string($ip)) { $result->{ou_id}=$hotspot_users->match_string($ip); return $result; }
  859. #check ip
  860. if (defined $ip and $ip) {
  861. my $users = new Net::Patricia;
  862. #check ip rules
  863. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND user_id IS NOT NULL');
  864. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{user_id}); }; }
  865. if ($users->match_string($ip)) { $result->{user_id}=$users->match_string($ip); return $result; }
  866. }
  867. #check mac
  868. if (defined $mac and $mac) {
  869. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  870. foreach my $user (@user_rules) {
  871. my $rule = mac_simplify($user->{rule});
  872. if ($mac=~/$rule/i) { $result->{user_id}=$user->{user_id}; return $result; }
  873. }
  874. }
  875. #check hostname
  876. if (defined $hostname and $hostname) {
  877. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND user_id IS NOT NULL');
  878. foreach my $user (@user_rules) {
  879. if ($hostname=~/$user->{rule}/i) { $result->{user_id}=$user->{user_id}; return $result; }
  880. }
  881. }
  882. #check ou rules
  883. #check ip
  884. if (defined $ip and $ip) {
  885. my $users = new Net::Patricia;
  886. #check ip rules
  887. my @ip_rules = get_records_sql($db,'SELECT * FROM auth_rules WHERE type=1 and LENGTH(rule)>0 AND ou_id IS NOT NULL');
  888. foreach my $row (@ip_rules) { eval { $users->add_string($row->{rule},$row->{ou_id}); }; }
  889. if ($users->match_string($ip)) { $result->{ou_id}=$users->match_string($ip); return $result; }
  890. }
  891. #check mac
  892. if (defined $mac and $mac) {
  893. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=2 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  894. foreach my $user (@user_rules) {
  895. my $rule = mac_simplify($user->{rule});
  896. if ($mac=~/$rule/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  897. }
  898. }
  899. #check hostname
  900. if (defined $hostname and $hostname) {
  901. my @user_rules=get_records_sql($db,'SELECT * FROM auth_rules WHERE type=3 AND LENGTH(rule)>0 AND ou_id IS NOT NULL');
  902. foreach my $user (@user_rules) {
  903. if ($hostname=~/$user->{rule}/i) { $result->{ou_id}=$user->{ou_id}; return $result; }
  904. }
  905. }
  906. if (!$result->{ou_id}) { $result->{ou_id}=$default_user_ou_id; }
  907. return $result;
  908. }
  909. #---------------------------------------------------------------------------------------------------------------
  910. sub set_changed {
  911. my $db = shift;
  912. my $id = shift;
  913. return if (!$db or !$id);
  914. my $update_record;
  915. $update_record->{changed}=1;
  916. update_record($db,'User_auth',$update_record,"id=$id");
  917. }
  918. #---------------------------------------------------------------------------------------------------------------
  919. sub update_dns_record {
  920. my $hdb = shift;
  921. my $auth_id = shift;
  922. return if (!$config_ref{enable_dns_updates});
  923. #get domain
  924. my $ad_zone = get_option($hdb,33);
  925. #get dns server
  926. my $ad_dns = get_option($hdb,3);
  927. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $config_ref{enable_dns_updates});
  928. log_debug("Auth id: ".$auth_id);
  929. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  930. log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
  931. 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");
  932. if (!@dns_queue or !scalar @dns_queue) { return; }
  933. foreach my $dns_cmd (@dns_queue) {
  934. my $fqdn = '';
  935. my $fqdn_ip = '';
  936. my $fqdn_parent = '';
  937. my $static_exists = 0;
  938. my $static_ref = '';
  939. my $static_ok = 0;
  940. eval {
  941. if ($dns_cmd->{name_type}=~/^cname$/i) {
  942. #skip update unknown domain
  943. if ($dns_cmd->{name} =~/\.$/ or $dns_cmd->{value} =~/\.$/) { next; }
  944. $fqdn=lc($dns_cmd->{name});
  945. $fqdn=~s/\.$ad_zone$//i;
  946. # $fqdn=~s/\.$//;
  947. if ($dns_cmd->{value}) {
  948. $fqdn_parent=lc($dns_cmd->{value});
  949. $fqdn_parent=~s/\.$ad_zone$//i;
  950. # $fqdn_parent=~s/\.$//;
  951. }
  952. $fqdn = $fqdn.".".$ad_zone;
  953. $fqdn_parent = $fqdn_parent.".".$ad_zone;
  954. #remove cname
  955. if ($dns_cmd->{type} eq 'del') {
  956. delete_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  957. }
  958. #create cname
  959. if ($dns_cmd->{type} eq 'add') {
  960. create_dns_cname($fqdn_parent,$fqdn,$ad_zone,$ad_dns,$hdb);
  961. }
  962. }
  963. if ($dns_cmd->{name_type}=~/^a$/i) {
  964. #skip update unknown domain
  965. if ($dns_cmd->{name} =~/\.$/ or $dns_cmd->{value} =~/\.$/) { next; }
  966. $fqdn=lc($dns_cmd->{name});
  967. $fqdn=~s/\.$ad_zone$//i;
  968. # $fqdn=~s/\.$//;
  969. if (!$dns_cmd->{value}) { next; }
  970. $fqdn_ip=lc($dns_cmd->{value});
  971. $fqdn = $fqdn.".".$ad_zone;
  972. #dns update disabled?
  973. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  974. if (!$maybe_update_dns) {
  975. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  976. next;
  977. }
  978. #get aliases
  979. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_id);
  980. #remove A & PTR
  981. if ($dns_cmd->{type} eq 'del') {
  982. #remove aliases
  983. if (@aliases and scalar @aliases) {
  984. foreach my $alias (@aliases) {
  985. delete_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  986. delete_dns_hostname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  987. }
  988. }
  989. #remove main record
  990. delete_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  991. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  992. }
  993. #create A & PTR
  994. if ($dns_cmd->{type} eq 'add') {
  995. my @dns_record=ResolveNames($fqdn,$dns_server);
  996. $static_exists = (scalar @dns_record>0);
  997. if ($static_exists) {
  998. $static_ref = join(' ',@dns_record);
  999. foreach my $dns_a (@dns_record) {
  1000. if ($dns_a=~/^$fqdn_ip$/) { $static_ok = 1; }
  1001. }
  1002. db_log_debug($hdb,"Dns record for static record $fqdn: $static_ref");
  1003. }
  1004. #skip update if already exists
  1005. if ($static_ok) {
  1006. db_log_debug($hdb,"Static record for $fqdn [$static_ok] correct.");
  1007. next;
  1008. }
  1009. #create record
  1010. create_dns_hostname($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1011. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1012. #create aliases
  1013. if (@aliases and scalar @aliases) {
  1014. foreach my $alias (@aliases) {
  1015. create_dns_cname($fqdn,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1016. }
  1017. }
  1018. }
  1019. }
  1020. #PTR
  1021. if ($dns_cmd->{name_type}=~/^ptr$/i) {
  1022. $fqdn=lc($dns_cmd->{name});
  1023. $fqdn=~s/\.$ad_zone$//i;
  1024. # $fqdn=~s/\.$//;
  1025. if (!$dns_cmd->{value}) { next; }
  1026. $fqdn_ip=lc($dns_cmd->{value});
  1027. #skip update unknown domain
  1028. if ($fqdn =~/\.$/) { next; }
  1029. $fqdn = $fqdn.".".$ad_zone;
  1030. #dns update disabled?
  1031. my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
  1032. if (!$maybe_update_dns) {
  1033. db_log_info($hdb,"FOUND Auth_id: $auth_id. DNS update disabled.");
  1034. next;
  1035. }
  1036. #remove A & PTR
  1037. if ($dns_cmd->{type} eq 'del') {
  1038. #remove main record
  1039. delete_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1040. }
  1041. #create A & PTR
  1042. if ($dns_cmd->{type} eq 'add') {
  1043. #create record
  1044. create_dns_ptr($fqdn,$fqdn_ip,$ad_zone,$ad_dns,$hdb);
  1045. }
  1046. }
  1047. };
  1048. if ($@) { log_error("Error dns commands: $@"); }
  1049. }
  1050. }
  1051. #---------------------------------------------------------------------------------------------------------------
  1052. sub is_ad_computer {
  1053. my $hdb = shift;
  1054. my $computer_name = shift;
  1055. if (!$computer_name or $computer_name =~/UNDEFINED/i) { return 0; }
  1056. my $ad_check = get_option($hdb,73);
  1057. if (!$ad_check) { return 1; }
  1058. my $ad_zone = get_option($hdb,33);
  1059. if ($computer_name =~/\./) {
  1060. if ($computer_name!~/\.$ad_zone$/i) {
  1061. db_log_verbose($hdb,"The domain of the computer $computer_name does not match the domain of the organization $ad_zone. Skip update.");
  1062. return 0;
  1063. }
  1064. }
  1065. if ($computer_name =~/^(.+)\./) {
  1066. $computer_name = $1;
  1067. }
  1068. my $ad_computer_name = trim($computer_name).'$';
  1069. my $name_in_cache = get_record_sql($hdb,"SELECT * FROM ad_comp_cache WHERE name='".$computer_name."'");
  1070. if ($name_in_cache) { return 1; }
  1071. my %name_found=do_exec_ref('/usr/bin/getent passwd '.$ad_computer_name);
  1072. if (!$name_found{output} or $name_found{status} ne 0) {
  1073. db_log_verbose($hdb,"The computer ".uc($ad_computer_name)." was not found in the domain $ad_zone. Skip update.");
  1074. return 0;
  1075. }
  1076. do_sql($hdb,"INSERT INTO ad_comp_cache(name) VALUES('".$computer_name."') ON DUPLICATE KEY UPDATE name='".$computer_name."';");
  1077. return 1;
  1078. }
  1079. #---------------------------------------------------------------------------------------------------------------
  1080. sub update_dns_record_by_dhcp {
  1081. my $hdb = shift;
  1082. my $dhcp_record = shift;
  1083. my $auth_record = shift;
  1084. return if (!$config_ref{enable_dns_updates});
  1085. my $ad_zone = get_option($hdb,33);
  1086. my $ad_dns = get_option($hdb,3);
  1087. $update_hostname_from_dhcp = get_option($hdb,46) || 0;
  1088. my $subnets_dhcp = get_subnets_ref($hdb);
  1089. my $enable_ad_dns_update = ($ad_zone and $ad_dns and $update_hostname_from_dhcp);
  1090. log_debug("Dhcp record: ".Dumper($dhcp_record));
  1091. log_debug("Subnets: ".Dumper($subnets_dhcp->{$dhcp_record->{network}->{subnet}}));
  1092. log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
  1093. 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});
  1094. 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)));
  1095. if (!$maybe_update_dns) {
  1096. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id}. DNS update don't needed.");
  1097. return 0;
  1098. }
  1099. log_debug("DNS update enabled.");
  1100. #update dns block
  1101. my $fqdn_static;
  1102. if ($auth_record->{dns_name}) {
  1103. $fqdn_static=lc($auth_record->{dns_name});
  1104. if ($fqdn_static!~/\.$ad_zone$/i) {
  1105. $fqdn_static=~s/\.$//;
  1106. $fqdn_static=lc($fqdn_static.'.'.$ad_zone);
  1107. }
  1108. }
  1109. my $fqdn=lc(trim($dhcp_record->{hostname_utf8}));
  1110. if ($fqdn!~/\.$ad_zone$/i) {
  1111. $fqdn=~s/\.$//;
  1112. $fqdn=lc($fqdn.'.'.$ad_zone);
  1113. }
  1114. db_log_debug($hdb,"FOUND Auth_id: $auth_record->{id} dns_name: $fqdn_static dhcp_hostname: $fqdn");
  1115. #check exists static dns name
  1116. my $static_exists = 0;
  1117. my $dynamic_exists = 0;
  1118. my $static_ok = 0;
  1119. my $dynamic_ok = 0;
  1120. my $static_ref;
  1121. my $dynamic_ref;
  1122. if ($fqdn_static ne '') {
  1123. my @dns_record=ResolveNames($fqdn_static,$dns_server);
  1124. $static_exists = (scalar @dns_record>0);
  1125. if ($static_exists) {
  1126. $static_ref = join(' ',@dns_record);
  1127. foreach my $dns_a (@dns_record) {
  1128. if ($dns_a=~/^$dhcp_record->{ip}$/) { $static_ok = $dns_a; }
  1129. }
  1130. }
  1131. } else { $static_ok = 1; }
  1132. if ($fqdn ne '') {
  1133. my @dns_record=ResolveNames($fqdn,$dns_server);
  1134. $dynamic_exists = (scalar @dns_record>0);
  1135. if ($dynamic_exists) {
  1136. $dynamic_ref = join(' ',@dns_record);
  1137. foreach my $dns_a (@dns_record) {
  1138. if ($dns_a=~/^$dhcp_record->{ip}$/) { $dynamic_ok = $dns_a; }
  1139. }
  1140. }
  1141. }
  1142. db_log_debug($hdb,"Dns record for static record $fqdn_static: $static_ok");
  1143. db_log_debug($hdb,"Dns record for dhcp-hostname $fqdn: $dynamic_ok");
  1144. if ($fqdn_static ne '') {
  1145. if (!$static_ok) {
  1146. db_log_info($hdb,"Static record mismatch! Expected $fqdn_static => $dhcp_record->{ip}, recivied: $static_ref");
  1147. if (!$static_exists) {
  1148. db_log_info($hdb,"Static dns hostname defined but not found. Create it ($fqdn_static => $dhcp_record->{ip})!");
  1149. create_dns_hostname($fqdn_static,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1150. }
  1151. } else {
  1152. db_log_debug($hdb,"Static record for $fqdn_static [$static_ok] correct.");
  1153. }
  1154. }
  1155. if ($fqdn ne '' and $dynamic_ok ne '') { db_log_debug($hdb,"Dynamic record for $fqdn [$dynamic_ok] correct. No changes required."); }
  1156. if ($fqdn ne '' and !$dynamic_ok) {
  1157. log_error("Dynamic record mismatch! Expected: $fqdn => $dhcp_record->{ip}, recivied: $dynamic_ref. Checking the status.");
  1158. #check exists hostname
  1159. my $another_hostname_exists = 0;
  1160. my $hostname_filter = ' LOWER(dns_name) REGEXP("^'.lc($dhcp_record->{hostname_utf8}).'\.*$")';
  1161. if ($fqdn_static ne '' and $fqdn !~/$fqdn_static/) {
  1162. $hostname_filter = $hostname_filter . ' or LOWER(dns_name) REGEXP("^'.lc($auth_record->{dns_name}).'\.*$")';
  1163. }
  1164. #check exists another records with some static hostname
  1165. my $filter_sql = 'SELECT * FROM User_auth WHERE id<>'.$auth_record->{id}.' and deleted=0 and ('.$hostname_filter.') ORDER BY last_found DESC';
  1166. db_log_debug($hdb,"Search dhcp hostname by: ".$filter_sql);
  1167. my $name_record = get_record_sql($hdb,$filter_sql);
  1168. if ($name_record->{dns_name} =~/^$fqdn$/i or $name_record->{dns_name} =~/^$dhcp_record->{hostname_utf8}$/i) {
  1169. $another_hostname_exists = 1;
  1170. }
  1171. if (!$another_hostname_exists) {
  1172. if ($fqdn_static and $fqdn_static ne '') {
  1173. if ($fqdn_static!~/$fqdn/) {
  1174. db_log_info($hdb,"Hostname from dhcp request $fqdn differs from static dns hostname $fqdn_static. Ignore dynamic binding!");
  1175. # delete_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1176. # create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1177. }
  1178. } else {
  1179. db_log_info($hdb,"Rewrite aliases if exists for $fqdn => $dhcp_record->{ip}");
  1180. #get and remove aliases
  1181. my @aliases = get_records_sql($hdb,"SELECT * FROM User_auth_alias WHERE auth_id=".$auth_record->{id});
  1182. if (@aliases and scalar @aliases) {
  1183. foreach my $alias (@aliases) {
  1184. delete_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1185. }
  1186. }
  1187. db_log_info($hdb,"Static dns hostname not defined. Create dns record by dhcp request. $fqdn => $dhcp_record->{ip}");
  1188. create_dns_hostname($fqdn,$dhcp_record->{ip},$ad_zone,$ad_dns,$hdb);
  1189. if (@aliases and scalar @aliases) {
  1190. foreach my $alias (@aliases) {
  1191. create_dns_cname($fqdn_static,$alias->{alias},$ad_zone,$ad_dns,$hdb) if ($alias->{alias});
  1192. }
  1193. }
  1194. }
  1195. } else {
  1196. 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.");
  1197. }
  1198. }
  1199. #end update dns block
  1200. }
  1201. #------------------------------------------------------------------------------------------------------------
  1202. sub apply_device_lock {
  1203. my $db = shift;
  1204. my $device_id = shift;
  1205. my $iteration = shift || 0;
  1206. $iteration++;
  1207. if ($iteration>2) { return 0; }
  1208. 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);
  1209. if (!$dev) { return 0; }
  1210. if (!$dev->{'discovery_locked'}) { return set_lock_discovery($db,$device_id); }
  1211. #if timestamp undefined, set and return
  1212. if (!$dev->{'locked_timestamp'}) { return set_lock_discovery($db,$device_id); }
  1213. #wait for discovery
  1214. my $wait_time = $dev->{'locked_timestamp'} + 30 - time();
  1215. if ($wait_time<0) { return set_lock_discovery($db,$device_id); }
  1216. sleep($wait_time);
  1217. return apply_device_lock($db,$device_id,$iteration);
  1218. }
  1219. #------------------------------------------------------------------------------------------------------------
  1220. sub set_lock_discovery {
  1221. my $db = shift;
  1222. my $device_id = shift;
  1223. my $new;
  1224. $new->{'discovery_locked'} = 1;
  1225. $new->{'locked_timestamp'} = GetNowTime();
  1226. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1227. return 0;
  1228. }
  1229. #------------------------------------------------------------------------------------------------------------
  1230. sub unset_lock_discovery {
  1231. my $db = shift;
  1232. my $device_id = shift;
  1233. my $new;
  1234. $new->{'discovery_locked'} = 0;
  1235. $new->{'locked_timestamp'} = GetNowTime();
  1236. if (update_record($db,'devices',$new,'id='.$device_id)) { return 1; }
  1237. return 0;
  1238. }
  1239. #------------------------------------------------------------------------------------------------------------
  1240. sub create_dns_cname {
  1241. my $fqdn = shift;
  1242. my $alias = shift;
  1243. my $zone = shift;
  1244. my $server = shift;
  1245. my $db = shift;
  1246. #skip update domain controllers
  1247. if (!$db) {
  1248. log_info("DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn");
  1249. } else {
  1250. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1251. }
  1252. my $ad_zone = get_option($db,33);
  1253. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1254. my @add_dns;
  1255. if ($config_ref{dns_server_type}=~/windows/i) {
  1256. push(@add_dns,"gsstsig");
  1257. push(@add_dns,"server $server");
  1258. push(@add_dns,"zone $zone");
  1259. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1260. push(@add_dns,"send");
  1261. write_to_file($nsupdate_file,\@add_dns);
  1262. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1263. }
  1264. if ($config_ref{dns_server_type}=~/bind/i) {
  1265. push(@add_dns,"server $server");
  1266. push(@add_dns,"zone $zone");
  1267. push(@add_dns,"update add $alias 3600 cname $fqdn.");
  1268. push(@add_dns,"send");
  1269. write_to_file($nsupdate_file,\@add_dns);
  1270. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1271. }
  1272. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1273. }
  1274. #---------------------------------------------------------------------------------------------------------------
  1275. sub delete_dns_cname {
  1276. my $fqdn = shift;
  1277. my $alias = shift;
  1278. my $zone = shift;
  1279. my $server = shift;
  1280. my $db = shift;
  1281. if (!$db) {
  1282. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn ");
  1283. } else {
  1284. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server CNAME: $alias for $fqdn");
  1285. }
  1286. my $ad_zone = get_option($db,33);
  1287. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1288. my @add_dns;
  1289. if ($config_ref{dns_server_type}=~/windows/i) {
  1290. push(@add_dns,"gsstsig");
  1291. push(@add_dns,"server $server");
  1292. push(@add_dns,"zone $zone");
  1293. push(@add_dns,"update delete $alias cname ");
  1294. push(@add_dns,"send");
  1295. write_to_file($nsupdate_file,\@add_dns);
  1296. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1297. }
  1298. if ($config_ref{dns_server_type}=~/bind/i) {
  1299. push(@add_dns,"server $server");
  1300. push(@add_dns,"zone $zone");
  1301. push(@add_dns,"update delete $alias cname");
  1302. push(@add_dns,"send");
  1303. write_to_file($nsupdate_file,\@add_dns);
  1304. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1305. }
  1306. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1307. }
  1308. #------------------------------------------------------------------------------------------------------------
  1309. sub create_dns_hostname {
  1310. my $fqdn = shift;
  1311. my $ip = shift;
  1312. my $zone = shift;
  1313. my $server = shift;
  1314. my $db = shift;
  1315. #skip update domain controllers
  1316. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1317. if (!$db) {
  1318. log_info("DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  1319. } else {
  1320. db_log_info($db,"DNS-UPDATE: Add => Zone $zone Server: $server A: $fqdn IP: $ip");
  1321. }
  1322. my $ad_zone = get_option($db,33);
  1323. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1324. my @add_dns;
  1325. if ($config_ref{dns_server_type}=~/windows/i) {
  1326. push(@add_dns,"gsstsig");
  1327. push(@add_dns,"server $server");
  1328. push(@add_dns,"zone $zone");
  1329. push(@add_dns,"update add $fqdn 3600 A $ip");
  1330. push(@add_dns,"send");
  1331. write_to_file($nsupdate_file,\@add_dns);
  1332. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1333. }
  1334. if ($config_ref{dns_server_type}=~/bind/i) {
  1335. push(@add_dns,"server $server");
  1336. push(@add_dns,"zone $zone");
  1337. push(@add_dns,"update add $fqdn 3600 A $ip");
  1338. push(@add_dns,"send");
  1339. write_to_file($nsupdate_file,\@add_dns);
  1340. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1341. }
  1342. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1343. }
  1344. #---------------------------------------------------------------------------------------------------------------
  1345. sub delete_dns_hostname {
  1346. my $fqdn = shift;
  1347. my $ip = shift;
  1348. my $zone = shift;
  1349. my $server = shift;
  1350. my $db = shift;
  1351. #skip update domain controllers
  1352. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1353. if (!$db) {
  1354. log_info("DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1355. } else {
  1356. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn IP: $ip");
  1357. }
  1358. my $ad_zone = get_option($db,33);
  1359. my $nsupdate_file = "/tmp/".$fqdn."-nsupdate";
  1360. my @add_dns;
  1361. if ($config_ref{dns_server_type}=~/windows/i) {
  1362. push(@add_dns,"gsstsig");
  1363. push(@add_dns,"server $server");
  1364. push(@add_dns,"zone $zone");
  1365. push(@add_dns,"update delete $fqdn A");
  1366. push(@add_dns,"send");
  1367. write_to_file($nsupdate_file,\@add_dns);
  1368. do_exec('/usr/bin/kinit -k -t /opt/Eye/scripts/cfg/dns_updater.keytab dns_updater@'.uc($ad_zone).' && /usr/bin/nsupdate "'.$nsupdate_file.'"');
  1369. }
  1370. if ($config_ref{dns_server_type}=~/bind/i) {
  1371. push(@add_dns,"server $server");
  1372. push(@add_dns,"zone $zone");
  1373. push(@add_dns,"update delete $fqdn A");
  1374. push(@add_dns,"send");
  1375. write_to_file($nsupdate_file,\@add_dns);
  1376. do_exec('/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"');
  1377. }
  1378. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1379. }
  1380. #---------------------------------------------------------------------------------------------------------------
  1381. sub create_dns_ptr {
  1382. my $fqdn = shift;
  1383. my $ip = shift;
  1384. my $ad_zone = shift;
  1385. my $server = shift;
  1386. my $db = shift;
  1387. my $radr;
  1388. my $zone;
  1389. #skip update domain controllers
  1390. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1391. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1392. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1393. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1394. $zone = "$3.$2.$1.in-addr.arpa";
  1395. }
  1396. if (!$radr or !$zone) { return 0; }
  1397. if (!$db) { return 0; }
  1398. db_log_info($db,"DNS-UPDATE: Zone $zone Server: $server A: $fqdn PTR: $ip");
  1399. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1400. my @add_dns;
  1401. if ($config_ref{dns_server_type}=~/windows/i) {
  1402. push(@add_dns,"gsstsig");
  1403. push(@add_dns,"server $server");
  1404. push(@add_dns,"zone $zone");
  1405. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1406. push(@add_dns,"send");
  1407. write_to_file($nsupdate_file,\@add_dns);
  1408. 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.'"';
  1409. do_exec($run_cmd);
  1410. }
  1411. if ($config_ref{dns_server_type}=~/bind/i) {
  1412. push(@add_dns,"server $server");
  1413. push(@add_dns,"zone $zone");
  1414. push(@add_dns,"update add $radr 3600 PTR $fqdn.");
  1415. push(@add_dns,"send");
  1416. write_to_file($nsupdate_file,\@add_dns);
  1417. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1418. do_exec($run_cmd);
  1419. }
  1420. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1421. }
  1422. #---------------------------------------------------------------------------------------------------------------
  1423. sub delete_dns_ptr {
  1424. my $fqdn = shift;
  1425. my $ip = shift;
  1426. my $ad_zone = shift;
  1427. my $server = shift;
  1428. my $db = shift;
  1429. my $radr;
  1430. my $zone;
  1431. #skip update domain controllers
  1432. if ($fqdn=~/^dc[0-9]{1,2}\./i) { return; }
  1433. if ($ip =~ /([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})(\/[0-9]{1,2}){0,1}/) {
  1434. return 0 if($1 > 255 || $2 > 255 || $3 > 255 || $4 > 255);
  1435. $radr = "$4.$3.$2.$1.in-addr.arpa";
  1436. $zone = "$3.$2.$1.in-addr.arpa";
  1437. }
  1438. if (!$radr or !$zone) { return 0; }
  1439. if (!$db) { return 0 ; }
  1440. db_log_info($db,"DNS-UPDATE: Delete => Zone $zone Server: $server A: $fqdn PTR: $ip");
  1441. my $nsupdate_file = "/tmp/".$radr."-nsupdate";
  1442. my @add_dns;
  1443. if ($config_ref{dns_server_type}=~/windows/i) {
  1444. push(@add_dns,"gsstsig");
  1445. push(@add_dns,"server $server");
  1446. push(@add_dns,"zone $zone");
  1447. push(@add_dns,"update delete $radr PTR");
  1448. push(@add_dns,"send");
  1449. write_to_file($nsupdate_file,\@add_dns);
  1450. 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.'"';
  1451. do_exec($run_cmd);
  1452. }
  1453. if ($config_ref{dns_server_type}=~/bind/i) {
  1454. push(@add_dns,"server $server");
  1455. push(@add_dns,"zone $zone");
  1456. push(@add_dns,"update delete $radr PTR");
  1457. push(@add_dns,"send");
  1458. write_to_file($nsupdate_file,\@add_dns);
  1459. my $run_cmd = '/usr/bin/nsupdate -k /etc/bind/rndc.key "'.$nsupdate_file.'"';
  1460. do_exec($run_cmd);
  1461. }
  1462. if (-e "$nsupdate_file") { unlink "$nsupdate_file"; }
  1463. }
  1464. #---------------------------------------------------------------------------------------------------------------
  1465. sub new_user {
  1466. my $db = shift;
  1467. my $user_info = shift;
  1468. my $user;
  1469. if ($user_info->{mac}) {
  1470. $user->{login}=mac_splitted($user_info->{mac});
  1471. } else {
  1472. $user->{login}=$user_info->{ip};
  1473. }
  1474. if ($user_info->{dhcp_hostname}) { $user->{fio}=$user_info->{dhcp_hostname}; }
  1475. if (!$user->{fio}) { $user->{fio}=$user_info->{ip}; }
  1476. my $login_count = get_count_records($db,"User_list","(login LIKE '".$user->{login}."(%)') OR (login='".$user->{login}."')");
  1477. if ($login_count) { $login_count++; $user->{login} .="(".$login_count.")"; }
  1478. $user->{ou_id} = $user_info->{ou_id};
  1479. my $ou_info = get_record_sql($db,"SELECT * FROM OU WHERE id=".$user_info->{'ou_id'});
  1480. if ($ou_info) {
  1481. $user->{'enabled'} = $ou_info->{'enabled'};
  1482. $user->{'queue_id'} = $ou_info->{'queue_id'};
  1483. $user->{'filter_group_id'} = $ou_info->{'filter_group_id'};
  1484. }
  1485. my $result = insert_record($db,"User_list",$user);
  1486. if ($result and $config_ref{auto_mac_rule} and $user_info->{mac}) {
  1487. my $auth_rule;
  1488. $auth_rule->{user_id} = $result;
  1489. $auth_rule->{type} = 2;
  1490. $auth_rule->{rule} = mac_splitted($user_info->{mac});
  1491. insert_record($db,"auth_rules",$auth_rule);
  1492. }
  1493. return $result;
  1494. }
  1495. #---------------------------------------------------------------------------------------------------------------
  1496. sub get_ip_subnet {
  1497. my $db = shift;
  1498. my $ip = shift;
  1499. if (!$ip) { return; }
  1500. my $ip_aton = StrToIp($ip);
  1501. 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)");
  1502. return $user_subnet;
  1503. }
  1504. #---------------------------------------------------------------------------------------------------------------
  1505. sub find_mac_in_subnet {
  1506. my $db = shift;
  1507. my $ip = shift;
  1508. my $mac = shift;
  1509. if (!$ip or !$mac) { return; }
  1510. my $ip_subnet = get_ip_subnet($db, $ip);
  1511. if (!$ip_subnet) { return; }
  1512. 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");
  1513. my $auth_count = 0;
  1514. my $result;
  1515. $result->{'count'} = 0;
  1516. foreach my $row (@t_auth) {
  1517. next if (!$row);
  1518. $auth_count++;
  1519. $result->{'count'} = $auth_count;
  1520. $result->{items}{$auth_count} = $row;
  1521. }
  1522. return $result;
  1523. }
  1524. #---------------------------------------------------------------------------------------------------------------
  1525. sub resurrection_auth {
  1526. my $db = shift;
  1527. my $ip_record = shift;
  1528. my $ip = $ip_record->{'ip'};
  1529. my $mac = $ip_record->{'mac'};
  1530. my $action = $ip_record->{'type'};
  1531. my $hostname = $ip_record->{'hostname_utf8'};
  1532. my $client_id = $ip_record->{'client-id'};
  1533. if (!exists $ip_record->{ip_aton}) { $ip_record->{ip_aton}=StrToIp($ip); }
  1534. if (!exists $ip_record->{hotspot}) { $ip_record->{hotspot}=is_hotspot($db,$ip); }
  1535. my $auth_ident = "Found new ip-address: " . $ip;
  1536. $auth_ident = $auth_ident . '['.$mac .']' if ($mac);
  1537. $auth_ident = $auth_ident . ' :: '.$hostname if ($hostname);
  1538. my $ip_aton=$ip_record->{ip_aton};
  1539. my $timestamp=GetNowTime();
  1540. my $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton.' AND `mac`="'.$mac.'"');
  1541. my $new_record;
  1542. $new_record->{last_found}=$timestamp;
  1543. $new_record->{arp_found}=$timestamp;
  1544. if ($client_id) { $new_record->{'client-id'} = $client_id; }
  1545. #auth found?
  1546. if ($record->{user_id}) {
  1547. #update timestamp and return
  1548. if ($action=~/^(add|old|del)$/i) {
  1549. $new_record->{dhcp_action}=$action;
  1550. $new_record->{created_by}='dhcp';
  1551. $new_record->{dhcp_time}=$timestamp;
  1552. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1553. }
  1554. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1555. return $record->{id};
  1556. }
  1557. my $user_subnet=$office_networks->match_string($ip);
  1558. if ($user_subnet->{static}) {
  1559. db_log_warning($db,"Unknown ip+mac found in static subnet! Abort create record for ip: $ip mac: [".$mac."]");
  1560. return 0;
  1561. }
  1562. my $send_alert_update = isNotifyUpdate(get_notify_subnet($db,$ip));
  1563. my $send_alert_create = isNotifyCreate(get_notify_subnet($db,$ip));
  1564. #my $send_alert_delete = isNotifyDelete(get_notify_subnet($db,$ip));
  1565. my $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1566. my $msg = '';
  1567. #search changed mac
  1568. $record=get_record_sql($db,'SELECT * FROM User_auth WHERE `ip_int`='.$ip_aton." and deleted=0");
  1569. if ($record->{id}) {
  1570. #if found record with same ip but without mac - update it
  1571. if (!$record->{mac}) {
  1572. $msg = $auth_ident. "\nUse auth record with no mac: " . hash_to_text($record);
  1573. db_log_verbose($db,$msg);
  1574. $new_record->{mac}=$mac;
  1575. #disable dhcp for same mac in one ip subnet
  1576. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1577. if ($action=~/^(add|old|del)$/i) {
  1578. $new_record->{dhcp_action}=$action;
  1579. $new_record->{dhcp_time}=$timestamp;
  1580. $new_record->{created_by}='dhcp';
  1581. if ($hostname) { $new_record->{dhcp_hostname} = $hostname; }
  1582. }
  1583. update_record($db,'User_auth',$new_record,"id=$record->{id}");
  1584. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert_update);
  1585. return $record->{id};
  1586. }
  1587. #if found record with same ip but another mac - delete old record
  1588. if ($record->{mac}) {
  1589. if (!$ip_record->{hotspot}) {
  1590. my $msg = "For ip: $ip mac change detected! Old mac: [".$record->{mac}."] New mac: [".$mac."]. Disable old auth_id: $record->{id}";
  1591. db_log_warning($db,$msg,$record->{id});
  1592. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert_update);
  1593. }
  1594. delete_user_auth($db,$record->{id});
  1595. }
  1596. }
  1597. #default user
  1598. my $new_user_info=get_new_user_id($db,$ip,$mac,$hostname);
  1599. my $new_user_id;
  1600. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1601. if (!$new_user_id) { $new_user_id = new_user($db,$new_user_info); }
  1602. if ($mac_exists) {
  1603. #deleting the user's entry if the address belongs to a dynamic group
  1604. foreach my $dup_record_id (keys %{$mac_exists->{items}}) {
  1605. my $dup_record = $mac_exists->{items}{$dup_record_id};
  1606. next if (!$dup_record);
  1607. #remove old dynamic record with some mac
  1608. if ($dup_record->{dynamic}) {
  1609. delete_user_auth($db,$dup_record->{id});
  1610. }
  1611. }
  1612. }
  1613. #recheck
  1614. $mac_exists=find_mac_in_subnet($db,$ip,$mac);
  1615. #disable dhcp for same mac in one ip subnet
  1616. if ($mac_exists and $mac_exists->{'count'}) { $new_record->{dhcp}=0; }
  1617. #seek old auth with same ip and mac
  1618. my $auth_exists=get_count_records($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1619. $new_record->{ip_int}=$ip_aton;
  1620. $new_record->{ip}=$ip;
  1621. $new_record->{mac}=$mac;
  1622. $new_record->{user_id}=$new_user_id;
  1623. $new_record->{save_traf}="$save_detail";
  1624. $new_record->{deleted}="0";
  1625. if ($action=~/^(add|old|del)$/i) {
  1626. $new_record->{dhcp_action}=$action;
  1627. $new_record->{dhcp_time}=$timestamp;
  1628. $new_record->{created_by}='dhcp';
  1629. } else {
  1630. $new_record->{created_by}=$action;
  1631. }
  1632. my $cur_auth_id= 0;
  1633. if ($auth_exists) {
  1634. #found ->Resurrection old record
  1635. my $resurrection_id = get_id_record($db,'User_auth',"ip_int=".$ip_aton." and mac='".$mac."'");
  1636. $msg = $auth_ident . " Resurrection auth_id: $resurrection_id with ip: $ip and mac: $mac";
  1637. if (!$ip_record->{hotspot}) { db_log_warning($db,$msg); } else { db_log_info($db,$msg); }
  1638. if (update_record($db,'User_auth',$new_record,"id=$resurrection_id")) { $cur_auth_id = $resurrection_id; }
  1639. } else {
  1640. #not found ->create new record
  1641. $msg = $auth_ident ."\n";
  1642. $cur_auth_id = insert_record($db,'User_auth',$new_record);
  1643. if ($cur_auth_id) {
  1644. if (!$ip_record->{hotspot}) { db_log_warning($db,$msg); } else { db_log_info($db,$msg); }
  1645. }
  1646. }
  1647. #filter and status
  1648. $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);
  1649. if ($cur_auth_id) {
  1650. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1651. if ($user_record) {
  1652. my $ou_info = get_record_sql($db,'SELECT * FROM OU WHERE id='.$user_record->{ou_id});
  1653. if ($ou_info and $ou_info->{'dynamic'}) {
  1654. # Устанавливаем значение по умолчанию, если не задано
  1655. if (!$ou_info->{'life_duration'}) {
  1656. $ou_info->{'life_duration'} = 24.0; # Явно указываем дробное число
  1657. }
  1658. my $now = DateTime->now(time_zone => 'local');
  1659. # Разбиваем life_duration на часы и минуты (для дробного значения)
  1660. my $hours = int($ou_info->{'life_duration'}); # Целая часть (часы)
  1661. my $minutes = ($ou_info->{'life_duration'} - $hours) * 60; # Дробная часть → минуты
  1662. # Создаём продолжительность с учётом дробных часов (в виде часов + минут)
  1663. my $duration = DateTime::Duration->new( hours => $hours, minutes => $minutes);
  1664. my $eof = $now + $duration;
  1665. $new_record->{'dynamic'} = 1;
  1666. $new_record->{'eof'} = $eof->strftime('%Y-%m-%d %H:%M:%S');
  1667. }
  1668. $new_record->{ou_id}=$user_record->{ou_id};
  1669. $new_record->{comments}=$user_record->{fio};
  1670. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1671. $new_record->{queue_id}=$user_record->{queue_id};
  1672. $new_record->{enabled}="$user_record->{enabled}";
  1673. update_record($db,'User_auth',$new_record,"id=$cur_auth_id");
  1674. }
  1675. db_log_warning($db, $msg, $cur_auth_id);
  1676. sendEmail("WARN! ".get_first_line($msg),$msg."\n".record_to_txt($db,'User_auth',$cur_auth_id),1) if ($send_alert_create);
  1677. } else { return; }
  1678. return $cur_auth_id;
  1679. }
  1680. #---------------------------------------------------------------------------------------------------------------
  1681. sub new_auth {
  1682. my $db = shift;
  1683. my $ip = shift;
  1684. my $ip_aton=StrToIp($ip);
  1685. my $record=get_record_sql($db,'SELECT id FROM User_auth WHERE `deleted`=0 AND `ip_int`='.$ip_aton);
  1686. if ($record->{id}) { return $record->{id}; }
  1687. #default user
  1688. my $new_user_info=get_new_user_id($db,$ip,undef,undef);
  1689. my $new_user_id;
  1690. if ($new_user_info->{user_id}) { $new_user_id = $new_user_info->{user_id}; }
  1691. if ($new_user_info->{ou_id}) { $new_user_id = new_user($db,$new_user_info); }
  1692. if (is_dynamic_ou($db,$new_user_info->{ou_id})) {
  1693. db_log_debug($db,"The ip-address $ip belongs to a dynamic group - ignore it.");
  1694. return;
  1695. }
  1696. my $send_alert = isNotifyCreate(get_notify_subnet($db,$ip));
  1697. my $user_record=get_record_sql($db,"SELECT * FROM User_list WHERE id=".$new_user_id);
  1698. my $timestamp=GetNowTime();
  1699. my $new_record;
  1700. $new_record->{ip_int}=$ip_aton;
  1701. $new_record->{ip}=$ip;
  1702. $new_record->{user_id}=$new_user_id;
  1703. $new_record->{save_traf}="$save_detail";
  1704. $new_record->{deleted}="0";
  1705. $new_record->{created_by}='netflow';
  1706. $new_record->{ou_id}=$user_record->{ou_id};
  1707. $new_record->{filter_group_id}=$user_record->{filter_group_id};
  1708. $new_record->{queue_id}=$user_record->{queue_id};
  1709. $new_record->{enabled}="$user_record->{enabled}";
  1710. if ($user_record->{fio}) { $new_record->{comments}=$user_record->{fio}; }
  1711. my $cur_auth_id=insert_record($db,'User_auth',$new_record);
  1712. if ($cur_auth_id) {
  1713. my $msg = "New ip created by netflow! ip: $ip";
  1714. db_log_warning($db,$msg,$cur_auth_id);
  1715. sendEmail("WARN! ".get_first_line($msg),$msg,1) if ($send_alert);
  1716. }
  1717. return $cur_auth_id;
  1718. }
  1719. #---------------------------------------------------------------------------------------------------------------
  1720. sub get_option {
  1721. my $db=shift;
  1722. my $option_id=shift;
  1723. return if (!$option_id);
  1724. return if (!$db);
  1725. my $default_option = get_record_sql($db,'SELECT * FROM config_options WHERE id='.$option_id);
  1726. my $config_options = get_record_sql($db,'SELECT * FROM config WHERE option_id='.$option_id);
  1727. my $result;
  1728. if (!$config_options) {
  1729. if ($default_option->{'type'}=~/^(int|bool)/i) { $result = $default_option->{'default_value'}*1; };
  1730. if ($default_option->{'type'}=~/^(string|text)/i) { $result = $default_option->{'default_value'}; }
  1731. if ($default_option->{'type'}=~/^list/i) { $result = $default_option->{'default_value'}; }
  1732. return $result;
  1733. }
  1734. $result = $config_options->{'value'};
  1735. return $result;
  1736. }
  1737. #---------------------------------------------------------------------------------------------------------------
  1738. sub init_option {
  1739. my $db=shift;
  1740. $last_refresh_config = time();
  1741. $config_ref{version}='';
  1742. my $version_record = get_record_sql($db,"SELECT version FROM version WHERE version is NOT NULL");
  1743. if ($version_record) { $config_ref{version}=$version_record->{version}; }
  1744. $config_ref{self_ip} = '127.0.0.1';
  1745. if ($DBHOST ne '127.0.0.1') {
  1746. my $ip_route = qx(ip r get $DBHOST 2>&1 | head -1);
  1747. if ($? == 0) {
  1748. if ($ip_route =~ /src\s+(\d+\.\d+\.\d+\.\d+)/) { $config_ref{self_ip} = $1; }
  1749. }
  1750. }
  1751. $config_ref{dbh}=$db;
  1752. $config_ref{save_detail}=get_option($db,23);
  1753. $config_ref{add_unknown_user}=get_option($db,22);
  1754. $config_ref{dhcp_server}=get_option($db,5);
  1755. $config_ref{snmp_default_version}=get_option($db,9);
  1756. $config_ref{snmp_default_community}=get_option($db,11);
  1757. $config_ref{KB}=get_option($db,1);
  1758. if ($config_ref{KB} ==0) { $config_ref{KB}=1000; }
  1759. if ($config_ref{KB} ==1) { $config_ref{KB}=1024; }
  1760. $config_ref{admin_email}=get_option($db,21);
  1761. $config_ref{sender_email}=get_option($db,52);
  1762. $config_ref{send_email}=get_option($db,51);
  1763. $config_ref{history}=get_option($db,26);
  1764. $config_ref{history_dhcp}=get_option($db,27);
  1765. $config_ref{router_login}=get_option($db,28);
  1766. $config_ref{router_password}=get_option($db,29);
  1767. $config_ref{router_port}=get_option($db,30);
  1768. $config_ref{org_name}=get_option($db,32);
  1769. $config_ref{domain_name}=get_option($db,33);
  1770. $config_ref{connections_history}=get_option($db,35);
  1771. $config_ref{debug}=get_option($db,34);
  1772. $config_ref{log_level} = get_option($db,53);
  1773. if ($config_ref{debug}) { $config_ref{log_level} = 255; }
  1774. $config_ref{urgent_sync}=get_option($db,50);
  1775. $config_ref{ignore_hotspot_dhcp_log} = get_option($db,44);
  1776. $config_ref{ignore_update_dhcp_event} = get_option($db,45);
  1777. $config_ref{update_hostname_from_dhcp} = get_option($db,46);
  1778. $config_ref{history_log_day}=get_option($db,47);
  1779. $config_ref{history_syslog_day} = get_option($db,48);
  1780. $config_ref{history_trafstat_day} = get_option($db,49);
  1781. $config_ref{enable_quotes} = get_option($db,54);
  1782. $config_ref{netflow_step} = get_option($db,55);
  1783. $config_ref{traffic_ipstat_history} = get_option($db,56);
  1784. $config_ref{nagios_url} = get_option($db,57);
  1785. $config_ref{cacti_url} = get_option($db,58);
  1786. $config_ref{torrus_url} = get_option($db,59);
  1787. $config_ref{wiki_url} = get_option($db,60);
  1788. $config_ref{stat_url} = get_option($db,62);
  1789. $config_ref{wiki_path} = get_option($db,61);
  1790. $config_ref{auto_mac_rule} = get_option($db,64);
  1791. #network configuration mode
  1792. $config_ref{config_mode}=get_option($db,68);
  1793. #auto clean old user record
  1794. $config_ref{clean_empty_user}=get_option($db,69);
  1795. #dns_server_type
  1796. $config_ref{dns_server}=get_option($db,3);
  1797. $config_ref{dns_server_type}=get_option($db,70);
  1798. $config_ref{enable_dns_updates}=get_option($db,71);
  1799. #$save_detail = 1; id=23
  1800. $save_detail=get_option($db,23);
  1801. #$add_unknown_user = 1; id=22
  1802. $add_unknown_user=get_option($db,22);
  1803. #$dns_server='192.168.2.12'; id=3
  1804. $dns_server=get_option($db,3);
  1805. #$dhcp_server='192.168.2.12'; id=5
  1806. $dhcp_server=get_option($db,5);
  1807. #$snmp_default_version='2'; id=9
  1808. $snmp_default_version=get_option($db,9);
  1809. #$snmp_default_community='public'; id=11
  1810. $snmp_default_community=get_option($db,11);
  1811. #$KB=1024; id=1
  1812. $KB=$config_ref{KB};
  1813. #$admin_email; id=21
  1814. $admin_email=get_option($db,21);
  1815. #sender email
  1816. $sender_email=get_option($db,52);
  1817. #send email
  1818. $send_email=get_option($db,51);
  1819. #$history=15; id=26
  1820. $history=get_option($db,26);
  1821. #$history_dhcp=7; id=27
  1822. $history_dhcp=get_option($db,27);
  1823. #$router_login="admin"; id=28
  1824. $router_login=get_option($db,28);
  1825. #$router_password="admin"; id=29
  1826. $router_password=get_option($db,29);
  1827. #$router_port=23; id=30
  1828. $router_port=get_option($db,30);
  1829. #32
  1830. $org_name=get_option($db,32);
  1831. #33
  1832. $domain_name=get_option($db,33);
  1833. #35
  1834. $connections_history=get_option($db,35);
  1835. #debug
  1836. $debug=get_option($db,34);
  1837. #log level
  1838. $log_level = get_option($db,53);
  1839. if ($debug) { $log_level = 255; }
  1840. #urgent sync access
  1841. $urgent_sync=get_option($db,50);
  1842. $ignore_hotspot_dhcp_log = get_option($db,44);
  1843. $ignore_update_dhcp_event = get_option($db,45);
  1844. $update_hostname_from_dhcp = get_option($db,46);
  1845. $history_log_day=get_option($db,47);
  1846. $history_syslog_day = get_option($db,48);
  1847. $history_trafstat_day = get_option($db,49);
  1848. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1849. if (!$ou) { $default_user_ou_id = 0; } else { $default_user_ou_id = $ou->{'id'}; }
  1850. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1851. if (!$ou) { $default_hotspot_ou_id = $default_user_ou_id; } else { $default_hotspot_ou_id = $ou->{'id'}; }
  1852. @subnets=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1853. if (defined $office_networks) { undef $office_networks; }
  1854. if (defined $free_networks) { undef $free_networks; }
  1855. if (defined $vpn_networks) { undef $vpn_networks; }
  1856. if (defined $hotspot_networks) { undef $hotspot_networks; }
  1857. if (defined $all_networks) { undef $all_networks; }
  1858. $office_networks = new Net::Patricia;
  1859. $free_networks = new Net::Patricia;
  1860. $vpn_networks = new Net::Patricia;
  1861. $hotspot_networks = new Net::Patricia;
  1862. $all_networks = new Net::Patricia;
  1863. @office_network_list=();
  1864. @free_network_list=();
  1865. @free_network_list=();
  1866. @vpn_network_list=();
  1867. @hotspot_network_list=();
  1868. @all_network_list=();
  1869. foreach my $net (@subnets) {
  1870. next if (!$net->{subnet});
  1871. $subnets_ref{$net->{subnet}}=$net;
  1872. if ($net->{office}) {
  1873. push(@office_network_list,$net->{subnet});
  1874. $office_networks->add_string($net->{subnet},$net);
  1875. }
  1876. if ($net->{free}) {
  1877. push(@free_network_list,$net->{subnet});
  1878. $free_networks->add_string($net->{subnet},$net);
  1879. }
  1880. if ($net->{vpn}) {
  1881. push(@vpn_network_list,$net->{subnet});
  1882. $vpn_networks->add_string($net->{subnet},$net);
  1883. }
  1884. if ($net->{hotspot}) {
  1885. push(@hotspot_network_list,$net->{subnet});
  1886. push(@all_network_list,$net->{subnet});
  1887. $hotspot_networks->add_string($net->{subnet},$net);
  1888. }
  1889. push(@all_network_list,$net->{subnet});
  1890. $all_networks->add_string($net->{subnet},$net);
  1891. }
  1892. }
  1893. #--------------------------------------------------------------------------------------------------------------
  1894. sub get_dynamic_ou {
  1895. my $db = shift;
  1896. my @dynamic=();
  1897. my @ou_list = get_records_sql($db,"SELECT id FROM OU WHERE dynamic = 1");
  1898. foreach my $group (@ou_list) {
  1899. next if (!$group);
  1900. push(@dynamic,$group->{id});
  1901. }
  1902. return wantarray ? @dynamic : \@dynamic;
  1903. }
  1904. #--------------------------------------------------------------------------------------------------------------
  1905. sub get_default_ou {
  1906. my $db = shift;
  1907. my @dynamic=();
  1908. my $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_users = 1");
  1909. if (!$ou) { push(@dynamic,0); } else { push(@dynamic,$ou->{'id'}); }
  1910. $ou = get_record_sql($db,"SELECT id FROM OU WHERE default_hotspot = 1");
  1911. if ($ou) { push(@dynamic,$ou->{id}); }
  1912. return wantarray ? @dynamic : \@dynamic;
  1913. }
  1914. #--------------------------------------------------------------------------------------------------------------
  1915. sub is_dynamic_ou {
  1916. my $db = shift;
  1917. my $ou_id = shift;
  1918. my @dynamic=get_dynamic_ou($db);
  1919. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1920. return 0;
  1921. }
  1922. #--------------------------------------------------------------------------------------------------------------
  1923. sub is_default_ou {
  1924. my $db = shift;
  1925. my $ou_id = shift;
  1926. my @dynamic=get_default_ou($db);
  1927. if (in_array(\@dynamic,$ou_id)) { return 1; }
  1928. return 0;
  1929. }
  1930. #---------------------------------------------------------------------------------------------------------------
  1931. sub get_subnets_ref {
  1932. my $db = shift;
  1933. my @list=get_records_sql($db,'SELECT * FROM subnets ORDER BY ip_int_start');
  1934. my $list_ref;
  1935. foreach my $net (@list) {
  1936. next if (!$net->{subnet});
  1937. $list_ref->{$net->{subnet}}=$net;
  1938. }
  1939. return $list_ref;
  1940. }
  1941. #---------------------------------------------------------------------------------------------------------------
  1942. sub get_device_by_ip {
  1943. my $db = shift;
  1944. my $ip = shift;
  1945. my $netdev=get_record_sql($db,'SELECT * FROM devices WHERE ip="'.$ip.'"');
  1946. if ($netdev and $netdev->{id}>0) { return $netdev; }
  1947. my $auth_rec=get_record_sql($db,'SELECT user_id FROM User_auth WHERE ip="'.$ip.'" and deleted=0');
  1948. if ($auth_rec and $auth_rec->{user_id}>0) {
  1949. $netdev=get_record_sql($db,'SELECT * FROM devices WHERE user_id='.$auth_rec->{user_id});
  1950. return $netdev;
  1951. }
  1952. return;
  1953. }
  1954. #---------------------------------------------------------------------------------------------------------------
  1955. sub GetUnixTimeByStr {
  1956. my $time_str = shift;
  1957. $time_str =~s/\//-/g;
  1958. $time_str = trim($time_str);
  1959. my ($sec,$min,$hour,$day,$mon,$year) = (localtime())[0,1,2,3,4,5];
  1960. $year+=1900;
  1961. $mon++;
  1962. if ($time_str =~/^([0-9]{2,4})\-([0-9]{1,2})-([0-9]{1,2})\s+/) {
  1963. $year = $1; $mon = $2; $day = $3;
  1964. }
  1965. if ($time_str =~/([0-9]{1,2})\:([0-9]{1,2})\:([0-9]{1,2})$/) {
  1966. $hour = $1; $min = $2; $sec = $3;
  1967. }
  1968. my $result = mktime($sec,$min,$hour,$day,$mon-1,$year-1900);
  1969. return $result;
  1970. }
  1971. #---------------------------------------------------------------------------------------------------------------
  1972. sub GetTimeStrByUnixTime {
  1973. my $time = shift || time();
  1974. my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($time))[0,1,2,3,4,5];
  1975. my $result = strftime("%Y-%m-%d %H:%M:%S",$sec, $min, $hour, $mday, $mon, $year);
  1976. return $result;
  1977. }
  1978. #---------------------------------------------------------------------------------------------------------------
  1979. sub Set_Variable {
  1980. my $db = shift;
  1981. my $name = shift || $MY_NAME;
  1982. my $value = shift || $$;
  1983. my $timeshift = shift || 60;
  1984. Del_Variable($db,$name);
  1985. my $clean_variables = time() + $timeshift;
  1986. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  1987. $month++;
  1988. $year += 1900;
  1989. my $clean_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  1990. my $clean_variables_date=$db->quote($clean_str);
  1991. do_sql($db,"INSERT INTO variables(name,value,clear_time) VALUES('".$name."','".$value."',".$clean_variables_date.");");
  1992. }
  1993. #---------------------------------------------------------------------------------------------------------------
  1994. sub Get_Variable {
  1995. my $db = shift;
  1996. my $name = shift || $MY_NAME;
  1997. my $variable=get_record_sql($db,'SELECT `value` FROM `variables` WHERE name="'.$name.'"');
  1998. if (!$variable and $variable->{'value'}) { return $variable->{'value'}; }
  1999. return;
  2000. }
  2001. #---------------------------------------------------------------------------------------------------------------
  2002. sub Del_Variable {
  2003. my $db = shift;
  2004. my $name = shift || $MY_NAME;
  2005. do_sql($db,"DELETE FROM `variables` WHERE name='".$name."';");
  2006. }
  2007. #---------------------------------------------------------------------------------------------------------------
  2008. sub recalc_quotes {
  2009. my $db = shift;
  2010. my $calc_id = shift || $$;
  2011. return if (!get_option($db,54));
  2012. clean_variables($db);
  2013. return if (Get_Variable($db,'RECALC'));
  2014. my $timeshift = get_option($db,55);
  2015. Set_Variable($db,'RECALC',$calc_id,time()+$timeshift*60);
  2016. my $now = DateTime->now(time_zone=>'local');
  2017. my $day_start = $db->quote($now->ymd("-")." 00:00:00");
  2018. my $day_dur = DateTime::Duration->new( days => 1 );
  2019. my $tomorrow = $now+$day_dur;
  2020. my $day_stop = $db->quote($tomorrow->ymd("-")." 00:00:00");
  2021. $now->set(day=>1);
  2022. my $month_start=$db->quote($now->ymd("-")." 00:00:00");
  2023. my $month_dur = DateTime::Duration->new( months => 1 );
  2024. my $next_month = $now + $month_dur;
  2025. $next_month->set(day=>1);
  2026. my $month_stop = $db->quote($next_month->ymd("-")." 00:00:00");
  2027. #get user limits
  2028. 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";
  2029. my @authlist_ref = get_records_sql($db,$user_auth_list_sql);
  2030. my %user_stats;
  2031. my %auth_info;
  2032. foreach my $row (@authlist_ref) {
  2033. $auth_info{$row->{auth_id}}{user_id}=$row->{id};
  2034. $auth_info{$row->{auth_id}}{day_limit}=$row->{auth_day};
  2035. $auth_info{$row->{auth_id}}{month_limit}=$row->{auth_month};
  2036. $auth_info{$row->{auth_id}}{day}=0;
  2037. $auth_info{$row->{auth_id}}{month}=0;
  2038. $user_stats{$row->{id}}{day_limit}=$row->{day_quota};
  2039. $user_stats{$row->{id}}{month_limit}=$row->{month_quota};
  2040. $user_stats{$row->{id}}{day}=0;
  2041. $user_stats{$row->{id}}{month}=0;
  2042. }
  2043. #recalc quotes - global
  2044. #day
  2045. my $day_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  2046. WHERE User_stats.`timestamp`>= $day_start AND User_stats.`timestamp`< $day_stop GROUP BY User_stats.auth_id";
  2047. my @day_stats = get_records_sql($db,$day_sql);
  2048. foreach my $row (@day_stats) {
  2049. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  2050. $auth_info{$row->{auth_id}}{day}=$row->{traf_all};
  2051. $user_stats{$user_id}{day}+=$row->{traf_all};
  2052. }
  2053. #month
  2054. my $month_sql="SELECT User_stats.auth_id, SUM( byte_in + byte_out ) AS traf_all FROM User_stats
  2055. WHERE User_stats.`timestamp`>= $month_start AND User_stats.`timestamp`< $month_stop GROUP BY User_stats.auth_id";
  2056. my @month_stats = get_records_sql($db,$month_sql);
  2057. foreach my $row (@month_stats) {
  2058. my $user_id=$auth_info{$row->{auth_id}}{user_id};
  2059. $auth_info{$row->{auth_id}}{month}=$row->{traf_all};
  2060. $user_stats{$user_id}{month}+=$row->{traf_all};
  2061. }
  2062. foreach my $auth_id (keys %auth_info) {
  2063. next if (!$auth_info{$auth_id}{day_limit});
  2064. next if (!$auth_info{$auth_id}{month_limit});
  2065. my $day_limit=$auth_info{$auth_id}{day_limit}*$KB*$KB;
  2066. my $month_limit=$auth_info{$auth_id}{month_limit}*$KB*$KB;
  2067. my $blocked_d=($auth_info{$auth_id}{day}>$day_limit);
  2068. my $blocked_m=($auth_info{$auth_id}{month}>$month_limit);
  2069. if ($blocked_d or $blocked_m) {
  2070. my $history_msg;
  2071. 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; }
  2072. 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; }
  2073. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where id=$auth_id");
  2074. db_log_verbose($db,$history_msg);
  2075. }
  2076. }
  2077. foreach my $user_id (keys %user_stats) {
  2078. next if (!$user_stats{$user_id}{day_limit});
  2079. next if (!$user_stats{$user_id}{month_limit});
  2080. my $day_limit=$user_stats{$user_id}{day_limit}*$KB*$KB;
  2081. my $month_limit=$user_stats{$user_id}{month_limit}*$KB*$KB;
  2082. my $blocked_d=($user_stats{$user_id}{day}>$day_limit);
  2083. my $blocked_m=($user_stats{$user_id}{month}>$month_limit);
  2084. if ($blocked_d or $blocked_m) {
  2085. my $history_msg;
  2086. 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; }
  2087. 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; }
  2088. do_sql($db,"UPDATE User_user set blocked=1 where id=$user_id");
  2089. do_sql($db,"UPDATE User_auth set blocked=1, changed=1 where user_id=$user_id");
  2090. db_log_verbose($db,$history_msg);
  2091. }
  2092. }
  2093. Del_Variable($db,'RECALC');
  2094. }
  2095. #---------------------------------------------------------------------------------------------------------------
  2096. sub clean_variables {
  2097. my $db = shift;
  2098. #clean temporary variables
  2099. my $clean_variables = time();
  2100. my ($sec,$min,$hour,$day,$month,$year,$zone) = localtime($clean_variables);
  2101. $month++;
  2102. $year += 1900;
  2103. my $now_str=sprintf "%04d-%02d-%02d %02d:%02d:%02d",$year,$month,$day,$hour,$min,$sec;
  2104. my $clean_variables_date=$db->quote($now_str);
  2105. do_sql($db,"DELETE FROM `variables` WHERE clear_time<=$clean_variables_date");
  2106. #clean old AD computer cache
  2107. my $now = DateTime->now(time_zone=>'local');
  2108. my $day_dur = DateTime::Duration->new( days => 1 );
  2109. my $clean_date = $now - $day_dur;
  2110. my $clean_str = $dbh->quote($clean_date->ymd("-")." 00:00:00");
  2111. do_sql($db,"DELETE FROM `ad_comp_cache` WHERE last_found<=$clean_str");
  2112. }
  2113. #--------------------------------------------------------------------------------
  2114. sub process_dhcp_request {
  2115. my ($db, $type, $mac, $ip, $hostname, $client_id, $circuit_id, $remote_id) = @_;
  2116. return if (!$type);
  2117. return if ($type!~/(old|add|del)/i);
  2118. my $client_hostname='';
  2119. if ($hostname and ($hostname ne "undef" or $hostname !~ /UNDEFINED/i)) { $client_hostname=$hostname; }
  2120. my $auth_network = $office_networks->match_string($ip);
  2121. if (!$auth_network) {
  2122. log_error("Unknown network in dhcp request! IP: $ip");
  2123. return;
  2124. }
  2125. if (!$circuit_id) { $circuit_id=''; }
  2126. if (!$client_id) { $client_id = ''; }
  2127. if (!$remote_id) { $remote_id = ''; }
  2128. my $timestamp=time();
  2129. my $ip_aton=StrToIp($ip);
  2130. $mac=mac_splitted(isc_mac_simplify($mac));
  2131. my $dhcp_event_time = GetNowTime($timestamp);
  2132. my $dhcp_record;
  2133. $dhcp_record->{'mac'}=$mac;
  2134. $dhcp_record->{'ip'}=$ip;
  2135. $dhcp_record->{'ip_aton'}=$ip_aton;
  2136. $dhcp_record->{'hostname'}=$client_hostname;
  2137. $dhcp_record->{'network'}=$auth_network;
  2138. $dhcp_record->{'type'}=$type;
  2139. $dhcp_record->{'hostname_utf8'}=$client_hostname;
  2140. $dhcp_record->{'timestamp'} = $timestamp;
  2141. $dhcp_record->{'last_time'} = time();
  2142. $dhcp_record->{'circuit-id'} = $circuit_id;
  2143. $dhcp_record->{'client-id'} = $client_id;
  2144. $dhcp_record->{'remote-id'} = $remote_id;
  2145. $dhcp_record->{'hotspot'}=is_hotspot($dbh,$dhcp_record->{ip});
  2146. #search actual record
  2147. 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');
  2148. #if record not found and type del => next event
  2149. if (!$auth_record and $type eq 'del') { return; }
  2150. #if record not found - create it
  2151. if (!$auth_record and $type=~/(add|old)/i) {
  2152. # db_log_warning($db,"Record for dhcp request type: ".$type." ip=".$dhcp_record->{ip}." and mac=".$mac." does not exists!");
  2153. my $res_id = resurrection_auth($db,$dhcp_record);
  2154. if (!$res_id) { db_log_error($db,"Error creating an ip address record for ip=".$dhcp_record->{ip}." and mac=".$mac."!"); return; }
  2155. $auth_record = get_record_sql($db,'SELECT * FROM User_auth WHERE id='.$res_id);
  2156. db_log_info($db,"Check for new auth. Found id: $res_id",$res_id);
  2157. }
  2158. my $auth_id = $auth_record->{id};
  2159. my $auth_ou_id = $auth_record->{ou_id};
  2160. $dhcp_record->{'auth_id'} = $auth_id;
  2161. $dhcp_record->{'auth_ou_id'} = $auth_ou_id;
  2162. log_debug(uc($type).">>");
  2163. log_debug("MAC: ".$dhcp_record->{'mac'});
  2164. log_debug("IP: ".$dhcp_record->{'ip'});
  2165. log_debug("CIRCUIT-ID: ".$dhcp_record->{'circuit-id'});
  2166. log_debug("REMOTE-ID: ".$dhcp_record->{'remote-id'});
  2167. log_debug("HOSTNAME: ".$dhcp_record->{'hostname'});
  2168. log_debug("TYPE: ".$dhcp_record->{'type'});
  2169. log_debug("TIME: ".$dhcp_event_time);
  2170. log_debug("AUTH_ID: ".$auth_id);
  2171. log_debug("END GET");
  2172. update_dns_record_by_dhcp($db,$dhcp_record,$auth_record);
  2173. if ($type=~/add/i and $dhcp_record->{hostname_utf8}) {
  2174. my $auth_rec;
  2175. $auth_rec->{dhcp_hostname} = $dhcp_record->{hostname_utf8};
  2176. $auth_rec->{dhcp_time}=$dhcp_event_time;
  2177. $auth_rec->{arp_found}=$dhcp_event_time;
  2178. $auth_rec->{created_by}='dhcp';
  2179. db_log_verbose($db,"Add lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  2180. update_record($db,'User_auth',$auth_rec,"id=$auth_id");
  2181. }
  2182. if ($type=~/old/i) {
  2183. my $auth_rec;
  2184. $auth_rec->{dhcp_action}=$type;
  2185. $auth_rec->{dhcp_time}=$dhcp_event_time;
  2186. $auth_rec->{created_by}='dhcp';
  2187. $auth_rec->{arp_found}=$dhcp_event_time;
  2188. db_log_verbose($db,"Update lease by dhcp event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  2189. update_record($db,'User_auth',$auth_rec,"id=$auth_id");
  2190. }
  2191. if ($type=~/del/i and $auth_id) {
  2192. if ($auth_record->{dhcp_time} =~ /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/) {
  2193. my $d_time = mktime($6,$5,$4,$3,$2-1,$1-1900);
  2194. if (time()-$d_time>60 and (is_dynamic_ou($db,$auth_ou_id) or is_default_ou($db,$auth_ou_id))) {
  2195. db_log_info($db,"Remove user ip record by dhcp release event for dynamic clients id: $auth_id ip: $dhcp_record->{ip}",$auth_id);
  2196. my $auth_rec;
  2197. $auth_rec->{dhcp_action}=$type;
  2198. $auth_rec->{dhcp_time}=$dhcp_event_time;
  2199. update_record($db,'User_auth',$auth_rec,"id=$auth_id");
  2200. #remove user auth record if it belongs to the default pool or it is dynamic
  2201. if (is_default_ou($db,$auth_ou_id) or (is_dynamic_ou($db,$auth_ou_id) and $auth_record->{dynamic})) {
  2202. delete_user_auth($db,$auth_id);
  2203. my $u_count=get_count_records($db,'User_auth','deleted=0 and user_id='.$auth_record->{'user_id'});
  2204. if (!$u_count) { delete_user($db,$auth_record->{'user_id'}); }
  2205. }
  2206. }
  2207. }
  2208. }
  2209. if ($dhcp_record->{hotspot} and $ignore_hotspot_dhcp_log) { return $dhcp_record; }
  2210. if ($ignore_update_dhcp_event and $type=~/old/i) { return $dhcp_record; }
  2211. my $dhcp_log;
  2212. if (!$auth_id) { $auth_id=0; }
  2213. $dhcp_log->{'auth_id'} = $auth_id;
  2214. $dhcp_log->{'ip'} = $dhcp_record->{'ip'};
  2215. $dhcp_log->{'ip_int'} = $dhcp_record->{'ip_aton'};
  2216. $dhcp_log->{'mac'} = $dhcp_record->{'mac'};
  2217. $dhcp_log->{'action'} = $type;
  2218. $dhcp_log->{'dhcp_hostname'} = $dhcp_record->{'hostname_utf8'};
  2219. $dhcp_log->{'timestamp'} = $dhcp_event_time;
  2220. $dhcp_log->{'circuit-id'} = $circuit_id;
  2221. $dhcp_log->{'client-id'} = $client_id;
  2222. $dhcp_log->{'remote-id'} = $remote_id;
  2223. insert_record($db,'dhcp_log',$dhcp_log);
  2224. return $dhcp_record;
  2225. }
  2226. #---------------------------------------------------------------------------------------------------------------
  2227. #skip init for upgrade
  2228. if ($MY_NAME!~/upgrade.pl/) {
  2229. $dbh=init_db();
  2230. init_option($dbh);
  2231. clean_variables($dbh);
  2232. Set_Variable($dbh);
  2233. }
  2234. 1;
  2235. }