php-adb/api.php

327 lines
12 KiB
PHP

<?php
declare(strict_types=1);
require __DIR__ . '/lib/adb.php';
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
function json_out(array $data, int $status = 200): never
{
http_response_code($status);
echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
function read_input(): array
{
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';
if (stripos($contentType, 'application/json') !== false) {
$raw = file_get_contents('php://input');
$decoded = json_decode($raw ?: '', true);
if (is_array($decoded)) {
return $decoded;
}
}
return $_POST;
}
function scan_subnets(): array
{
$subnets = ['192.168.1.', '192.168.2.'];
$targets = [];
foreach ($subnets as $prefix) {
for ($i = 1; $i <= 254; $i++) {
$targets[] = $prefix . $i;
}
}
$pending = []; // ip => [socket, deadline]
$found = [];
$timeout = 1.2;
$start = microtime(true);
foreach ($targets as $ip) {
$errno = 0;
$errstr = '';
$sock = @stream_socket_client(
'tcp://' . $ip . ':5555',
$errno,
$errstr,
0.1,
STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT
);
if (is_resource($sock)) {
stream_set_blocking($sock, false);
$pending[$ip] = ['sock' => $sock, 'deadline' => $start + $timeout];
}
}
while (!empty($pending)) {
$write = [];
$except = [];
foreach ($pending as $ip => $info) {
$write[] = $info['sock'];
$except[] = $info['sock'];
}
$read = null;
$ready = @stream_select($read, $write, $except, 0, 100000); // 100ms
$now = microtime(true);
$writable = [];
foreach ($write as $s) {
$writable[(int) $s] = $s;
}
$errored = [];
foreach ($except as $s) {
$errored[(int) $s] = $s;
}
foreach ($pending as $ip => $info) {
$id = (int) $info['sock'];
$isWritable = isset($writable[$id]);
$isErrored = isset($errored[$id]);
$isExpired = $now >= $info['deadline'];
if ($isWritable || $isErrored) {
$open = false;
if ($isWritable && !$isErrored) {
// For async connects, writable usually means connected; verify SO_ERROR when possible.
$err = null;
if (function_exists('socket_import_stream') && function_exists('socket_get_option')) {
$sockRes = @socket_import_stream($info['sock']);
if ($sockRes !== false && $sockRes !== null) {
$err = @socket_get_option($sockRes, SOL_SOCKET, SO_ERROR);
}
}
$open = ($err === 0 || $err === null);
}
if ($open) {
$found[] = $ip;
}
fclose($info['sock']);
unset($pending[$ip]);
continue;
}
if ($isExpired) {
fclose($info['sock']);
unset($pending[$ip]);
}
}
if ($ready === 0) {
// loop will handle expirations
}
}
sort($found, SORT_NATURAL);
return $found;
}
$action = $_GET['action'] ?? ($_POST['action'] ?? '');
$input = read_input();
if ($action === '' && isset($input['action'])) {
$action = (string) $input['action'];
}
$action = trim((string) $action);
try {
switch ($action) {
case 'status': {
$devices = load_devices();
$adb = adb_devices();
json_out([
'ok' => true,
'adb_available' => adb_available(),
'adb_devices' => $adb,
'known_devices' => $devices,
]);
}
case 'scan': {
$foundIps = scan_subnets();
$known = load_devices();
$knownByIp = [];
foreach ($known as $d) {
if (isset($d['ip'])) {
$knownByIp[$d['ip']] = $d;
}
}
$adb = adb_devices();
$adbByIp = [];
foreach ($adb as $d) {
if (!empty($d['ip'])) {
$adbByIp[$d['ip']] = $d;
}
}
$results = [];
foreach ($foundIps as $ip) {
$k = $knownByIp[$ip] ?? null;
$a = $adbByIp[$ip] ?? null;
$name = trim((string) ($k['name'] ?? ''));
$lookup = lookup_device_name($ip);
if ($lookup !== null && $lookup !== '') {
$name = $lookup;
}
$results[] = [
'ip' => $ip,
'port_open' => true,
'name' => $name,
'last_seen' => gmdate('c'),
'last_connected' => $k['last_connected'] ?? null,
'adb_state' => $a['state'] ?? null,
];
$save = ['last_seen' => gmdate('c')];
if ($name !== '') {
$save['name'] = $name;
}
upsert_device($ip, $save);
}
// Also include known devices that were not found in this scan
foreach ($known as $k) {
$ip = $k['ip'] ?? '';
if (!is_allowed_ip($ip)) {
continue;
}
if (in_array($ip, $foundIps, true)) {
continue;
}
$a = $adbByIp[$ip] ?? null;
$results[] = [
'ip' => $ip,
'port_open' => false,
'name' => $k['name'] ?? '',
'last_seen' => $k['last_seen'] ?? null,
'last_connected' => $k['last_connected'] ?? null,
'adb_state' => $a['state'] ?? null,
];
}
usort($results, function ($a, $b) {
if (($a['port_open'] ?? false) !== ($b['port_open'] ?? false)) {
return ($a['port_open'] ? 0 : 1) <=> ($b['port_open'] ? 0 : 1);
}
return strnatcmp($a['ip'], $b['ip']);
});
json_out([
'ok' => true,
'adb_available' => adb_available(),
'devices' => $results,
'scanned_at' => gmdate('c'),
]);
}
case 'connect': {
$ip = normalize_ip((string) ($input['ip'] ?? ''));
if ($ip === null) {
json_out(['ok' => false, 'error' => 'Invalid IP. Only 192.168.1.* and 192.168.2.* are allowed.'], 400);
}
if (!adb_available()) {
json_out(['ok' => false, 'error' => 'adb is not installed or not in PATH.'], 500);
}
$res = adb_connect($ip);
$name = null;
if ($res['ok']) {
$name = adb_get_name($ip);
upsert_device($ip, [
'name' => $name ?? '',
'last_seen' => gmdate('c'),
'last_connected' => gmdate('c'),
]);
}
$devices = load_devices();
json_out([
'ok' => $res['ok'],
'ip' => $ip,
'name' => $name,
'output' => $res['output'],
'known_devices' => $devices,
'adb_devices' => adb_devices(),
]);
}
case 'disconnect': {
$ip = normalize_ip((string) ($input['ip'] ?? ''));
if ($ip === null) {
json_out(['ok' => false, 'error' => 'Invalid IP.'], 400);
}
if (!adb_available()) {
json_out(['ok' => false, 'error' => 'adb is not installed or not in PATH.'], 500);
}
$res = adb_disconnect($ip);
json_out([
'ok' => $res['ok'],
'ip' => $ip,
'output' => $res['output'],
'adb_devices' => adb_devices(),
]);
}
case 'command': {
$ip = normalize_ip((string) ($input['ip'] ?? ''));
if ($ip === null) {
json_out(['ok' => false, 'error' => 'Invalid IP.'], 400);
}
if (!adb_available()) {
json_out(['ok' => false, 'error' => 'adb is not installed or not in PATH.'], 500);
}
$cmdType = trim((string) ($input['command'] ?? ''));
$result = ['ok' => false, 'output' => 'Unknown command'];
if ($cmdType === 'key') {
$key = strtoupper(trim((string) ($input['keycode'] ?? '')));
$allowed = [
'KEYCODE_HOME', 'KEYCODE_BACK', 'KEYCODE_DPAD_UP', 'KEYCODE_DPAD_DOWN',
'KEYCODE_DPAD_LEFT', 'KEYCODE_DPAD_RIGHT', 'KEYCODE_DPAD_CENTER',
'KEYCODE_ENTER', 'KEYCODE_MENU', 'KEYCODE_APP_SWITCH', 'KEYCODE_POWER',
'KEYCODE_VOLUME_UP', 'KEYCODE_VOLUME_DOWN', 'KEYCODE_VOLUME_MUTE', 'KEYCODE_MUTE',
'KEYCODE_MEDIA_PLAY_PAUSE', 'KEYCODE_MEDIA_PLAY', 'KEYCODE_MEDIA_PAUSE',
'KEYCODE_MEDIA_NEXT', 'KEYCODE_MEDIA_PREVIOUS', 'KEYCODE_MEDIA_STOP',
'KEYCODE_MEDIA_REWIND', 'KEYCODE_MEDIA_FAST_FORWARD',
'KEYCODE_CHANNEL_UP', 'KEYCODE_CHANNEL_DOWN',
'KEYCODE_INFO', 'KEYCODE_GUIDE', 'KEYCODE_SETTINGS',
'KEYCODE_SLEEP', 'KEYCODE_WAKEUP', 'KEYCODE_SOFT_SLEEP',
'KEYCODE_0','KEYCODE_1','KEYCODE_2','KEYCODE_3','KEYCODE_4',
'KEYCODE_5','KEYCODE_6','KEYCODE_7','KEYCODE_8','KEYCODE_9',
'KEYCODE_DEL', 'KEYCODE_FORWARD_DEL', 'KEYCODE_SPACE',
'KEYCODE_SEARCH', 'KEYCODE_NAVIGATE_PREVIOUS', 'KEYCODE_NAVIGATE_NEXT',
];
if (!in_array($key, $allowed, true)) {
json_out(['ok' => false, 'error' => 'Keycode not allowed.'], 400);
}
$result = adb_send_key($ip, $key);
} elseif ($cmdType === 'text') {
$text = (string) ($input['text'] ?? '');
$result = adb_send_text($ip, $text);
} elseif ($cmdType === 'launch_home') {
$result = adb_send_key($ip, 'KEYCODE_HOME');
} elseif ($cmdType === 'shell') {
$raw = (string) ($input['shell'] ?? $input['cmd'] ?? $input['text'] ?? '');
$shellCmd = normalize_adb_shell_command($raw);
if ($shellCmd === '') {
json_out(['ok' => false, 'error' => 'Empty or comment-only shell command.'], 400);
}
$res = adb_run_shell_command($ip, $shellCmd, 30);
$result = ['ok' => $res['ok'], 'output' => $res['output'], 'command_line' => $shellCmd];
} else {
json_out(['ok' => false, 'error' => 'Unsupported command type.'], 400);
}
json_out([
'ok' => $result['ok'],
'ip' => $ip,
'command' => $cmdType,
'output' => $result['output'],
]);
}
default:
json_out(['ok' => false, 'error' => 'Unknown action.'], 400);
}
} catch (Throwable $e) {
json_out(['ok' => false, 'error' => 'Server error: ' . $e->getMessage()], 500);
}