64 lines
2.3 KiB
PHP
64 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Support\WoltGuard;
|
|
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
trait Probes
|
|
{
|
|
protected function check(string $source): bool
|
|
{
|
|
if (str_starts_with($source, 'systemd:')) return $this->probeSystemd(substr($source, 8));
|
|
if (str_starts_with($source, 'tcp:')) return $this->probeTcp(...$this->splitTcp(substr($source, 4)));
|
|
if (str_starts_with($source, 'socket:')) return @file_exists(substr($source, 7));
|
|
if (str_starts_with($source, 'pid:')) return $this->probePid(substr($source, 4));
|
|
if (str_starts_with($source, 'proc:')) return $this->probeProcessRegex(substr($source, 5));
|
|
if ($source === 'db') return $this->probeDatabase();
|
|
return false;
|
|
}
|
|
|
|
protected function splitTcp(string $s): array { [$h,$p] = explode(':', $s, 2); return [$h,(int)$p]; }
|
|
|
|
protected function probeSystemd(string $unit): bool
|
|
{
|
|
$bin = file_exists('/bin/systemctl') ? '/bin/systemctl'
|
|
: (file_exists('/usr/bin/systemctl') ? '/usr/bin/systemctl' : 'systemctl');
|
|
$cmd = sprintf('%s is-active --quiet %s 2>/dev/null', escapeshellcmd($bin), escapeshellarg($unit));
|
|
$exit = null; @exec($cmd, $_, $exit);
|
|
return $exit === 0;
|
|
}
|
|
|
|
protected function probeTcp(string $host, int $port, int $timeout = 1): bool
|
|
{
|
|
$fp = @fsockopen($host, $port, $e1, $e2, $timeout);
|
|
if (is_resource($fp)) { fclose($fp); return true; }
|
|
return false;
|
|
}
|
|
|
|
protected function probePid(string $path): bool
|
|
{
|
|
if (!@is_file($path)) return false;
|
|
$pid = (int) trim(@file_get_contents($path) ?: '');
|
|
return $pid > 1 && @posix_kill($pid, 0);
|
|
}
|
|
|
|
protected function probeProcessRegex(string $regex): bool
|
|
{
|
|
$regex = '#' . $regex . '#i';
|
|
foreach (@scandir('/proc') ?: [] as $d) {
|
|
if (!ctype_digit($d)) continue;
|
|
$cmd = @file_get_contents("/proc/$d/cmdline");
|
|
if (!$cmd) continue;
|
|
$cmd = str_replace("\0", ' ', $cmd);
|
|
if (preg_match($regex, $cmd)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
protected function probeDatabase(): bool
|
|
{
|
|
try { DB::connection()->getPdo(); return true; }
|
|
catch (\Throwable) { return false; }
|
|
}
|
|
}
|