Parcourir la source

spegnimento e accensione funzionanti

FabioFratini il y a 6 mois
Parent
commit
ea5415b068

+ 204 - 0
app/Console/Commands/VpnStatusCommand.php

@@ -0,0 +1,204 @@
+<?php
+
+namespace App\Console\Commands;
+
+use Illuminate\Console\Command;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Storage;
+
+class VpnStatusCommand extends Command
+{
+    protected $signature = 'vpn:status {--refresh : Refresh status from system} {--sync : Sync database with system status}';
+    protected $description = 'Controlla e sincronizza lo stato della connessione VPN';
+
+    public function handle()
+    {
+        $this->info('=== VPN STATUS REPORT ===');
+        $this->newLine();
+
+        // 1. Stato dal database
+        $this->checkDatabaseStatus();
+
+        // 2. Stato dal sistema (se richiesto)
+        if ($this->option('refresh') || $this->option('sync')) {
+            $this->checkSystemStatus();
+        }
+
+        // 3. Sincronizzazione (se richiesta)
+        if ($this->option('sync')) {
+            $this->syncStatus();
+        }
+
+        // 4. Verifica file e configurazioni
+        $this->checkFiles();
+
+        // 5. Mostra log recenti
+        $this->showRecentLogs();
+
+        $this->newLine();
+        $this->info('=== END REPORT ===');
+    }
+
+    private function checkDatabaseStatus()
+    {
+        $this->line('<comment>1. Database Status:</comment>');
+
+        try {
+            $status = DB::table('vpn_status')->first();
+
+            if ($status) {
+                $statusColor = $status->status === 'connected' ? 'green' : 'red';
+                $this->line("   Status: <fg={$statusColor}>{$status->status}</>");
+                $this->line("   Last Update: {$status->last_update}");
+                $this->line("   Record ID: {$status->id}");
+            } else {
+                $this->error('   No status record found in database');
+            }
+        } catch (\Exception $e) {
+            $this->error('   Database error: ' . $e->getMessage());
+        }
+
+        $this->newLine();
+    }
+
+    private function syncStatus()
+    {
+        $this->line('<comment>3. Synchronizing Database with System:</comment>');
+
+        try {
+            // Ottieni stato dal sistema
+            $output = [];
+            exec('/opt/cisco/anyconnect/bin/vpn state 2>&1', $output);
+            $statusText = implode(' ', $output);
+
+            $systemStatus = 'unknown';
+            if (strpos($statusText, 'state: Connected') !== false) {
+                $systemStatus = 'connected';
+            } elseif (strpos($statusText, 'Disconnected') !== false) {
+                $systemStatus = 'disconnected';
+            }
+
+            // Ottieni stato dal database
+            $dbRecord = DB::table('vpn_status')->first();
+            $dbStatus = $dbRecord ? $dbRecord->status : 'no_record';
+
+            $this->line("   System Status: <fg=yellow>{$systemStatus}</>");
+            $this->line("   Database Status: <fg=yellow>{$dbStatus}</>");
+
+            if ($systemStatus !== 'unknown' && $systemStatus !== $dbStatus) {
+                // Aggiorna il database
+                DB::table('vpn_status')->updateOrInsert(
+                    ['id' => 1],
+                    [
+                        'status' => $systemStatus,
+                        'last_update' => now(),
+                        'updated_at' => now(),
+                    ]
+                );
+
+                $this->line("   ✅ <fg=green>Database updated to: {$systemStatus}</>");
+                Log::info('VPN status synced via command', [
+                    'old_status' => $dbStatus,
+                    'new_status' => $systemStatus
+                ]);
+            } else {
+                $this->line('   ℹ️  No sync needed - statuses match');
+            }
+
+        } catch (\Exception $e) {
+            $this->error("   ❌ Sync failed: " . $e->getMessage());
+        }
+    }
+
+    private function checkSystemStatus()
+    {
+        $this->line('<comment>2. System Status (Live Check):</comment>');
+
+        if (file_exists('/opt/cisco/anyconnect/bin/vpn')) {
+            $this->line('   ✅ Cisco AnyConnect: Installed');
+
+            $output = [];
+            $returnVar = 0;
+            exec('/opt/cisco/anyconnect/bin/vpn state 2>&1', $output, $returnVar);
+
+            $this->line('   System Status Output:');
+            foreach ($output as $line) {
+                $this->line('      ' . $line);
+            }
+
+            // Analizza l'output
+            $statusText = implode(' ', $output);
+            if (strpos($statusText, 'Connected') !== false) {
+                $this->line('   ✅ <fg=green>System Status: CONNECTED</>', 'green');
+            } elseif (strpos($statusText, 'Disconnected') !== false) {
+                $this->line('   ❌ <fg=red>System Status: DISCONNECTED</>');
+            } else {
+                $this->line('   ⚠️  <fg=yellow>System Status: UNKNOWN</>');
+            }
+        } else {
+            $this->error('   ❌ Cisco AnyConnect: Not Installed');
+        }
+
+        $this->newLine();
+    }
+
+    private function checkFiles()
+    {
+        $this->line('<comment>3. Configuration Files:</comment>');
+
+        $files = [
+            'scripts/vpn-connect.sh' => 'Connection Script',
+            'scripts/vpn-disconnect.sh' => 'Disconnection Script',
+            'scripts/vpn-config.conf' => 'Configuration File',
+        ];
+
+        foreach ($files as $file => $description) {
+            if (Storage::exists($file)) {
+                $this->line("   ✅ {$description}: Present");
+
+                // Mostra i permessi per gli script
+                if (str_ends_with($file, '.sh')) {
+                    $fullPath = storage_path($file);
+                    $perms = substr(sprintf('%o', fileperms($fullPath)), -4);
+                    $this->line("      Permissions: {$perms}");
+                }
+            } else {
+                $this->error("   ❌ {$description}: Missing");
+            }
+        }
+
+        // Controlla directory logs
+        if (Storage::exists('logs')) {
+            $this->line('   ✅ Logs Directory: Present');
+        } else {
+            $this->error('   ❌ Logs Directory: Missing');
+        }
+
+        $this->newLine();
+    }
+
+    private function showRecentLogs()
+    {
+        $this->line('<comment>4. Recent Log Entries:</comment>');
+
+        $logFile = storage_path('app/logs/vpn-connection.log');
+
+        if (file_exists($logFile)) {
+            $this->line("   Log file: {$logFile}");
+
+            // Leggi le ultime 10 righe
+            $lines = file($logFile);
+            $recentLines = array_slice($lines, -10);
+
+            $this->line('   Last 10 entries:');
+            foreach ($recentLines as $line) {
+                $this->line('      ' . trim($line));
+            }
+        } else {
+            $this->error('   Log file not found');
+        }
+
+        $this->newLine();
+    }
+}

+ 47 - 26
app/Services/VpnManager.php

@@ -15,23 +15,19 @@ class VpnManager
     public function updateCredentials($username, $password, $server)
     public function updateCredentials($username, $password, $server)
     {
     {
         try {
         try {
-            // Crea il contenuto del file di configurazione
             $configContent = "# Configurazione VPN - storage/scripts/vpn-config.conf\n";
             $configContent = "# Configurazione VPN - storage/scripts/vpn-config.conf\n";
             $configContent .= "# ATTENZIONE: Questo file deve avere permessi 600\n\n";
             $configContent .= "# ATTENZIONE: Questo file deve avere permessi 600\n\n";
             $configContent .= "VPN_USERNAME=\"{$username}\"\n";
             $configContent .= "VPN_USERNAME=\"{$username}\"\n";
             $configContent .= "VPN_PASSWORD=\"{$password}\"\n";
             $configContent .= "VPN_PASSWORD=\"{$password}\"\n";
             $configContent .= "VPN_SERVER=\"{$server}\"\n";
             $configContent .= "VPN_SERVER=\"{$server}\"\n";
 
 
-            // Salva il file di configurazione
             Storage::put($this->configPath, $configContent);
             Storage::put($this->configPath, $configContent);
 
 
-            // Imposta i permessi corretti (solo per sistemi Unix/Linux)
-            $fullPath = storage_path('app/' . $this->configPath);
+            $fullPath = storage_path( $this->configPath);
             chmod($fullPath, 0600);
             chmod($fullPath, 0600);
 
 
             Log::info('Credenziali VPN aggiornate con successo');
             Log::info('Credenziali VPN aggiornate con successo');
             return true;
             return true;
-
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Errore nell\'aggiornamento delle credenziali VPN: ' . $e->getMessage());
             Log::error('Errore nell\'aggiornamento delle credenziali VPN: ' . $e->getMessage());
             return false;
             return false;
@@ -41,12 +37,10 @@ class VpnManager
     public function getVpnStatus($forceRefresh = false)
     public function getVpnStatus($forceRefresh = false)
     {
     {
         try {
         try {
-            // Se richiesto refresh, sincronizza con il sistema
             if ($forceRefresh) {
             if ($forceRefresh) {
                 return $this->syncStatusWithSystem();
                 return $this->syncStatusWithSystem();
             }
             }
 
 
-            // Verifica se la tabella esiste
             if (!Schema::hasTable('vpn_status')) {
             if (!Schema::hasTable('vpn_status')) {
                 Log::warning('Tabella vpn_status non esiste');
                 Log::warning('Tabella vpn_status non esiste');
                 return 'disconnected';
                 return 'disconnected';
@@ -55,12 +49,10 @@ class VpnManager
             $status = \DB::table('vpn_status')->first();
             $status = \DB::table('vpn_status')->first();
 
 
             if (!$status) {
             if (!$status) {
-                // Se non ci sono record, sincronizza con il sistema
                 return $this->syncStatusWithSystem();
                 return $this->syncStatusWithSystem();
             }
             }
 
 
             return $status->status;
             return $status->status;
-
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Errore nel recupero dello stato VPN: ' . $e->getMessage());
             Log::error('Errore nel recupero dello stato VPN: ' . $e->getMessage());
             return 'disconnected';
             return 'disconnected';
@@ -76,7 +68,6 @@ class VpnManager
 
 
             $status = \DB::table('vpn_status')->first();
             $status = \DB::table('vpn_status')->first();
             return $status ? $status->last_update : now();
             return $status ? $status->last_update : now();
-
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Errore nel recupero dell\'ultimo aggiornamento VPN: ' . $e->getMessage());
             Log::error('Errore nel recupero dell\'ultimo aggiornamento VPN: ' . $e->getMessage());
             return now();
             return now();
@@ -100,16 +91,19 @@ class VpnManager
             ]);
             ]);
 
 
             // Determina lo stato basandosi sull'output
             // Determina lo stato basandosi sull'output
-            if (strpos($statusText, 'state: Connected') !== false ||
-                strpos($statusText, 'Connected') !== false) {
+            if (
+                strpos($statusText, 'state: Connected') !== false ||
+                strpos($statusText, 'Connected') !== false
+            ) {
                 return 'connected';
                 return 'connected';
-            } elseif (strpos($statusText, 'Disconnected') !== false ||
-                      strpos($statusText, 'state: Disconnected') !== false) {
+            } elseif (
+                strpos($statusText, 'Disconnected') !== false ||
+                strpos($statusText, 'state: Disconnected') !== false
+            ) {
                 return 'disconnected';
                 return 'disconnected';
             } else {
             } else {
                 return 'unknown';
                 return 'unknown';
             }
             }
-
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Error checking real VPN status: ' . $e->getMessage());
             Log::error('Error checking real VPN status: ' . $e->getMessage());
             return 'error';
             return 'error';
@@ -121,7 +115,6 @@ class VpnManager
         try {
         try {
             $realStatus = $this->checkRealVpnStatus();
             $realStatus = $this->checkRealVpnStatus();
 
 
-            // Aggiorna il database con lo stato reale
             \DB::table('vpn_status')->updateOrInsert(
             \DB::table('vpn_status')->updateOrInsert(
                 ['id' => 1],
                 ['id' => 1],
                 [
                 [
@@ -136,7 +129,6 @@ class VpnManager
             ]);
             ]);
 
 
             return $realStatus;
             return $realStatus;
-
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Error syncing VPN status: ' . $e->getMessage());
             Log::error('Error syncing VPN status: ' . $e->getMessage());
             return 'error';
             return 'error';
@@ -146,31 +138,63 @@ class VpnManager
     public function connectVpn()
     public function connectVpn()
     {
     {
         try {
         try {
-            // Prima controlla se è già connesso
             $currentStatus = $this->checkRealVpnStatus();
             $currentStatus = $this->checkRealVpnStatus();
             if ($currentStatus === 'connected') {
             if ($currentStatus === 'connected') {
                 Log::info('VPN already connected, no action needed');
                 Log::info('VPN already connected, no action needed');
                 return true;
                 return true;
             }
             }
 
 
-            $scriptPath = storage_path('app/' . $this->scriptPath);
+            $scriptPath = storage_path($this->scriptPath);
+            $configPath = storage_path($this->configPath);
 
 
+            // Check if both script and config exist
             if (!file_exists($scriptPath)) {
             if (!file_exists($scriptPath)) {
                 Log::error('Script VPN non trovato: ' . $scriptPath);
                 Log::error('Script VPN non trovato: ' . $scriptPath);
                 return false;
                 return false;
             }
             }
 
 
-            // Esegue lo script in background
-            $command = "bash {$scriptPath} > /dev/null 2>&1 &";
+            if (!file_exists($configPath)) {
+                Log::error('Config VPN non trovato: ' . $configPath);
+                return false;
+            }
+
+            // Make sure script is executable
+            $this->makeScriptExecutable();
+
+            // Execute the script and capture output
+            $command = "timeout 60 bash {$scriptPath} 2>&1";
             exec($command, $output, $returnVar);
             exec($command, $output, $returnVar);
 
 
             Log::info('Comando VPN connect eseguito', [
             Log::info('Comando VPN connect eseguito', [
                 'command' => $command,
                 'command' => $command,
+                'output' => $output,
                 'return_var' => $returnVar
                 'return_var' => $returnVar
             ]);
             ]);
 
 
-            return true;
+            // Wait a moment and check status
+            sleep(5);
+            $attempts = 0;
+            $maxAttempts = 12; // 1 minute total (5 seconds * 12)
+
+            while ($attempts < $maxAttempts) {
+                $newStatus = $this->checkRealVpnStatus();
+
+                if ($newStatus === 'connected') {
+                    $this->syncStatusWithSystem();
+                    Log::info('VPN connection successful after ' . ($attempts + 1) . ' attempts');
+                    return true;
+                }
+
+                sleep(5);
+                $attempts++;
+            }
 
 
+            Log::warning('VPN connection timeout or failed', [
+                'final_status' => $this->checkRealVpnStatus(),
+                'attempts' => $attempts
+            ]);
+
+            return false;
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Errore nell\'esecuzione del comando VPN connect: ' . $e->getMessage());
             Log::error('Errore nell\'esecuzione del comando VPN connect: ' . $e->getMessage());
             return false;
             return false;
@@ -180,11 +204,9 @@ class VpnManager
     public function disconnectVpn()
     public function disconnectVpn()
     {
     {
         try {
         try {
-            // Comando per disconnettere VPN Cisco AnyConnect
             $command = "/opt/cisco/anyconnect/bin/vpn disconnect > /dev/null 2>&1 &";
             $command = "/opt/cisco/anyconnect/bin/vpn disconnect > /dev/null 2>&1 &";
             exec($command, $output, $returnVar);
             exec($command, $output, $returnVar);
 
 
-            // Aggiorna lo stato nel database
             \DB::table('vpn_status')->updateOrInsert(
             \DB::table('vpn_status')->updateOrInsert(
                 ['id' => 1],
                 ['id' => 1],
                 [
                 [
@@ -200,7 +222,6 @@ class VpnManager
             ]);
             ]);
 
 
             return true;
             return true;
-
         } catch (\Exception $e) {
         } catch (\Exception $e) {
             Log::error('Errore nell\'esecuzione del comando VPN disconnect: ' . $e->getMessage());
             Log::error('Errore nell\'esecuzione del comando VPN disconnect: ' . $e->getMessage());
             return false;
             return false;
@@ -210,7 +231,7 @@ class VpnManager
     public function makeScriptExecutable()
     public function makeScriptExecutable()
     {
     {
         try {
         try {
-            $fullPath = storage_path('app/' . $this->scriptPath);
+            $fullPath = storage_path($this->scriptPath);
             chmod($fullPath, 0755);
             chmod($fullPath, 0755);
             return true;
             return true;
         } catch (\Exception $e) {
         } catch (\Exception $e) {

+ 1 - 1
storage/scripts/vpn-connect.sh

@@ -29,7 +29,7 @@ fi
 log_message "INFO: Avvio connessione VPN..."
 log_message "INFO: Avvio connessione VPN..."
 
 
 # Esegue la connessione VPN
 # Esegue la connessione VPN
-echo -e "${VPN_USERNAME}\n${VPN_PASSWORD}\ny" | /opt/cisco/anyconnect/bin/vpn -s connect "$VPN_SERVER"
+printf "${VPN_USERNAME}\n${VPN_PASSWORD}\ny" | /opt/cisco/anyconnect/bin/vpn -s connect "$VPN_SERVER"
 
 
 # Controlla il risultato
 # Controlla il risultato
 if [[ $? -eq 0 ]]; then
 if [[ $? -eq 0 ]]; then