php-adb/lib/adb.php

299 lines
8.4 KiB
PHP

<?php
declare(strict_types=1);
function adb_bin(): string
{
static $bin = null;
if ($bin !== null) {
return $bin;
}
$found = trim((string) shell_exec('command -v adb 2>/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 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 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 save_devices(array $devices): bool
{
$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;
}