[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 $info) { $write[] = $info['sock']; $except[] = $info['sock']; } $read = null; @stream_select($read, $write, $except, 0, 100000); $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) { $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]); } } } sort($found, SORT_NATURAL); return $found; } function scan_eureka_info(array $targets): array { // Returns ip => name for devices responding on 8008/setup/eureka_info $found = []; if (!function_exists('curl_multi_init')) { return $found; } foreach (array_chunk($targets, 128) as $chunk) { $mh = curl_multi_init(); $handles = []; foreach ($chunk as $ip) { $url = 'http://' . $ip . ':8008/setup/eureka_info'; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT_MS => 700, CURLOPT_TIMEOUT_MS => 2000, CURLOPT_HTTPHEADER => ['Accept: application/json'], ]); curl_multi_add_handle($mh, $ch); $handles[$ip] = $ch; } do { $status = curl_multi_exec($mh, $running); if ($running) curl_multi_select($mh, 0.2); } while ($running && $status === CURLM_OK); foreach ($handles as $ip => $ch) { $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $body = (string) curl_multi_getcontent($ch); if ($code === 200 && $body !== '') { $data = json_decode($body, true); if (is_array($data)) { $name = trim((string) ($data['name'] ?? '')); if ($name !== '') $found[$ip] = $name; } } curl_multi_remove_handle($mh, $ch); curl_close($ch); } curl_multi_close($mh); } 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': { $targets = scan_subnet_targets(); $port5555 = scan_port_5555($targets); $eureka = scan_eureka_info($targets); // ip => name $discoveredIps = array_values(array_unique(array_merge($port5555, array_keys($eureka)))); sort($discoveredIps, SORT_NATURAL); $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 ($discoveredIps as $ip) { $k = $knownByIp[$ip] ?? null; $a = $adbByIp[$ip] ?? null; $name = trim((string) ($k['name'] ?? '')); $eurekaName = trim((string) ($eureka[$ip] ?? '')); if ($eurekaName !== '') { $name = $eurekaName; } $portOpen = in_array($ip, $port5555, true); $results[] = [ 'ip' => $ip, 'port_open' => $portOpen, 'discovered' => 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); } // Include known devices not discovered in this scan foreach ($known as $k) { $ip = $k['ip'] ?? ''; if (!is_allowed_ip($ip)) continue; if (in_array($ip, $discoveredIps, true)) continue; $a = $adbByIp[$ip] ?? null; $results[] = [ 'ip' => $ip, 'port_open' => false, 'discovered' => 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(), 'adb_devices' => $adb, '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']) { $lookupName = lookup_device_name($ip); $adbName = adb_get_name($ip); $name = $lookupName ?: $adbName; $save = [ 'last_seen' => gmdate('c'), 'last_connected' => gmdate('c'), ]; if ($name !== null && $name !== '') { $save['name'] = $name; } upsert_device($ip, $save); } $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 'delete_device': { $ip = normalize_ip((string) ($input['ip'] ?? '')); if ($ip === null) { json_out(['ok' => false, 'error' => 'Invalid IP.'], 400); } $devices = load_devices(); $before = count($devices); $devices = array_values(array_filter($devices, fn($d) => ($d['ip'] ?? '') !== $ip)); if (count($devices) === $before) { json_out(['ok' => false, 'error' => 'Device not found.'], 404); } if (!save_devices($devices)) { json_out(['ok' => false, 'error' => 'Failed to save devices.'], 500); } json_out(['ok' => true, 'ip' => $ip, 'known_devices' => $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); }