소스 검색

added support for "foreign" domains. If the host name ends with a dot, then this entry will not be added to the office DNS.

root 11 달 전
부모
커밋
462a9ecc01

+ 50 - 0
docs/dhcpd/windows/dhcp_monitor.ps1

@@ -0,0 +1,50 @@
+# Параметры API
+$ApiHost = "STAT_IP_OR_HOSTNAME"  # Замените на IP/хост API-сервера
+$ApiLogin = "LOGIN"               # Логин для API
+$ApiKey = "API_CUSTOMER_KEY"      # API-ключ клиента
+
+# Функция отправки данных на API
+function Send-DhcpEventToApi {
+    param (
+        [string]$Mac,
+        [string]$Ip,
+        [string]$Action,
+        [string]$Hostname
+    )
+
+    # Формируем URL запроса
+    $ApiUrl = "http://$ApiHost/api.php?login=$ApiLogin&api_key=$ApiKey&send=dhcp&mac=$Mac&ip=$Ip&action=$Action&hostname=$Hostname"
+
+    try {
+        # Отправляем GET-запрос
+        $Response = Invoke-RestMethod -Uri $ApiUrl -Method Get -ErrorAction Stop
+        
+        # Логируем успешную отправку
+        Write-Host "[$(Get-Date)] DHCP Event Sent: MAC=$Mac, IP=$Ip, Action=$Action, Hostname=$Hostname"
+        Write-Host "API Response: $($Response | ConvertTo-Json -Compress)"
+    }
+    catch {
+        Write-Host "[ERROR] Failed to send DHCP event: $_" -ForegroundColor Red
+    }
+}
+
+# Основной цикл: мониторим события DHCP
+while ($true) {
+    # Получаем последние события DHCP (ID 10 = "Аренда выдана", ID 11 = "Аренда освобождена")
+    $Events = Get-WinEvent -LogName "Microsoft-Windows-DHCP-Server/Operational" -MaxEvents 10 -ErrorAction SilentlyContinue |
+              Where-Object { $_.Id -eq 10 -or $_.Id -eq 11 }
+
+    foreach ($Event in $Events) {
+        # Парсим параметры события
+        $Ip = $Event.Properties[0].Value
+        $Mac = $Event.Properties[1].Value
+        $Hostname = $Event.Properties[2].Value
+        $Action = if ($Event.Id -eq 10) { "add" } else { "del" }
+
+        # Отправляем данные на API
+        Send-DhcpEventToApi -Mac $Mac -Ip $Ip -Action $Action -Hostname $Hostname
+    }
+
+    # Пауза перед следующей проверкой (5 секунд)
+    Start-Sleep -Seconds 5
+}

+ 66 - 0
docs/dhcpd/windows/dhcp_sync.ps1

@@ -0,0 +1,66 @@
+# Параметры API
+$ApiUrl = "http://your-api-server.com/api/dhcp/reservations"
+$ApiKey = "ваш_api_ключ"
+$DhcpServer = "Ваш_DHCP_Сервер"
+
+# Получаем текущие резервирования DHCP
+$CurrentReservations = Get-DhcpServerv4Reservation -ComputerName $DhcpServer | 
+                       Select-Object IPAddress, ClientId, Name, Description
+
+# Получаем актуальные резервирования из API
+$Headers = @{ "Authorization" = "Bearer $ApiKey" }
+$ApiReservations = Invoke-RestMethod -Uri $ApiUrl -Method Get -Headers $Headers
+
+# Конвертируем MAC-адреса в единый формат (убираем разделители)
+$ApiReservations | ForEach-Object { 
+    $_.MAC = $_.MAC -replace '[:-]', ''
+}
+
+# Удаляем резервирования, которых нет в API
+foreach ($Reservation in $CurrentReservations) {
+    $MacFromDhcp = $Reservation.ClientId -replace '[:-]', ''
+    $MatchingApiEntry = $ApiReservations | Where-Object { $_.MAC -eq $MacFromDhcp }
+
+    if (-not $MatchingApiEntry) {
+        try {
+            Remove-DhcpServerv4Reservation -ComputerName $DhcpServer `
+                -IPAddress $Reservation.IPAddress `
+                -ErrorAction Stop
+            Write-Host "Удалено устаревшее резервирование: $($Reservation.IPAddress) ($($Reservation.ClientId))" -ForegroundColor Yellow
+        } catch {
+            Write-Host "Ошибка при удалении $($Reservation.IPAddress): $_" -ForegroundColor Red
+        }
+    }
+}
+
+# Добавляем/обновляем резервирования из API
+foreach ($ApiReservation in $ApiReservations) {
+    try {
+        # Проверяем, существует ли запись
+        $ExistingReservation = $CurrentReservations | Where-Object { 
+            ($_.ClientId -replace '[:-]', '') -eq $ApiReservation.MAC
+        }
+
+        if ($ExistingReservation) {
+            # Обновляем описание (если изменилось)
+            Set-DhcpServerv4Reservation -ComputerName $DhcpServer `
+                -IPAddress $ExistingReservation.IPAddress `
+                -ClientId $ApiReservation.MAC `
+                -Name $ApiReservation.Hostname `
+                -Description $ApiReservation.Description `
+                -ErrorAction Stop
+            Write-Host "Обновлено резервирование: $($ExistingReservation.IPAddress)"
+        } else {
+            # Добавляем новое
+            Add-DhcpServerv4Reservation -ComputerName $DhcpServer `
+                -IPAddress $ApiReservation.IP `
+                -ClientId $ApiReservation.MAC `
+                -Name $ApiReservation.Hostname `
+                -Description $ApiReservation.Description `
+                -ErrorAction Stop
+            Write-Host "Добавлено новое резервирование: $($ApiReservation.IP)"
+        }
+    } catch {
+        Write-Host "Ошибка при обработке $($ApiReservation.IP): $_" -ForegroundColor Red
+    }
+}

+ 3 - 0
docs/dhcpd/windows/install_srv.ps1

@@ -0,0 +1,3 @@
+# Установка службы через nssm (https://nssm.cc)
+nssm install "DHCP_Events_Monitor" "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-ExecutionPolicy Bypass -File C:\Scripts\dhcp_monitor.ps1"
+nssm start DHCP_Events_Monitor

+ 8 - 6
html/admin/users/edit_alias.php

@@ -31,6 +31,7 @@ if (isset($_POST["s_remove"])) {
 if (isset($_POST['s_save'])) {
     $len = is_array($_POST['s_save']) ? count($_POST['s_save']) : 0;
     $domain_zone = get_option($db_link, 33);
+    $domain_zone = ltrim($domain_zone, '.');
     for ($i = 0; $i < $len; $i ++) {
         $save_id = intval($_POST['s_save'][$i]);
         $len_all = is_array($_POST['n_id']) ? count($_POST['n_id']) : 0;
@@ -38,10 +39,10 @@ if (isset($_POST['s_save'])) {
             if (intval($_POST['n_id'][$j]) != $save_id) { continue; }
             $f_dnsname = trim($_POST['s_alias'][$j]);
             if (!empty($f_dnsname)) {
-                $f_dnsname = preg_replace('/'.$domain_zone.'/','',$f_dnsname);
-                $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
+                $f_dnsname = preg_replace('/\.' . str_replace('.', '\.', $domain_zone) . '$/', '', $f_dnsname);
+//                $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
                 $f_dnsname = preg_replace('/\s+/','-',$f_dnsname);
-                $f_dnsname = preg_replace('/\./','-',$f_dnsname);
+//                $f_dnsname = preg_replace('/\./','-',$f_dnsname);
                 }
             if (empty($f_dnsname) or !checkValidHostname($f_dnsname) or !checkUniqHostname($db_link,$id,$f_dnsname)) { continue; }
             $new['alias'] = $f_dnsname;
@@ -59,10 +60,11 @@ if (isset($_POST["s_create"])) {
         $f_dnsname = trim($new_alias);
         if (!empty($f_dnsname)) {
             $domain_zone = get_option($db_link, 33);
-            $f_dnsname = preg_replace('/'.$domain_zone.'/','',$f_dnsname);
-            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
+            $domain_zone = ltrim($domain_zone, '.');
+            $f_dnsname = preg_replace('/\.' . str_replace('.', '\.', $domain_zone) . '$/', '', $f_dnsname);
+//            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
             $f_dnsname = preg_replace('/\s+/','-',$f_dnsname);
-            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
+//            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
             }
 
         if (empty($f_dnsname) or !checkValidHostname($f_dnsname) or !checkUniqHostname($db_link,$id,$f_dnsname)) {

+ 17 - 9
html/admin/users/editauth.php

@@ -71,18 +71,25 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
         $dns_alias_count = get_count_records($db_link,'User_auth_alias','auth_id='.$id);
         if (!empty($f_dnsname) and !$new['dns_ptr_only']) {
             $domain_zone = get_option($db_link, 33);
-            $f_dnsname = preg_replace('/'.$domain_zone.'/','',$f_dnsname);
-            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
+            $domain_zone = ltrim($domain_zone, '.');
+            $f_dnsname = preg_replace('/\.' . str_replace('.', '\.', $domain_zone) . '$/', '', $f_dnsname);
+//            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
             $f_dnsname = preg_replace('/\s+/','-',$f_dnsname);
-            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
+//            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
             //disable change dns name when exists aliases
             if ($dns_alias_count >0 and $f_dnsname !== $old_auth_info['dns_name']) {
                 $f_dnsname =  $old_auth_info['dns_name'];
                 } else {
-                if (checkValidHostname($f_dnsname) and checkUniqHostname($db_link,$id,$f_dnsname)) {
+                $valid_dns = checkValidHostname($f_dnsname);
+                $uniq_dns = checkUniqHostname($db_link,$id,$f_dnsname);
+                if ($valid_dns and $uniq_dns) {
                         $new['dns_name'] = $f_dnsname;
                         } else {
-                        $msg_error = "DNS $f_dnsname already exists at: ".searchHostname($db_link,$id,$f_dnsname)." Discard changes!";
+                        if (!$uniq_dns) {
+                            $msg_error = "DNS $f_dnsname already exists at: ".searchHostname($db_link,$id,$f_dnsname)." Discard changes!";
+                            } else {
+                            $msg_error = "DNS $f_dnsname not valid! Discard changes!";
+                            }
                         $_SESSION[$page_url]['msg'] = $msg_error;
                         LOG_ERROR($db_link, $msg_error);
                         header("Location: " . $_SERVER["REQUEST_URI"]);
@@ -109,10 +116,11 @@ if (isset($_POST["editauth"]) and !$old_auth_info['deleted']) {
 
         if (!empty($f_dnsname) and $new['dns_ptr_only']) {
             $domain_zone = get_option($db_link, 33);
-            $f_dnsname = preg_replace('/'.$domain_zone.'/','',$f_dnsname);
-            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
+            $domain_zone = ltrim($domain_zone, '.');
+            $f_dnsname = preg_replace('/\.' . str_replace('.', '\.', $domain_zone) . '$/', '', $f_dnsname);
+//            $f_dnsname = preg_replace('/\.$/','',$f_dnsname);
             $f_dnsname = preg_replace('/\s+/','-',$f_dnsname);
-            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
+//            $f_dnsname = preg_replace('/\./','-',$f_dnsname);
             $new['dns_name'] = $f_dnsname;
             }
 
@@ -326,7 +334,7 @@ if (empty($auth_info['eof']) or $auth_info['eof'] == '0000-00-00 00:00:00') {
                 <td></td>
             </tr>
             <tr>
-                <td><input type="text" name="f_dns_name" size="14"  value="<?php echo $auth_info['dns_name']; ?>" pattern="^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$">
+                <td><input type="text" name="f_dns_name" size="14"  value="<?php echo $auth_info['dns_name']; ?>" pattern="^([a-zA-Z0-9-]{1,63})(\.[a-zA-Z0-9-]{1,63})*\.?$">
                     <input type="checkbox" id="f_dns_ptr" name="f_dns_ptr" value="1" <?php echo $f_dns_ptr; ?>> &nbsp ptr
                 </td>
                 <td><input type="text" name="f_comments" value="<?php echo $auth_info['comments']; ?>"></td>

+ 1 - 1
html/inc/common.php

@@ -172,7 +172,7 @@ function checkValidHostname($dnsname)
         return TRUE;
     }
 
-    $host_pattern = "/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/";
+    $host_pattern = "/^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])\.?$/";
     if (!preg_match($host_pattern, $dnsname)) {
         $result = FALSE;
     } else {

+ 12 - 12
html/inc/sql.php

@@ -474,7 +474,7 @@ function update_record($db, $table, $filter, $newvalue)
     }
 
     if ($table === "User_auth" and $dns_changed) {
-        if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only']) {
+        if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
             $del_dns['name_type'] = 'A';
             $del_dns['name'] = $old['dns_name'];
             $del_dns['value'] = $old['ip'];
@@ -484,7 +484,7 @@ function update_record($db, $table, $filter, $newvalue)
             }
             insert_record($db, 'dns_queue', $del_dns);
         }
-        if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only']) {
+        if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only'] and !preg_match('/\.$/', $old['dns_name'])) {
             $del_dns['name_type'] = 'PTR';
             $del_dns['name'] = $old['dns_name'];
             $del_dns['value'] = $old['ip'];
@@ -495,7 +495,7 @@ function update_record($db, $table, $filter, $newvalue)
             insert_record($db, 'dns_queue', $del_dns);
         }
 
-        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only']) {
+        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
             $new_dns['name_type'] = 'A';
             $new_dns['name'] = $newvalue['dns_name'];
             $new_dns['value'] = $newvalue['ip'];
@@ -505,7 +505,7 @@ function update_record($db, $table, $filter, $newvalue)
             }
             insert_record($db, 'dns_queue', $new_dns);
         }
-        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only']) {
+        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
             $new_dns['name_type'] = 'PTR';
             $new_dns['name'] = $newvalue['dns_name'];
             $new_dns['value'] = $newvalue['ip'];
@@ -522,7 +522,7 @@ function update_record($db, $table, $filter, $newvalue)
         if ($old['auth_id']) {
             $auth_id = $old['auth_id'];
         }
-        if (!empty($old['alias'])) {
+        if (!empty($old['alias']) and !preg_match('/\.$/', $old['alias'])) {
             $del_dns['name_type'] = 'CNAME';
             $del_dns['name'] = $old['alias'];
             $del_dns['type'] = 'del';
@@ -532,7 +532,7 @@ function update_record($db, $table, $filter, $newvalue)
             }
             insert_record($db, 'dns_queue', $del_dns);
         }
-        if (!empty($newvalue['alias'])) {
+        if (!empty($newvalue['alias'])  and !preg_match('/\.$/', $newvalue['alias'])) {
             $new_dns['name_type'] = 'CNAME';
             $new_dns['name'] = $newvalue['alias'];
             $new_dns['type'] = 'add';
@@ -643,7 +643,7 @@ function delete_record($db, $table, $filter)
             return;
             }
         //dns - A-record
-        if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only']) {
+        if (!empty($old['dns_name']) and !empty($old['ip']) and !$old['dns_ptr_only']  and !preg_match('/\.$/', $old['dns_name'])) {
             $del_dns['name_type'] = 'A';
             $del_dns['name'] = $old['dns_name'];
             $del_dns['value'] = $old['ip'];
@@ -654,7 +654,7 @@ function delete_record($db, $table, $filter)
             insert_record($db, 'dns_queue', $del_dns);
             }
         //ptr
-        if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only']) {
+        if (!empty($old['dns_name']) and !empty($old['ip']) and $old['dns_ptr_only']  and !preg_match('/\.$/', $old['dns_name'])) {
             $del_dns['name_type'] = 'PTR';
             $del_dns['name'] = $old['dns_name'];
             $del_dns['value'] = $old['ip'];
@@ -674,7 +674,7 @@ function delete_record($db, $table, $filter)
     //remove aliases
     if ($table === 'User_auth_alias') {
         //dns
-        if (!empty($old['alias'])) {
+        if (!empty($old['alias'])  and !preg_match('/\.$/', $old['alias'])) {
             $del_dns['name_type'] = 'CNAME';
             $del_dns['name'] = $old['alias'];
             $del_dns['value'] = '';
@@ -756,7 +756,7 @@ function insert_record($db, $table, $newvalue)
 
     if ($table === 'User_auth_alias') {
         //dns
-        if (!empty($newvalue['alias'])) {
+        if (!empty($newvalue['alias'])  and !preg_match('/\.$/', $newvalue['alias'])) {
             $add_dns['name_type'] = 'CNAME';
             $add_dns['name'] = $newvalue['alias'];
             $add_dns['value'] = get_dns_name($db, $newvalue['auth_id']);
@@ -768,7 +768,7 @@ function insert_record($db, $table, $newvalue)
 
     if ($table === 'User_auth') {
         //dns - A-record
-        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only']) {
+        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and !$newvalue['dns_ptr_only']  and !preg_match('/\.$/', $newvalue['dns_name'])) {
             $add_dns['name_type'] = 'A';
             $add_dns['name'] = $newvalue['dns_name'];
             $add_dns['value'] = $newvalue['ip'];
@@ -777,7 +777,7 @@ function insert_record($db, $table, $newvalue)
             insert_record($db, 'dns_queue', $add_dns);
         }
         //dns - ptr
-        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only']) {
+        if (!empty($newvalue['dns_name']) and !empty($newvalue['ip']) and $newvalue['dns_ptr_only'] and !preg_match('/\.$/', $newvalue['dns_name'])) {
             $add_dns['name_type'] = 'PTR';
             $add_dns['name'] = $newvalue['dns_name'];
             $add_dns['value'] = $newvalue['ip'];

+ 20 - 20
scripts/eyelib/database.pm

@@ -527,7 +527,7 @@ if ($found_changed) {
         $change_str .= ", `changed_time`='".GetNowTime()."'"; 
         if ($dns_changed) {
                 my $del_dns;
-                if ($old_record->{'dns_name'} and $old_record->{'ip'} and !$old_record->{'dns_ptr_only'}) {
+                if ($old_record->{'dns_name'} and $old_record->{'ip'} and !$old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
                     $del_dns->{'name_type'}='A';
                     $del_dns->{'name'}=$old_record->{'dns_name'};
                     $del_dns->{'value'}=$old_record->{'ip'};
@@ -535,7 +535,7 @@ if ($found_changed) {
                     if ($rec_id) { $del_dns->{'auth_id'}=$rec_id; }
                     insert_record($db,'dns_queue',$del_dns);
                     }
-                if ($old_record->{'dns_name'} and $old_record->{'ip'} and $old_record->{'dns_ptr_only'}) {
+                if ($old_record->{'dns_name'} and $old_record->{'ip'} and $old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
                     $del_dns->{'name_type'}='PTR';
                     $del_dns->{'name'}=$old_record->{'dns_name'};
                     $del_dns->{'value'}=$old_record->{'ip'};
@@ -548,7 +548,7 @@ if ($found_changed) {
                 my $dns_rec_name = $old_record->{dns_name};
                 if ($record->{'dns_name'}) { $dns_rec_name = $record->{'dns_name'}; }
                 if ($record->{'ip'}) { $dns_rec_ip = $record->{'ip'}; }
-                if ($dns_rec_name and $dns_rec_ip and !$record->{'dns_ptr_only'}) {
+                if ($dns_rec_name and $dns_rec_ip and !$record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
                     $new_dns->{'name_type'}='A';
                     $new_dns->{'name'}=$dns_rec_name;
                     $new_dns->{'value'}=$dns_rec_ip;
@@ -556,7 +556,7 @@ if ($found_changed) {
                     if ($rec_id) { $new_dns->{'auth_id'}=$rec_id; }
                     insert_record($db,'dns_queue',$new_dns);
                     }
-                if ($dns_rec_name and $dns_rec_ip and $record->{'dns_ptr_only'}) {
+                if ($dns_rec_name and $dns_rec_ip and $record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
                     $new_dns->{'name_type'}='PTR';
                     $new_dns->{'name'}=$dns_rec_name;
                     $new_dns->{'value'}=$dns_rec_ip;
@@ -569,7 +569,7 @@ if ($found_changed) {
     if ($table eq 'User_auth_alias') {
         if ($dns_changed) {
                 my $del_dns;
-                if ($old_record->{'alias'}) {
+                if ($old_record->{'alias'} and $old_record->{'alias'}!~/\.$/) {
                     $del_dns->{'name_type'}='CNAME';
                     $del_dns->{'name'}=$old_record->{'alias'};
                     $del_dns->{'type'}='del';
@@ -580,7 +580,7 @@ if ($found_changed) {
                 my $new_dns;
                 my $dns_rec_name = $old_record->{alias};
                 if ($record->{'alias'}) { $dns_rec_name = $record->{'alias'}; }
-                if ($dns_rec_name) {
+                if ($dns_rec_name and $record->{'alias'}!~/\.$/) {
                     $new_dns->{'name_type'}='CNAME';
                     $new_dns->{'name'}=$dns_rec_name;
                     $new_dns->{'type'}='add';
@@ -642,7 +642,7 @@ my $result = do_sql($db,$sSQL);
 if ($result) {
     $new_str='id: '.$result.' '.$new_str;
     if ($table eq 'User_auth_alias' and $dns_changed) {
-        if ($record->{'alias'}) {
+        if ($record->{'alias'} and $record->{'alias'}!~/\.$/) {
                     my $add_dns;
                     $add_dns->{'name_type'}='CNAME';
                     $add_dns->{'name'}=$record->{'alias'};
@@ -653,7 +653,7 @@ if ($result) {
                     }
         }
     if ($table eq 'User_auth' and $dns_changed) {
-        if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed and !$record->{'dns_ptr_only'}) {
+        if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed and !$record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
                     my $add_dns;
                     $add_dns->{'name_type'}='A';
                     $add_dns->{'name'}=$record->{'dns_name'};
@@ -662,7 +662,7 @@ if ($result) {
                     $add_dns->{'auth_id'}=$result;
                     insert_record($db,'dns_queue',$add_dns);
                     }
-        if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed and $record->{'dns_ptr_only'}) {
+        if ($record->{'dns_name'} and $record->{'ip'} and $dns_changed and $record->{'dns_ptr_only'} and $record->{'dns_name'}!~/\.$/) {
                     my $add_dns;
                     $add_dns->{'name_type'}='PTR';
                     $add_dns->{'name'}=$record->{'dns_name'};
@@ -700,7 +700,7 @@ db_log_debug($db,'Delete record from table  '.$table.' value: '.$diff);
 if ($table eq 'User_auth') {
     my $sSQL = "UPDATE User_auth SET changed=1, deleted=1, changed_time='".GetNowTime()."' WHERE ".$filter;
     do_sql($db,$sSQL);
-    if ($old_record->{'dns_name'} and $old_record->{'ip'} and !$old_record->{'dns_ptr_only'}) {
+    if ($old_record->{'dns_name'} and $old_record->{'ip'} and !$old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
             my $del_dns;
             $del_dns->{'name_type'}='A';
             $del_dns->{'name'}=$old_record->{'dns_name'};
@@ -709,7 +709,7 @@ if ($table eq 'User_auth') {
             $del_dns->{'auth_id'}=$old_record->{'id'};
             insert_record($db,'dns_queue',$del_dns);
             }
-    if ($old_record->{'dns_name'} and $old_record->{'ip'} and $old_record->{'dns_ptr_only'}) {
+    if ($old_record->{'dns_name'} and $old_record->{'ip'} and $old_record->{'dns_ptr_only'} and $old_record->{'dns_name'}!~/\.$/) {
             my $del_dns;
             $del_dns->{'name_type'}='PTR';
             $del_dns->{'name'}=$old_record->{'dns_name'};
@@ -723,7 +723,7 @@ if ($table eq 'User_auth') {
 if ($table eq 'User_list' and $old_record->{'permanent'}) { return; }
 
 if ($table eq 'User_auth_alias') {
-    if ($old_record->{'alias'} and $old_record->{'auth_id'}) {
+    if ($old_record->{'alias'} and $old_record->{'auth_id'} and $old_record->{'alias'}!~/\.$/) {
             my $del_dns;
             $del_dns->{'name_type'}='CNAME';
             $del_dns->{'name'}=$old_record->{'alias'};
@@ -932,7 +932,7 @@ log_debug("Auth id: ".$auth_id);
 log_debug("enable_ad_dns_update: ".$enable_ad_dns_update);
 log_debug("DNS update flags - zone: ".$ad_zone.", dns: ".$ad_dns.", enable_ad_dns_update: ".$enable_ad_dns_update);
 
-my @dns_queue = get_records_sql($hdb,"SELECT * FROM dns_queue WHERE auth_id=".$auth_id." ORDER BY id ASC");
+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");
 
 if (!@dns_queue or !scalar @dns_queue) { return; }
 
@@ -950,14 +950,14 @@ eval {
 if ($dns_cmd->{name_type}=~/^cname$/i) {
     $fqdn=lc($dns_cmd->{name});
     $fqdn=~s/\.$ad_zone$//i;
-    $fqdn=~s/\.$//;
+#    $fqdn=~s/\.$//;
     if ($dns_cmd->{value}) {
         $fqdn_parent=lc($dns_cmd->{value});
         $fqdn_parent=~s/\.$ad_zone$//i;
-        $fqdn_parent=~s/\.$//;
+#        $fqdn_parent=~s/\.$//;
         }
     #skip update unknown domain
-    if ($fqdn =~/\./ or $fqdn_parent =~/\./) { next; }
+    if ($fqdn =~/\.$/ or $fqdn_parent =~/\.$/) { next; }
 
     $fqdn = $fqdn.".".$ad_zone;
     $fqdn_parent = $fqdn_parent.".".$ad_zone;
@@ -975,11 +975,11 @@ if ($dns_cmd->{name_type}=~/^cname$/i) {
 if ($dns_cmd->{name_type}=~/^a$/i) {
     $fqdn=lc($dns_cmd->{name});
     $fqdn=~s/\.$ad_zone$//i;
-    $fqdn=~s/\.$//;
+#    $fqdn=~s/\.$//;
     if (!$dns_cmd->{value}) { next; }
     $fqdn_ip=lc($dns_cmd->{value});
     #skip update unknown domain
-    if ($fqdn =~/\./) { next; }
+    if ($fqdn =~/\.$/) { next; }
     $fqdn = $fqdn.".".$ad_zone;
     #dns update disabled?
     my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );
@@ -1033,11 +1033,11 @@ if ($dns_cmd->{name_type}=~/^a$/i) {
 if ($dns_cmd->{name_type}=~/^ptr$/i) {
     $fqdn=lc($dns_cmd->{name});
     $fqdn=~s/\.$ad_zone$//i;
-    $fqdn=~s/\.$//;
+#    $fqdn=~s/\.$//;
     if (!$dns_cmd->{value}) { next; }
     $fqdn_ip=lc($dns_cmd->{value});
     #skip update unknown domain
-    if ($fqdn =~/\./) { next; }
+    if ($fqdn =~/\.$/) { next; }
     $fqdn = $fqdn.".".$ad_zone;
     #dns update disabled?
     my $maybe_update_dns=( $enable_ad_dns_update and $office_networks->match_string($fqdn_ip) );

+ 71 - 0
scripts/print-dnsmasq.pl

@@ -99,4 +99,75 @@ if (!$static_hole{$ip}{skip}) {
     }
 }
 
+# DNS
+print "#--- DNS ---#\n";
+
+#get userid list
+my $sSQL="SELECT id,ou_id,ip,dns_name,dhcp_hostname,dns_ptr_only FROM User_auth WHERE deleted=0 AND ip>'' AND (dns_name>'' OR dhcp_hostname>'') AND dns_name NOT LIKE '%.' ORDER by ip_int;";
+my @users = get_records_sql($dbh,$sSQL);
+foreach my $row (@users) {
+next if (!$row);
+next if (is_default_ou($dbh,$row->{ou_id}));
+next if (!$office_networks->match_string($row->{ip}));
+
+my $dns_name = trim($row->{dns_name});
+if ($dns_name) {
+    $dns_name =~s/_/-/g;
+#    $dns_name =~s/[\.]/-/g;
+    $dns_name =~s/ /-/g;
+    $dns_name =~s/-$//g;
+    $dns_name = trim($dns_name);
+    if ($dns_name and $dns_name!~/\.$domain_name$/) { $dns_name = $dns_name .".".$domain_name; }
+    } else { $dns_name=''; }
+
+next if (!$dns_name);
+
+#if (!$row->{dns_ptr_only} and ($dns_name or $row->{dhcp_hostname})) {
+if (!$row->{dns_ptr_only} and $dns_name) {
+    print '#Comment:'.$row->{comments}."\n" if ($row->{comments});
+    if ($dns_name) {
+        print '#DNS A-record '.$dns_name."\n";
+        print 'address=/'.$dns_name.'/'.$row->{ip}."\n";
+        } 
+#        else {
+#        if ($row->{dhcp_hostname} and $row->{dhcp_hostname}!~/UNDEFINED/i) {
+#            $dns_name = $row->{dhcp_hostname};
+#            $dns_name = $dns_name .".".$domain_name; }
+#            $dns_name =~s/_/-/g;
+##            $dns_name =~s/[\.]/-/g;
+#            $dns_name =~s/ /-/g;
+#            $dns_name =~s/-$//g;
+#            $dns_name = trim($dns_name);
+#            if ($dns_name) {
+#                print '#DNS-from-DHCP A-record '.$dns_name."\n";
+#                print 'address=/'.$dns_name.'/'.$row->{ip}."\n";
+#                }
+#            }
+    #aliases
+    if ($dns_name) {
+        my $aSQL="SELECT * FROM `User_auth_alias` WHERE auth_id=$row->{id} AND alias>'' AND alias NOT LIKE '%.';";
+        my @aliases = get_records_sql($dbh,$aSQL);
+        print '#DNS aliases for '.$dns_name."\n" if (@aliases and scalar @aliases);
+        foreach my $alias (@aliases) {
+            my $dns_alias = trim($alias->{alias});
+#            $dns_alias =~s/$domain_name//i;
+            $dns_alias =~s/_/-/g;
+            $dns_alias =~s/[\.]/-/g;
+            $dns_alias =~s/ /-/g;
+            $dns_alias =~s/-$//g;
+            $dns_alias = trim($dns_alias);
+            if ($dns_alias and $dns_alias !~ /\.\Q$domain_name\E$/i) { $dns_alias = $dns_alias .".".$domain_name; }
+            print "cname=".$dns_alias.",".$dns_name."\n" if ($dns_alias);
+            }
+        }
+    }
+
+my $ptr_record='';
+if ($dns_name and $row->{ip}=~/([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/) {
+    $ptr_record=$4.".".$3.".".$2.".".$1.".in-addr.arpa";
+    print '#PTR for '.$dns_name."\n";
+    print 'ptr-record='.$ptr_record.','.$dns_name."\n";
+    }
+}
+
 exit 0;

+ 79 - 0
scripts/updates/2-8-0/after_sql.pl

@@ -0,0 +1,79 @@
+#!/usr/bin/perl
+
+#
+# Copyright (C) Roman Dmitiriev, rnd@rajven.ru
+#
+
+use utf8;
+use Encode;
+no warnings 'utf8';
+use open ':encoding(utf-8)';
+use FindBin '$Bin';
+use lib "/opt/Eye/scripts";
+use eyelib::config;
+use eyelib::main;
+use eyelib::database;
+use strict;
+use warnings;
+
+STDOUT->autoflush(1);
+
+my $upgrade_from = '2.7.9';
+my $this_release = '2.8.0';
+
+$dbh=init_db();
+init_option($dbh);
+
+if (!$config_ref{version}) {
+    print "Current version unknown! Skip upgrade!\n";
+    exit 100;
+    }
+
+if ($this_release eq $config_ref{version}) { print "Already updated!\n"; exit; }
+
+if ($upgrade_from ne $config_ref{version}) { print "Illegal version. Needed $upgrade_from!\n"; exit; }
+
+print 'Apply patch for version: '.$config_ref{version}.' upgrade to: '.$this_release."\n";
+
+my @authlist_ref = get_records_sql($dbh,"SELECT * FROM User_auth WHERE dns_name>''" );
+
+my $total = scalar @authlist_ref;
+
+print "Stage 1: Fix dns name fields\n";
+
+my $i = 0;
+foreach my $row (@authlist_ref) {
+my $new;
+$i++;
+my $dns_name = trim($row->{dns_name});
+if ($dns_name and $dns_name =~ /\.\Q$domain_name\E$/i) {
+    $dns_name =~ s/\.\Q$domain_name\E$//i;
+    $dns_name =~s/\.$//g;
+    $dns_name =~s/_/-/g;
+    $dns_name =~s/ /-/g;
+    $dns_name =~s/-$//g;
+    $dns_name = trim($dns_name);
+    if ($dns_name) { $new->{dns_name}=$dns_name; }
+    } else {
+    $dns_name =~s/_/-/g;
+    $dns_name =~s/ /-/g;
+    $dns_name =~s/-$//g;
+    $dns_name = trim($dns_name);
+    if ($dns_name and $dns_name=~/\./) {
+        $dns_name = $dns_name.".";
+        $new->{dns_name}=$dns_name;
+        }
+    }
+
+my $percent = int(($i / $total) * 100);
+
+if (exists $new->{dns_name} and $new->{dns_name}) {
+    update_record($dbh,'User_auth',$new,'id='.$row->{id});
+    }
+
+print "\r::Progress: [$percent%] ";
+}
+
+print "Done!\n";
+
+exit;

+ 2 - 0
scripts/updates/upgrade.pl

@@ -17,6 +17,8 @@ use eyelib::database;
 use strict;
 use warnings;
 
+STDOUT->autoflush(1);
+
 my $update_dir = '/opt/Eye/scripts/updates/';
 
 opendir(my $dh, $update_dir) or die "Eror listing for $update_dir: $!";

+ 57 - 42
scripts/utils/bind/print-dns-zones.pl

@@ -22,55 +22,65 @@ my $named_db_fullpath=$named_root.'/etc/bind/masters';
 my $named_db_path='/etc/bind/masters';
 
 my $DNS1=$config_ref{dns_server};
-
-my $dns_server_record = get_record_sql($dbh,"SELECT id,ip,dns_name FROM User_auth WHERE deleted=0 AND ip='".$DNS1."'");
-
-my $ns1 = 'ns1';
-if ($dns_server_record and $dns_server_record->{dns_name}) { $ns1=$dns_server_record->{dns_name}; }
+my $DNS1_IP=$config_ref{dns_server};
+
+my $dns_server_record = get_record_sql($dbh,"SELECT id,ip,dns_name FROM User_auth WHERE deleted=0 AND ip='".$DNS1_IP."'");
+
+if ($dns_server_record and $dns_server_record->{dns_name}) { 
+    my $ns1=$dns_server_record->{dns_name};
+    $ns1 =~s/\.$//g;
+    $ns1 =~s/_/-/g;
+#    $dns_name =~s/[\.]/-/g;
+    $ns1 =~s/ /-/g;
+    $ns1 =~s/-$//g;
+    $ns1 = trim($ns1);
+    if ($ns1 and $ns1 !~ /\.\Q$domain_name\E$/i) { $ns1 = $ns1 .".".$domain_name; }
+    $DNS1 = $ns1;
+    }
 
 #exit if ($config_ref{dns_server_type!='bind');
 
 my $named_conf=$named_root.'/etc/bind/named.dynamic';
 
-# user auth list
-my @authlist_ref = get_records_sql($dbh,"SELECT id,ip,dns_name FROM User_auth WHERE `ip_int`>0 AND `deleted`=0 ORDER BY ip_int");
-
 my %zones;
 
-$zones{$domain_name}->{A}->{$ns1}=$DNS1;
-
+my $sSQL="SELECT id,ou_id,ip,dns_name,dhcp_hostname,dns_ptr_only FROM User_auth WHERE deleted=0 AND ip>'' AND (dns_name>'' OR dhcp_hostname>'') AND dns_name NOT LIKE '%.' ORDER by ip_int;";
+my @authlist_ref = get_records_sql($dbh,$sSQL);
 foreach my $row (@authlist_ref) {
 next if (!$row);
+next if (is_default_ou($dbh,$row->{ou_id}));
+my $dns_name = trim($row->{dns_name});
+if ($dns_name) {
+#    $dns_name =~s/$domain_name//i;
+    $dns_name =~s/\.$//g;
+    $dns_name =~s/_/-/g;
+#    $dns_name =~s/[\.]/-/g;
+    $dns_name =~s/ /-/g;
+    $dns_name =~s/-$//g;
+    $dns_name = trim($dns_name);
+    if ($dns_name and $dns_name !~ /\.\Q$domain_name\E$/i) { $dns_name = $dns_name .".".$domain_name; }
+    } else { $dns_name=''; }
+
+next if (!$dns_name);
 
 my $ip=trim($row->{ip});
-my $dns_name=trim($row->{dns_name});
 next if (!$ip);
 next if (!$office_networks->match_string($ip));
 
-my $default_name=$ip;
-$default_name=~s/\./-/g;
-
-if ($dns_name) {
-    $default_name=$dns_name;
-    $default_name =~s/$domain_name$//g;
-    $default_name =~s/\.$//g;
-    $default_name =~s/_/-/g;
-    $default_name =~s/[\.]/-/g;
-    $default_name =~s/ /-/g;
-    $default_name =~s/-$//g;
-    $zones{$domain_name}{A}{$default_name}=$ip;
-    }
-
-my @dns_names=get_records_sql($dbh,"SELECT * FROM User_auth_alias WHERE auth_id=$row->{id} ORDER BY alias");
-foreach my $alias (@dns_names) {
-        my $dns = $alias->{alias};
-        $dns =~s/$domain_name$//g;
-        $dns =~s/\.$/-/g;
-        $dns =~s/_/-/g;
-        $dns =~s/[.]/-/g;
-        $dns =~s/ /-/g;
-        $dns =~s/-$//g;
-        $zones{$domain_name}{CNAME}{$dns}=$default_name;
+my $default_name=$dns_name;
+$zones{$domain_name}{A}{$default_name}=$ip;
+
+my @dns_aliases=get_records_sql($dbh,"SELECT * FROM User_auth_alias WHERE auth_id=$row->{id} AND alias>'' AND alias NOT LIKE '%.' ORDER BY alias");
+foreach my $alias (@dns_aliases) {
+        my $dns_alias = trim($alias->{alias});
+#        $dns_alias =~s/$domain_name//i;
+        $dns_alias =~s/_/-/g;
+        $dns_alias =~s/[\.]/-/g;
+        $dns_alias =~s/ /-/g;
+        $dns_alias =~s/-$//g;
+        $dns_alias = trim($dns_alias);
+        if ($dns_alias and $dns_alias !~ /\.\Q$domain_name\E$/i) { $dns_alias = $dns_alias .".".$domain_name; }
+        $zones{$domain_name}{CNAME}{$dns_alias}=$default_name if ($dns_alias);
         }
 
 if ($ip=~/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\.([0-9]{1,3})/) {
@@ -119,7 +129,7 @@ flock(F1,2);
 
 print F1  "\$ORIGIN .\n";
 print F1  "\$TTL 3600\t; 1 hour\n";
-print F1  "$zone_name\t\tIN SOA\t\t".$ns1.".".$domain_name.". root.".$ns1.".".$domain_name.". (\n";
+print F1  $zone_name."\t\tIN SOA\t\t".$DNS1." root.".$DNS1.". (\n";
 printf F1 "\t\t\t\t%04d%02d%02d%02d ; serial\n",$year,$mon,$mday,$hour;
 print F1  "\t\t\t\t900\t; refresh (15 minutes)\n";
 print F1  "\t\t\t\t600\t; retry (10 minutes)\n";
@@ -127,24 +137,29 @@ print F1  "\t\t\t\t86400\t; expire (1 day)\n";
 print F1  "\t\t\t\t3600\t; minimum (1 hour)\n";
 print F1  "\t\t\t\t)\n";
 print F1  "\t\t\t\tNS\t $DNS1\n";
-if ($dns_server) {
-print F1  "\t\t\t\tA\t $dns_server\n";
-}
 print F1  ";\n";
+
+#A-record for domain
+if ($DNS1) { 
+    print F1  ";A-record for domain\n";
+    print F1  "\t\t\t\tA\t $DNS1_IP\n"; 
+    }
+
 print F1  "\$TTL 3600\t; 1 hour\n";
 print F1  "; host list\n";
-print F1  "\$ORIGIN $zone_name.\n";
 
 if ($reverse) {
+    print F1  "\$ORIGIN $zone_name.\n";
     foreach my $record (sort keys %{$zones{$ZONE}->{PTR}}) {
-        print  F1 "$record\t\t\tIN\tPTR\t$zones{$ZONE}->{PTR}->{$record}.$domain_name.\n";
+        print  F1 "$record\t\t\tIN\tPTR\t$zones{$ZONE}->{PTR}->{$record}.\n";
         }
     } else {
+    #print F1  "\$ORIGIN $zone_name.\n";
     foreach my $record (sort keys %{$zones{$ZONE}->{A}}) {
         print  F1 "$record\t\t\t\tA\t$zones{$ZONE}->{A}->{$record}\n";
         };
     foreach my $record (sort keys %{$zones{$ZONE}->{CNAME}}) {
-        print  F1 "$record\t\t\t\tCNAME\t$zones{$ZONE}->{CNAME}->{$record}.$domain_name.\n";
+        print  F1 "$record\t\t\t\tCNAME\t$zones{$ZONE}->{CNAME}->{$record}.\n";
         };
     }
 }