/dev/null')); $bin = $found !== '' ? $found : 'adb'; return $bin; } function adb_available(): bool { $bin = adb_bin(); $out = []; $code = 1; exec(escapeshellcmd($bin) . ' version 2>&1', $out, $code); return $code === 0; } function is_allowed_ip(string $ip): bool { if (!preg_match('/^192\.168\.(1|2)\.([0-9]{1,3})$/', $ip, $m)) { return false; } $octet = (int) $m[2]; return $octet >= 1 && $octet <= 254; } function normalize_ip(string $ip): ?string { $ip = trim($ip); return is_allowed_ip($ip) ? $ip : null; } function adb_target(string $ip): string { return $ip . ':5555'; } function run_cmd(string $cmd, int $timeout = 10): array { $descriptors = [ 0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ]; $proc = proc_open($cmd, $descriptors, $pipes, null, null); if (!is_resource($proc)) { return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Failed to start process', 'timed_out' => false]; } fclose($pipes[0]); stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false); $stdout = ''; $stderr = ''; $start = microtime(true); $timedOut = false; while (true) { $status = proc_get_status($proc); $stdout .= stream_get_contents($pipes[1]); $stderr .= stream_get_contents($pipes[2]); if (!$status['running']) { break; } if ((microtime(true) - $start) > $timeout) { $timedOut = true; proc_terminate($proc, 9); break; } usleep(50000); } $stdout .= stream_get_contents($pipes[1]); $stderr .= stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $code = proc_close($proc); if ($timedOut) { $code = 124; } return [ 'ok' => $code === 0 && !$timedOut, 'code' => $code, 'stdout' => trim($stdout), 'stderr' => trim($stderr), 'timed_out' => $timedOut, ]; } function run_cmd_array(array $args, int $timeout = 15): array { $descriptors = [ 0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ]; $proc = proc_open($args, $descriptors, $pipes, null, null); if (!is_resource($proc)) { return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Failed to start process', 'timed_out' => false]; } fclose($pipes[0]); stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false); $stdout = ''; $stderr = ''; $start = microtime(true); $timedOut = false; while (true) { $status = proc_get_status($proc); $stdout .= stream_get_contents($pipes[1]); $stderr .= stream_get_contents($pipes[2]); if (!$status['running']) { break; } if ((microtime(true) - $start) > $timeout) { $timedOut = true; proc_terminate($proc, 9); break; } usleep(50000); } $stdout .= stream_get_contents($pipes[1]); $stderr .= stream_get_contents($pipes[2]); fclose($pipes[1]); fclose($pipes[2]); $code = proc_close($proc); if ($timedOut) { $code = 124; } return [ 'ok' => $code === 0 && !$timedOut, 'code' => $code, 'stdout' => trim($stdout), 'stderr' => trim($stderr), 'timed_out' => $timedOut, ]; } function adb_connect(string $ip): array { $target = adb_target($ip); $cmd = escapeshellcmd(adb_bin()) . ' connect ' . escapeshellarg($target) . ' 2>&1'; $res = run_cmd($cmd, 12); $out = trim($res['stdout'] . "\n" . $res['stderr']); $ok = stripos($out, 'connected') !== false || stripos($out, 'already connected') !== false; return ['ok' => $ok, 'output' => $out, 'target' => $target]; } function adb_disconnect(string $ip): array { $target = adb_target($ip); $cmd = escapeshellcmd(adb_bin()) . ' disconnect ' . escapeshellarg($target) . ' 2>&1'; $res = run_cmd($cmd, 8); $out = trim($res['stdout'] . "\n" . $res['stderr']); return ['ok' => $res['code'] === 0, 'output' => $out, 'target' => $target]; } function adb_devices(): array { $cmd = escapeshellcmd(adb_bin()) . ' devices -l 2>&1'; $res = run_cmd($cmd, 8); $devices = []; $lines = preg_split('/\r?\n/', $res['stdout']); foreach ($lines as $line) { $line = trim((string) $line); if ($line === '' || str_starts_with($line, 'List of devices') || str_starts_with($line, '*')) { continue; } if (preg_match('/^(\S+)\s+(device|offline|unauthorized|connecting)\b(.*)$/', $line, $m)) { $serial = $m[1]; $state = $m[2]; $meta = trim($m[3]); $ip = null; if (preg_match('/^(\d+\.\d+\.\d+\.\d+):\d+$/', $serial, $im)) { $candidate = $im[1]; if (is_allowed_ip($candidate)) { $ip = $candidate; } } $devices[] = [ 'serial' => $serial, 'state' => $state, 'meta' => $meta, 'ip' => $ip, ]; } } return $devices; } function adb_shell(string $ip, string $shellCmd, int $timeout = 10): array { $target = adb_target($ip); $cmd = escapeshellcmd(adb_bin()) . ' -s ' . escapeshellarg($target) . ' shell ' . $shellCmd . ' 2>&1'; return run_cmd($cmd, $timeout); } function adb_get_name(string $ip): ?string { $props = [ 'ro.product.model', 'ro.product.name', 'ro.product.device', ]; foreach ($props as $prop) { $res = adb_shell($ip, escapeshellarg('getprop') . ' ' . escapeshellarg($prop), 8); $val = trim($res['stdout']); if ($res['code'] === 0 && $val !== '' && strtolower($val) !== 'unknown') { return $val; } } return null; } function lookup_device_name(string $ip): ?string { // Try Google Cast / Android TV eureka_info (no ADB, no auth) $url = 'http://' . $ip . ':8008/setup/eureka_info'; $ctx = stream_context_create([ 'http' => [ 'method' => 'GET', 'timeout' => 1.5, 'ignore_errors' => true, 'header' => "Accept: application/json\r\n", ], ]); $raw = @file_get_contents($url, false, $ctx); if (is_string($raw) && $raw !== '') { $data = json_decode($raw, true); if (is_array($data)) { $name = trim((string) ($data['name'] ?? '')); if ($name !== '') { return $name; } } } // Fallback: reverse DNS $host = @gethostbyaddr($ip); if (is_string($host) && $host !== '' && $host !== $ip) { return $host; } return null; } function adb_send_key(string $ip, string $keycode): array { if (!preg_match('/^KEYCODE_[A-Z0-9_]+$/', $keycode)) { return ['ok' => false, 'output' => 'Invalid keycode']; } $res = adb_shell($ip, 'input keyevent ' . escapeshellarg($keycode), 8); $out = trim($res['stdout'] . "\n" . $res['stderr']); return ['ok' => $res['ok'], 'output' => $out]; } function adb_send_text(string $ip, string $text): array { $text = str_replace(["\r", "\n"], ' ', $text); $text = trim($text); if ($text === '') { return ['ok' => false, 'output' => 'Text is empty']; } $len = function_exists('mb_strlen') ? mb_strlen($text) : strlen($text); if ($len > 200) { return ['ok' => false, 'output' => 'Text too long (max 200 chars)']; } // adb input text uses %s for spaces and requires escaping certain chars. $encoded = ''; $chars = preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY); foreach ($chars as $ch) { if ($ch === ' ') { $encoded .= '%s'; } elseif (preg_match('/[A-Za-z0-9._@,:\/-]/', $ch)) { $encoded .= $ch; } else { // Fallback: skip unsupported chars to avoid shell injection/adb quirks. $encoded .= ''; } } if ($encoded === '') { return ['ok' => false, 'output' => 'Text contains no supported characters for adb input text']; } $res = adb_shell($ip, 'input text ' . escapeshellarg($encoded), 10); $out = trim($res['stdout'] . "\n" . $res['stderr']); return ['ok' => $res['ok'], 'output' => $out]; } function normalize_adb_shell_command(string $line): string { $cmd = trim($line); if ($cmd === '' || str_starts_with($cmd, '#')) { return ''; } // Strip inline comment (simple heuristic: " #...") $hashPos = strpos($cmd, ' #'); if ($hashPos !== false) { $cmd = trim(substr($cmd, 0, $hashPos)); } if (str_starts_with($cmd, '#')) { return ''; } // Strip common prefixes if (preg_match('/^adb\s+-s\s+\S+\s+shell\s+(.+)$/i', $cmd, $m)) { $cmd = trim($m[1]); } elseif (preg_match('/^adb\s+shell\s+(.+)$/i', $cmd, $m)) { $cmd = trim($m[1]); } return trim($cmd); } function adb_run_shell_command(string $ip, string $command, int $timeout = 20): array { $command = trim($command); if ($command === '') { return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Empty command', 'timed_out' => false, 'output' => 'Empty command']; } // Basic guardrails: no newlines, limit length if (preg_match('/[\r\n\0]/', $command)) { return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Invalid command', 'timed_out' => false, 'output' => 'Invalid command']; } if (strlen($command) > 500) { return ['ok' => false, 'code' => 1, 'stdout' => '', 'stderr' => 'Command too long', 'timed_out' => false, 'output' => 'Command too long (max 500 chars)']; } $target = adb_target($ip); $res = run_cmd_array([adb_bin(), '-s', $target, 'shell', $command], $timeout); $out = trim($res['stdout'] . "\n" . $res['stderr']); $res['output'] = $out; return $res; } function devices_path(): string { return __DIR__ . '/../data/devices.json'; } function load_devices(): array { $path = devices_path(); if (!is_file($path)) { return []; } $raw = file_get_contents($path); if ($raw === false || trim($raw) === '') { return []; } $data = json_decode($raw, true); return is_array($data) ? $data : []; } function prune_devices(array $devices, int $maxAgeDays = 60, int $maxEntries = 100): array { $cutoff = time() - ($maxAgeDays * 86400); $out = []; foreach ($devices as $d) { if (!is_array($d)) continue; $ip = (string) ($d['ip'] ?? ''); if (!is_allowed_ip($ip)) continue; $seen = strtotime((string) ($d['last_seen'] ?? '')) ?: 0; $conn = strtotime((string) ($d['last_connected'] ?? '')) ?: 0; $latest = max($seen, $conn); // Keep if recently seen/connected, or if never timestamped but present if ($latest > 0 && $latest < $cutoff) continue; $out[] = $d; } usort($out, function ($a, $b) { $aT = max(strtotime((string) ($a['last_seen'] ?? '')) ?: 0, strtotime((string) ($a['last_connected'] ?? '')) ?: 0); $bT = max(strtotime((string) ($b['last_seen'] ?? '')) ?: 0, strtotime((string) ($b['last_connected'] ?? '')) ?: 0); return $bT <=> $aT; }); if (count($out) > $maxEntries) { $out = array_slice($out, 0, $maxEntries); } return $out; } function save_devices(array $devices): bool { $devices = prune_devices($devices); $path = devices_path(); $dir = dirname($path); if (!is_dir($dir)) { @mkdir($dir, 0775, true); } $tmp = $path . '.tmp'; $json = json_encode(array_values($devices), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); if ($json === false) { return false; } $ok = @file_put_contents($tmp, $json . "\n", LOCK_EX) !== false; if (!$ok) { return false; } return @rename($tmp, $path); } function upsert_device(string $ip, array $fields): array { $devices = load_devices(); $found = false; foreach ($devices as &$d) { if (($d['ip'] ?? '') === $ip) { $d = array_merge($d, $fields); $d['ip'] = $ip; $found = true; break; } } unset($d); if (!$found) { $devices[] = array_merge(['ip' => $ip, 'name' => '', 'last_seen' => null, 'last_connected' => null], $fields); } save_devices($devices); return $devices; }