'choose-a-long-random-password', * * // Access token the apps must send too. Leave empty for a bridge anyone may use. * 'token' => '', * * // MySQL / MariaDB instead of the SQLite file. Leave 'dsn' out to keep SQLite. * // 'dsn' => 'mysql:host=localhost;dbname=mytools;charset=utf8mb4', * // 'db_user' => 'mytools', * // 'db_pass' => 'database-password', * * // Audit log (metadata only): days kept, and days until addresses are blanked (1.2.3.xxx). * 'log_keep_days' => 90, * 'log_anonymize_days' => 30, * * // Only if a proxy or CDN sits in front of this server: its address(es), so X-Forwarded-For is believed. * // 'trusted_proxies' => ['203.0.113.10'], * ]; * * MIT licence. The QR code generator at the end is qrcode-generator by Kazuhiko Arase (MIT). */ $defaults = [ // If not empty, apps must send this token too. Use it when the bridge is public and should be for you only. 'token' => '', // Database. Leave 'dsn' empty for SQLite (a file is created next to this script on first run). // For MySQL/MariaDB, for example: 'mysql:host=localhost;dbname=mytools;charset=utf8mb4' 'dsn' => '', 'db_user' => '', 'db_pass' => '', 'table_prefix' => 'mat_', // How long messages are kept, and the most one room (group) may hold. 'keep_hours' => 72, 'room_max_messages' => 300, // The newest message of a "slot" (the apps use one per device for its last known location) is kept apart from // the queue above, so it is not pushed out by other messages, until it is replaced or this old. Largest size in bytes. 'slot_max_bytes' => 4096, 'slot_max_per_room' => 20, // The most slots in the whole database; when there are more, the oldest are dropped. Stops somebody from filling the disk. 'slot_max_total' => 10000, 'max_message_bytes' => 6 * 1024 * 1024, // Longest a poll request is held open (seconds). Lower this on servers with few PHP workers. 'max_wait' => 25, // Requests per minute and address. 'send_per_minute' => 240, 'poll_per_minute' => 600, // ---- audit log: metadata only, never message contents or tokens ---- 'log' => true, // Log rows are deleted after this many days. 'log_keep_days' => 90, // After this many days the last part of the address in the log is blanked (1.2.3.4 -> 1.2.3.xxx). 'log_anonymize_days' => 30, // The daily counters per address and room are kept this long (anonymized the same way). 'stats_keep_days' => 365, // Password for the admin page (?a=admin). Empty: there is no admin page. 'admin_token' => '', // Addresses of proxies in front of this server whose X-Forwarded-For header is believed. Empty: never believed. 'trusted_proxies' => [], // The admin page lists an address that used this many rooms, and a room used from this many addresses, in the period. 'alert_rooms_per_ip' => 5, 'alert_ips_per_room' => 6, // ---- watchdog: a request that never finishes keeps a PHP worker for ever (a worker blocked inside the system cannot // stop itself), and when every worker is stuck the bridge is down. Every request therefore writes down its process // id and start time, and any later request checks for entries older than this many seconds: they are logged // (event "stalled" in the audit log) and, if watchdog_kill is on, the worker is ended, but only after it was checked // to be a PHP process that has not started a newer request. Where PHP workers are not restarted by a server // (a fixed pool of php-cgi processes), something else has to start the missing ones again. 'watchdog' => true, 'watchdog_seconds' => 120, 'watchdog_kill' => true, ]; $cfg = $defaults; if (is_file(__DIR__ . '/bridge.config.php')) { $extra = include __DIR__ . '/bridge.config.php'; if (is_array($extra)) $cfg = array_merge($cfg, $extra); } const BRIDGE_VERSION = 3; // What the log is told about this request; filled in as the request is handled, written when it ends. $started = microtime(true); $ctx = ['action' => 'page', 'rooms' => [], 'bytes' => 0, 'seq' => null, 'event' => '', 'note' => '']; // The audit log is written after the response, also when the client has left; a poll turns this off below, so that it // stops as soon as its client is gone instead of keeping a PHP worker busy. ignore_user_abort(true); @set_time_limit(60); function ctx($key, $value) { global $ctx; $ctx[$key] = $value; } function clientIp() { global $cfg; static $ip = null; if ($ip !== null) return $ip; $ip = $_SERVER['REMOTE_ADDR'] ?? '?'; $trusted = (array)$cfg['trusted_proxies']; if ($trusted && in_array($ip, $trusted, true) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $chain = array_map('trim', explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])); // From the right: the first address that is not one of our own proxies is the client. for ($i = count($chain) - 1; $i >= 0; $i--) { if (!in_array($chain[$i], $trusted, true) && filter_var($chain[$i], FILTER_VALIDATE_IP)) { $ip = $chain[$i]; break; } } } return $ip; } function fail($code, $message, $event = 'error') { ctx('event', $event); http_response_code($code); header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode(['error' => $message]); exit; } function database() { global $cfg; static $pdo = null; if ($pdo) return $pdo; $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]; $p = $cfg['table_prefix']; if ($cfg['dsn'] === '') { $files = glob(__DIR__ . '/.htbridge-*.sqlite'); $file = $files ? $files[0] : __DIR__ . '/.htbridge-' . bin2hex(random_bytes(5)) . '.sqlite'; $pdo = new PDO('sqlite:' . $file, null, null, $options); $pdo->exec('PRAGMA journal_mode=WAL'); $pdo->exec('PRAGMA busy_timeout=5000'); $pdo->exec('PRAGMA synchronous=NORMAL'); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}msgs (id INTEGER PRIMARY KEY AUTOINCREMENT, room TEXT NOT NULL, ts INTEGER NOT NULL, body BLOB NOT NULL)"); $pdo->exec("CREATE INDEX IF NOT EXISTS {$p}msgs_room ON {$p}msgs (room, id)"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}slots (room TEXT NOT NULL, slot TEXT NOT NULL, ts INTEGER NOT NULL, body BLOB NOT NULL, PRIMARY KEY (room, slot))"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}rate (k TEXT PRIMARY KEY, n INTEGER NOT NULL, win INTEGER NOT NULL)"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}log (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, ip TEXT NOT NULL, ua TEXT, method TEXT, act TEXT, room TEXT, status INTEGER, nbytes INTEGER, seq INTEGER, ms INTEGER, ev TEXT, note TEXT)"); $pdo->exec("CREATE INDEX IF NOT EXISTS {$p}log_ts ON {$p}log (ts)"); $pdo->exec("CREATE INDEX IF NOT EXISTS {$p}log_ip ON {$p}log (ip, ts)"); $pdo->exec("CREATE INDEX IF NOT EXISTS {$p}log_room ON {$p}log (room, ts)"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}stats (d INTEGER NOT NULL, ip TEXT NOT NULL, room TEXT NOT NULL, req INTEGER NOT NULL, nbytes INTEGER NOT NULL, t1 INTEGER NOT NULL, t2 INTEGER NOT NULL, PRIMARY KEY (d, ip, room))"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}block (kind TEXT NOT NULL, value TEXT NOT NULL, reason TEXT, ts INTEGER NOT NULL, PRIMARY KEY (kind, value))"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}meta (k TEXT PRIMARY KEY, v INTEGER NOT NULL)"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}inflight (id TEXT PRIMARY KEY, pid INTEGER NOT NULL, t0 INTEGER NOT NULL, act TEXT)"); $pdo->exec("CREATE INDEX IF NOT EXISTS {$p}inflight_t0 ON {$p}inflight (t0)"); if (!is_file(__DIR__ . '/.htaccess')) { @file_put_contents(__DIR__ . '/.htaccess', "# MyTools bridge: the database must never be downloadable\n\n Require all denied\n\n"); } } else { $pdo = new PDO($cfg['dsn'], $cfg['db_user'], $cfg['db_pass'], $options); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}msgs (id BIGINT AUTO_INCREMENT PRIMARY KEY, room CHAR(32) NOT NULL, ts INT NOT NULL, body MEDIUMBLOB NOT NULL, KEY room_id (room, id), KEY ts (ts)) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}slots (room CHAR(32) NOT NULL, slot CHAR(32) NOT NULL, ts INT NOT NULL, body BLOB NOT NULL, PRIMARY KEY (room, slot)) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}rate (k VARCHAR(80) PRIMARY KEY, n INT NOT NULL, win INT NOT NULL) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}log (id BIGINT AUTO_INCREMENT PRIMARY KEY, ts INT NOT NULL, ip VARCHAR(45) NOT NULL, ua VARCHAR(120), method VARCHAR(8), act VARCHAR(8), room CHAR(32), status SMALLINT, nbytes BIGINT, seq BIGINT, ms INT, ev VARCHAR(24), note VARCHAR(80), KEY ts (ts), KEY ip_ts (ip, ts), KEY room_ts (room, ts)) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}stats (d INT NOT NULL, ip VARCHAR(45) NOT NULL, room CHAR(32) NOT NULL, req INT NOT NULL, nbytes BIGINT NOT NULL, t1 INT NOT NULL, t2 INT NOT NULL, PRIMARY KEY (d, ip, room)) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}block (kind VARCHAR(8) NOT NULL, value VARCHAR(64) NOT NULL, reason VARCHAR(200), ts INT NOT NULL, PRIMARY KEY (kind, value)) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}meta (k VARCHAR(40) PRIMARY KEY, v INT NOT NULL) ENGINE=InnoDB"); $pdo->exec("CREATE TABLE IF NOT EXISTS {$p}inflight (id CHAR(12) PRIMARY KEY, pid INT NOT NULL, t0 INT NOT NULL, act VARCHAR(8), KEY t0 (t0)) ENGINE=InnoDB"); } return $pdo; } function table($name) { global $cfg; return $cfg['table_prefix'] . $name; } /** Counts a request of this kind from this address in the current minute; stops the request when over the limit. */ function limit($kind, $perMinute) { $pdo = database(); $t = table('rate'); $win = (int)(time() / 60); $key = $kind . '|' . clientIp() . '|' . $win; $up = $pdo->prepare("UPDATE $t SET n = n + 1 WHERE k = ?"); $up->execute([$key]); if ($up->rowCount() === 0) { try { $pdo->prepare("INSERT INTO $t (k, n, win) VALUES (?, 1, ?)")->execute([$key, $win]); } catch (PDOException $e) { // another request created it at the same moment } return; } $row = $pdo->prepare("SELECT n FROM $t WHERE k = ?"); $row->execute([$key]); if ((int)$row->fetchColumn() > $perMinute) fail(429, 'Too many requests', 'ratelimit'); } /** Stops the request if the address or the room has been blocked on the admin page. */ function checkBlocked($room = '') { $pdo = database(); $s = $pdo->prepare('SELECT COUNT(*) FROM ' . table('block') . " WHERE (kind = 'ip' AND value = ?) OR (kind = 'room' AND value = ?)"); $s->execute([clientIp(), $room]); if ((int)$s->fetchColumn() > 0) fail(403, 'Blocked', 'blocked'); } function trimRoom($room) { global $cfg; $pdo = database(); $t = table('msgs'); $pdo->prepare("DELETE FROM $t WHERE room = ? AND id NOT IN (SELECT id FROM (SELECT id FROM $t WHERE room = ? ORDER BY id DESC LIMIT " . (int)$cfg['room_max_messages'] . ') keep)') ->execute([$room, $room]); } function checkToken() { global $cfg; if ($cfg['token'] === '') return; $given = $_SERVER['HTTP_X_BRIDGE_TOKEN'] ?? ($_GET['t'] ?? ''); if (!hash_equals($cfg['token'], (string)$given)) fail(403, 'Wrong or missing access token', 'token'); } function validRoom($room) { return is_string($room) && preg_match('/^[0-9a-f]{32}$/', $room) === 1; } function pageUrl() { $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'); $path = strtok($_SERVER['REQUEST_URI'] ?? '/', '?'); if (substr($path, -10) === '/index.php') $path = substr($path, 0, -9); return ($https ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . $path; } // ------------------------------------------------------------------ the audit log /** 1.2.3.4 -> 1.2.3.xxx, 2001:db8:1:2::5 -> 2001:db8:1::xxxx; the "x" marks an address that is already blanked. */ function anonymizeIp($ip) { if (strpos($ip, 'x') !== false) return $ip; if (strpos($ip, ':') !== false) { $parts = explode(':', $ip); return implode(':', array_slice($parts, 0, 3)) . '::xxxx'; } $parts = explode('.', $ip); return count($parts) === 4 ? $parts[0] . '.' . $parts[1] . '.' . $parts[2] . '.xxx' : $ip; } /** Once an hour: deletes what is too old, and blanks addresses that are old enough. */ function maintenance($pdo) { global $cfg; $now = time(); $hour = (int)($now / 3600); $meta = table('meta'); $last = $pdo->prepare("SELECT v FROM $meta WHERE k = 'maintenance'"); $last->execute(); $v = $last->fetchColumn(); if ($v !== false && (int)$v >= $hour) return; $up = $pdo->prepare("UPDATE $meta SET v = ? WHERE k = 'maintenance'"); $up->execute([$hour]); if ($up->rowCount() === 0) { try { $pdo->prepare("INSERT INTO $meta (k, v) VALUES ('maintenance', ?)")->execute([$hour]); } catch (PDOException $e) { } } $pdo->prepare('DELETE FROM ' . table('msgs') . ' WHERE ts < ?')->execute([$now - (int)($cfg['keep_hours'] * 3600)]); $pdo->prepare('DELETE FROM ' . table('slots') . ' WHERE ts < ?')->execute([$now - (int)($cfg['keep_hours'] * 3600)]); $pdo->prepare('DELETE FROM ' . table('rate') . ' WHERE win < ?')->execute([(int)($now / 60) - 5]); $pdo->prepare('DELETE FROM ' . table('log') . ' WHERE ts < ?')->execute([$now - (int)$cfg['log_keep_days'] * 86400]); $pdo->prepare('DELETE FROM ' . table('stats') . ' WHERE d < ?')->execute([(int)gmdate('Ymd', $now - (int)$cfg['stats_keep_days'] * 86400)]); // Blank the addresses of older rows, a batch at a time. $cut = $now - (int)$cfg['log_anonymize_days'] * 86400; $old = $pdo->prepare('SELECT id, ip FROM ' . table('log') . " WHERE ts < ? AND ip NOT LIKE '%x%' LIMIT 2000"); $old->execute([$cut]); $set = $pdo->prepare('UPDATE ' . table('log') . ' SET ip = ? WHERE id = ?'); foreach ($old->fetchAll() as $row) $set->execute([anonymizeIp($row['ip']), $row['id']]); $st = table('stats'); $old = $pdo->prepare("SELECT d, ip, room, req, nbytes, t1, t2 FROM $st WHERE d < ? AND ip NOT LIKE '%x%' LIMIT 2000"); $old->execute([(int)gmdate('Ymd', $cut)]); foreach ($old->fetchAll() as $row) { $new = anonymizeIp($row['ip']); $exists = $pdo->prepare("SELECT req, nbytes, t1, t2 FROM $st WHERE d = ? AND ip = ? AND room = ?"); $exists->execute([$row['d'], $new, $row['room']]); $other = $exists->fetch(); if ($other) { // Two addresses that become the same: add them up. $pdo->prepare("UPDATE $st SET req = ?, nbytes = ?, t1 = ?, t2 = ? WHERE d = ? AND ip = ? AND room = ?")->execute([ $other['req'] + $row['req'], $other['nbytes'] + $row['nbytes'], min($other['t1'], $row['t1']), max($other['t2'], $row['t2']), $row['d'], $new, $row['room'], ]); $pdo->prepare("DELETE FROM $st WHERE d = ? AND ip = ? AND room = ?")->execute([$row['d'], $row['ip'], $row['room']]); } else { $pdo->prepare("UPDATE $st SET ip = ? WHERE d = ? AND ip = ? AND room = ?")->execute([$new, $row['d'], $row['ip'], $row['room']]); } } } /** * Runs when the request is over. Every send, every failure and every first poll of an address and room in an hour * gets a row in the log; every request is counted in the daily counters. */ function writeLog() { global $cfg, $ctx, $started; if (!$cfg['log']) return; if (function_exists('fastcgi_finish_request')) @fastcgi_finish_request(); try { $pdo = database(); $now = time(); $ip = clientIp(); $status = http_response_code() ?: 200; $rooms = $ctx['rooms']; $bytes = (int)$ctx['bytes']; $day = (int)gmdate('Ymd', $now); $st = table('stats'); $first = false; foreach ($rooms ?: [''] as $room) { $sel = $pdo->prepare("SELECT t2 FROM $st WHERE d = ? AND ip = ? AND room = ?"); $sel->execute([$day, $ip, $room]); $seen = $sel->fetchColumn(); if ($seen === false) { try { $pdo->prepare("INSERT INTO $st (d, ip, room, req, nbytes, t1, t2) VALUES (?, ?, ?, 1, ?, ?, ?)")->execute([$day, $ip, $room, $bytes, $now, $now]); } catch (PDOException $e) { $pdo->prepare("UPDATE $st SET req = req + 1, nbytes = nbytes + ?, t2 = ? WHERE d = ? AND ip = ? AND room = ?")->execute([$bytes, $now, $day, $ip, $room]); } $first = true; } else { $pdo->prepare("UPDATE $st SET req = req + 1, nbytes = nbytes + ?, t2 = ? WHERE d = ? AND ip = ? AND room = ?")->execute([$bytes, $now, $day, $ip, $room]); if ($now - (int)$seen > 3600) $first = true; } } if ($ctx['action'] !== 'poll' || $status !== 200 || $ctx['event'] !== '' || $first) { $pdo->prepare('INSERT INTO ' . table('log') . ' (ts, ip, ua, method, act, room, status, nbytes, seq, ms, ev, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')->execute([ $now, $ip, substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 120), substr((string)($_SERVER['REQUEST_METHOD'] ?? ''), 0, 8), $ctx['action'], $rooms ? implode(',', array_slice($rooms, 0, 1)) : null, $status, $bytes, $ctx['seq'], (int)round((microtime(true) - $started) * 1000), $ctx['event'], substr($ctx['note'] . (count($rooms) > 1 ? ' rooms=' . count($rooms) : ''), 0, 80), ]); } maintenance($pdo); } catch (Throwable $e) { // The log must never get in the way of the bridge. } } register_shutdown_function('writeLog'); // ------------------------------------------------------------------ watchdog $inflightId = null; /** Ends the worker with this process id if it is a PHP process; returns what happened, in a few words. */ function killWorker($pid) { if ($pid <= 0 || $pid === getmypid()) return 'not killed (own process)'; $disabled = array_map('trim', explode(',', (string)ini_get('disable_functions'))); $can = function ($fn) use ($disabled) { return function_exists($fn) && !in_array($fn, $disabled, true); }; if (DIRECTORY_SEPARATOR === '\\') { if (!$can('exec')) return 'not killed (exec is off)'; $out = []; @exec('tasklist /FI "PID eq ' . (int)$pid . '" /FO CSV /NH 2>NUL', $out); $line = strtolower(implode(' ', $out)); if (strpos($line, '"' . $pid . '"') === false) return 'gone'; if (strpos($line, 'php') === false) return 'not killed (not a php process)'; @exec('taskkill /F /PID ' . (int)$pid . ' 2>NUL'); return 'killed'; } $comm = @file_get_contents('/proc/' . (int)$pid . '/comm'); if ($comm === false) return is_dir('/proc') ? 'gone' : 'not killed (cannot check the process)'; if (stripos($comm, 'php') === false) return 'not killed (not a php process)'; if ($can('posix_kill')) { @posix_kill((int)$pid, 9); return 'killed'; } if ($can('exec')) { @exec('kill -9 ' . (int)$pid . ' 2>/dev/null'); return 'killed'; } return 'not killed (no way to do it)'; } /** Looks for requests that have been running for too long; they are written to the audit log and their workers ended. */ function watchdogSweep($pdo) { global $cfg; $t = table('inflight'); $now = time(); $stale = $pdo->prepare("SELECT id, pid, t0, act FROM $t WHERE t0 < ? ORDER BY t0 LIMIT 10"); $stale->execute([$now - (int)$cfg['watchdog_seconds']]); foreach ($stale->fetchAll() as $row) { $take = $pdo->prepare("DELETE FROM $t WHERE id = ?"); $take->execute([$row['id']]); if ($take->rowCount() !== 1) continue; // another request took care of it // A worker that has begun a newer request is not stuck: that old entry was only left behind. $newer = $pdo->prepare("SELECT 1 FROM $t WHERE pid = ? AND t0 >= ? LIMIT 1"); $newer->execute([$row['pid'], $now - (int)$cfg['watchdog_seconds']]); if ($newer->fetchColumn() !== false) { $result = 'worker moved on'; } else { $result = $cfg['watchdog_kill'] ? killWorker((int)$row['pid']) : 'not killed (watchdog_kill is off)'; } if ($cfg['log']) { $pdo->prepare('INSERT INTO ' . table('log') . ' (ts, ip, ua, method, act, room, status, nbytes, seq, ms, ev, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')->execute([ $now, 'watchdog', '', '', substr((string)$row['act'], 0, 8), null, 0, 0, null, ($now - (int)$row['t0']) * 1000, 'stalled', substr('pid ' . $row['pid'] . ': ' . $result, 0, 80), ]); } } } /** Writes down that this request is running, and checks for stalled ones. */ function inflightStart($action) { global $cfg, $inflightId; if (!$cfg['watchdog']) return; try { $pdo = database(); $inflightId = bin2hex(random_bytes(6)); $pdo->prepare('INSERT INTO ' . table('inflight') . ' (id, pid, t0, act) VALUES (?, ?, ?, ?)')->execute([$inflightId, getmypid(), time(), substr($action, 0, 8)]); watchdogSweep($pdo); } catch (Throwable $e) { // The watchdog must never get in the way of the bridge. } } function inflightEnd() { global $inflightId; if ($inflightId === null) return; try { database()->prepare('DELETE FROM ' . table('inflight') . ' WHERE id = ?')->execute([$inflightId]); } catch (Throwable $e) { } $inflightId = null; } register_shutdown_function('inflightEnd'); // ------------------------------------------------------------------ requests $action = $_GET['a'] ?? ''; if (in_array($action, ['ping', 'send', 'poll', 'slots', 'admin'], true)) ctx('action', $action); if (in_array($action, ['send', 'poll', 'slots'], true)) inflightStart($action); if ($action === 'ping') { checkToken(); checkBlocked(); header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode(['mytools_bridge' => BRIDGE_VERSION, 'wait' => (int)$cfg['max_wait']]); exit; } if ($action === 'send') { if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') fail(405, 'POST only', 'method'); checkToken(); $room = $_GET['room'] ?? ''; if (!validRoom($room)) fail(400, 'Bad room', 'badroom'); ctx('rooms', [$room]); checkBlocked($room); $body = file_get_contents('php://input', false, null, 0, (int)$cfg['max_message_bytes'] + 1); if ($body === false || $body === '') fail(400, 'Empty message', 'empty'); ctx('bytes', strlen($body)); if (strlen($body) > $cfg['max_message_bytes']) fail(413, 'Message too large', 'toolarge'); limit('s', (int)$cfg['send_per_minute']); $pdo = database(); $insert = $pdo->prepare('INSERT INTO ' . table('msgs') . ' (room, ts, body) VALUES (?, ?, ?)'); $insert->bindValue(1, $room); $insert->bindValue(2, time(), PDO::PARAM_INT); $insert->bindValue(3, $body, PDO::PARAM_LOB); $insert->execute(); $id = (int)$pdo->lastInsertId(); ctx('seq', $id); if (mt_rand(1, 20) === 1) trimRoom($room); // A slot keeps the newest message of its kind (for example a device's last location) until it is replaced or expires. $slot = $_GET['slot'] ?? ''; if ($slot !== '' && preg_match('/^[0-9a-f]{32}$/', (string)$slot) === 1 && strlen($body) <= (int)$cfg['slot_max_bytes']) { $st = table('slots'); $count = $pdo->prepare("SELECT COUNT(*) FROM $st WHERE room = ? AND slot <> ?"); $count->execute([$room, $slot]); if ((int)$count->fetchColumn() < (int)$cfg['slot_max_per_room']) { $put = $pdo->prepare("REPLACE INTO $st (room, slot, ts, body) VALUES (?, ?, ?, ?)"); $put->bindValue(1, $room); $put->bindValue(2, $slot); $put->bindValue(3, time(), PDO::PARAM_INT); $put->bindValue(4, $body, PDO::PARAM_LOB); $put->execute(); } if (mt_rand(1, 10) === 1) { $total = (int)$pdo->query("SELECT COUNT(*) FROM $st")->fetchColumn(); $over = $total - (int)$cfg['slot_max_total']; if ($over > 0) { // The $over oldest slots (ties broken by room and slot). The inner SELECT is a derived table so that MySQL accepts it. $pdo->exec("DELETE FROM $st WHERE (ts, room, slot) <= (SELECT ts, room, slot FROM (SELECT ts, room, slot FROM $st ORDER BY ts, room, slot LIMIT 1 OFFSET " . ($over - 1) . ') oldest)'); } } } header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode(['ok' => 1, 'seq' => $id]); exit; } if ($action === 'slots') { checkToken(); $room = $_GET['room'] ?? ''; if (!validRoom($room)) fail(400, 'Bad room', 'badroom'); ctx('rooms', [$room]); checkBlocked($room); limit('p', (int)$cfg['poll_per_minute']); $pdo = database(); $list = $pdo->prepare('SELECT slot, ts, body FROM ' . table('slots') . ' WHERE room = ? AND ts >= ? ORDER BY ts DESC LIMIT ' . (int)$cfg['slot_max_per_room']); $list->execute([$room, time() - (int)($cfg['keep_hours'] * 3600)]); $out = []; $bytes = 0; while ($row = $list->fetch()) { $blob = $row['body']; if (is_resource($blob)) $blob = stream_get_contents($blob); $bytes += strlen($blob); $out[] = ['s' => $row['slot'], 't' => (int)$row['ts'], 'b' => base64_encode($blob)]; } ctx('bytes', $bytes); ctx('note', 'slots=' . count($out)); header('Content-Type: application/json'); header('Cache-Control: no-store'); echo json_encode(['slots' => $out, 'now' => time()]); exit; } if ($action === 'poll') { checkToken(); // rooms=:,: (-1 means "just tell me where you are") $wanted = []; foreach (explode(',', (string)($_GET['rooms'] ?? '')) as $part) { $bits = explode(':', $part); if (count($bits) === 2 && validRoom($bits[0]) && is_numeric($bits[1])) $wanted[$bits[0]] = (int)$bits[1]; if (count($wanted) >= 4) break; } if (!$wanted) fail(400, 'No rooms', 'badrooms'); ctx('rooms', array_keys($wanted)); foreach (array_keys($wanted) as $r) checkBlocked($r); limit('p', (int)$cfg['poll_per_minute']); $wait = max(0, min((int)($_GET['wait'] ?? 20), (int)$cfg['max_wait'])); @set_time_limit($wait + 10); // A client that has gone away must not keep this worker: PHP stops the script when a write to it fails. ignore_user_abort(false); $pdo = database(); $t = table('msgs'); $list = $pdo->prepare("SELECT id, ts, body FROM $t WHERE room = ? AND id > ? ORDER BY id LIMIT 50"); $latest = $pdo->prepare("SELECT COALESCE(MAX(id), 0) FROM $t WHERE room = ?"); header('Content-Type: application/json'); header('Cache-Control: no-store'); $deadline = microtime(true) + $wait; // Whatever happens in the loop, it ends a few seconds after the wait is over. $hardEnd = $deadline + 5; $quiet = 0; while (true) { $rooms = []; $bytes = 0; $count = 0; foreach ($wanted as $room => $since) { if ($since < 0) { $latest->execute([$room]); $rooms[$room] = ['seq' => (int)$latest->fetchColumn(), 'msgs' => []]; continue; } $list->bindValue(1, $room); $list->bindValue(2, $since, PDO::PARAM_INT); $list->execute(); $msgs = []; while ($row = $list->fetch()) { $blob = $row['body']; if (is_resource($blob)) $blob = stream_get_contents($blob); if ($msgs && $bytes + strlen($blob) > 6 * 1024 * 1024) break; $bytes += strlen($blob); $count++; $msgs[] = ['i' => (int)$row['id'], 't' => (int)$row['ts'], 'b' => base64_encode($blob)]; } $list->closeCursor(); if ($msgs) $rooms[$room] = ['msgs' => $msgs]; } if ($rooms || microtime(true) >= $deadline || microtime(true) >= $hardEnd) break; if (connection_aborted()) exit; usleep(500000); // A little output now and then lets PHP notice that the app has gone away. if (++$quiet % 10 === 0) { if (connection_aborted()) exit; echo ' '; @ob_flush(); flush(); if (connection_aborted()) exit; } } ctx('bytes', $bytes); ctx('note', 'msgs=' . $count . (count(array_filter($wanted, function ($s) { return $s < 0; })) ? ' first' : '')); echo json_encode(['rooms' => $rooms ?: new stdClass(), 'now' => time()]); exit; } // ------------------------------------------------------------------ the admin page (?a=admin) function h($s) { return htmlspecialchars((string)$s, ENT_QUOTES); } // ------------------------------------------------------------------ translations (human pages only) // // Only the HTML pages people read are translated (the admin page, its login page and the status page). // Everything the apps receive (JSON, errors, ping) stays English. The English table below is the master; // other languages are optional files bridge-.json (for example bridge-deDE.json) next to this file, // see doc/bridge-i18n.md. A key that a language file lacks falls back to English. // // t('key', ...$args) plain text (sprintf-style %1$s placeholders); the caller escapes it with h(). // th('key', ...$args) HTML-safe result for the few keys whose text may contain , (marked [html] below): // everything is escaped, then only exactly those tags are turned back into tags. function i18nEnglish() { return [ '_name' => 'English', '_code' => 'en-US', // language switcher 'lang.label' => 'Language', 'lang.apply' => 'Apply', // admin page: general 'admin.title' => 'MyTools bridge admin', 'admin.off.title' => 'Admin page is off', 'admin.off.body' => 'Set admin_token in bridge.config.php (next to this file) or at the top of this file, then reload.', // [html] 'login.placeholder' => 'Admin password', 'login.button' => 'Sign in', 'login.wrong' => 'Wrong password.', 'admin.signout' => 'Sign out', 'table.nothing' => 'Nothing.', 'period.1' => 'today (UTC day)', 'period.7' => '7 days', 'period.30' => '30 days', // blocking 'kind.ip' => 'address', 'kind.room' => 'room', 'block.button' => 'Block', 'block.confirm.ip' => 'Block this address?', 'block.confirm.room' => 'Block this room?', 'unblock.button' => 'Unblock', // summary 'summary.title' => 'Summary', 'summary.line' => '%1$s requests from %2$s addresses for %3$s rooms · %4$s messages stored (%5$s) · traffic %6$s · %7$s messages waiting now', 'summary.events' => 'Events:', // worth a look 'look.title' => 'Worth a look', 'look.rooms' => 'Addresses that used %1$s or more rooms (scanning or guessing):', 'look.addresses' => 'Rooms used from %1$s or more addresses (a leaked group password, or a very large group):', 'look.failed' => 'Addresses with failed requests:', // busiest 'busiest.addresses' => 'Busiest addresses', 'busiest.rooms' => 'Busiest rooms', // blocked list 'blocked.title' => 'Blocked', 'blocked.placeholder' => 'address or room', 'blocked.reason' => 'reason', 'blocked.note' => 'Blocked requests get status 403 and are logged with the event blocked.', // [html] // log 'log.title' => 'Log', 'log.ip' => 'address starts with', 'log.room' => 'room', 'log.event' => 'event', 'log.anyAction' => 'any action', 'log.failuresOnly' => 'failures only', 'log.filter' => 'Filter', 'log.csv' => 'Download CSV', 'log.note' => 'Newest 200 of the selection. Polls are logged once per address and room per hour, and when they fail; all requests are counted above. Rows are deleted after %1$s days, and addresses are blanked after %2$s days.', // table column headings 'th.address' => 'Address', 'th.addresses' => 'Addresses', 'th.rooms' => 'Rooms', 'th.room' => 'Room', 'th.requests' => 'Requests', 'th.traffic' => 'Traffic', 'th.failures' => 'Failures', 'th.latest' => 'Latest', 'th.event' => 'Event', 'th.lastSeen' => 'Last seen', 'th.kind' => 'Kind', 'th.value' => 'Value', 'th.reason' => 'Reason', 'th.since' => 'Since', 'th.timeUtc' => 'Time (UTC)', 'th.action' => 'Action', 'th.status' => 'Status', 'th.bytes' => 'Bytes', 'th.seq' => 'Seq', 'th.time' => 'Time', 'th.note' => 'Note', 'th.userAgent' => 'User agent', // status page (the page people see) 'page.title' => 'MyTools bridge', 'page.intro' => 'This server relays encrypted Intercom and notification sync messages between your devices when they are not on the same network.', 'page.scan' => 'In MyTools open Intercom settings or Sync settings, go to Bridge and scan this code, or type the address.', // [html] 'page.keep' => 'Messages are encrypted by the apps; this server cannot read them, and keeps them for %1$s hours at most (the newest message of a device\'s location slot, too).', 'page.logs' => 'It logs metadata about requests (time, address, room, size) for security and abuse prevention.', 'check.php' => 'PHP %1$s', 'check.db' => 'Database: %1$s (%2$s messages waiting)', 'check.db.one' => 'Database: %1$s (%2$s message waiting)', 'check.db.fail' => 'Database: %1$s - %2$s', 'check.token.open' => 'Open to anyone who knows a group (set a token to restrict)', 'check.token.on' => 'Access token required', 'check.log.on' => 'Audit log on: metadata kept %1$s days, addresses blanked after %2$s', 'check.log.off' => 'Audit log off', 'check.admin.off' => 'Admin page off (set admin_token)', 'check.admin.on' => 'Admin page on', ]; } // Language files found next to this file: code (de-DE) => ['name' => ..., 'strings' => [...]]. Broken files are skipped. function i18nFiles() { static $files = null; if ($files !== null) return $files; $files = []; foreach ((array)@scandir(__DIR__) as $f) { if (!is_string($f) || !preg_match('/^bridge-([a-z]{2})([A-Z]{2})\.json$/', $f, $m)) continue; $code = $m[1] . '-' . $m[2]; if ($code === 'en-US') continue; // English is baked in $path = __DIR__ . '/' . $f; // $f matched the strict pattern above: never user input if (!is_file($path) || (int)@filesize($path) > 400000) continue; $raw = @file_get_contents($path); if (!is_string($raw)) continue; if (substr($raw, 0, 3) === "\xEF\xBB\xBF") $raw = substr($raw, 3); $data = json_decode($raw, true); if (!is_array($data) || !isset($data['_name']) || !is_string($data['_name'])) continue; $name = trim(preg_replace('/[\x00-\x1F\x7F]+/', ' ', $data['_name'])); if ($name === '' || !preg_match('//u', $name)) continue; $strings = []; foreach ($data as $k => $v) { if (is_string($k) && $k !== '' && $k[0] !== '_' && is_string($v) && $v !== '') $strings[$k] = $v; } $files[$code] = ['name' => preg_match('/^.{1,60}/su', $name, $nm) ? $nm[0] : $name, 'strings' => $strings]; } ksort($files); return $files; } // code => display name, English first. function i18nLanguages() { $list = ['en-US' => 'English']; foreach (i18nFiles() as $code => $file) $list[$code] = $file['name']; return $list; } // The Accept-Language header, best match among the available languages, else null. function i18nFromBrowser() { $header = (string)($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? ''); if ($header === '') return null; $wanted = []; foreach (explode(',', substr($header, 0, 500)) as $i => $part) { $bits = explode(';', trim($part)); $tag = strtolower(str_replace('_', '-', trim($bits[0]))); if (!preg_match('/^[a-z]{2,3}(-[a-z0-9]{2,8})*$/', $tag)) continue; $q = 1.0; foreach (array_slice($bits, 1) as $param) { if (preg_match('/^\s*q\s*=\s*([0-9.]+)\s*$/i', $param, $m)) $q = (float)$m[1]; } if ($q > 0) $wanted[] = [$q, $i, $tag]; } usort($wanted, function ($a, $b) { return $b[0] <=> $a[0] ?: $a[1] <=> $b[1]; }); $available = array_keys(i18nLanguages()); foreach ($wanted as $w) { $tag = $w[2]; foreach ($available as $code) { // exact: de-de if (strtolower($code) === $tag) return $code; } $lang = explode('-', $tag)[0]; foreach ($available as $code) { // same language, any country: de-at -> de-DE if (substr($code, 0, 2) === $lang) return $code; } } return null; } // The language of this request: the bridge_lang cookie if it names a known language, else the browser's, else English. function i18nCode() { static $code = null; if ($code !== null) return $code; $known = i18nLanguages(); $c = $_COOKIE['bridge_lang'] ?? ''; if (is_string($c) && isset($known[$c])) return $code = $c; return $code = (i18nFromBrowser() ?? 'en-US'); } // A POST from the language form: remember the choice in a cookie and go back to the same page. function i18nHandlePost() { if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST' || !isset($_POST['bridge_lang'])) return; $code = (string)$_POST['bridge_lang']; if (isset(i18nLanguages()[$code])) { setcookie('bridge_lang', $code, ['expires' => time() + 365 * 86400, 'path' => cookiePath(), 'secure' => isHttps(), 'httponly' => false, 'samesite' => 'Lax']); } $to = preg_replace('#^/+#', '/', strtok($_SERVER['REQUEST_URI'] ?? '/', '?')); $query = preg_replace('/[\x00-\x20]+/', '', (string)($_SERVER['QUERY_STRING'] ?? '')); header('Location: ' . $to . ($query !== '' ? '?' . $query : '')); exit; } function i18nTemplate($key, $english = false) { $en = i18nEnglish(); if (!$english) { $files = i18nFiles(); $code = i18nCode(); if (isset($files[$code]['strings'][$key]) && isset($en[$key])) return $files[$code]['strings'][$key]; } return $en[$key] ?? $key; } // sprintf that returns null instead of throwing/warning when a (translated) text has bad placeholders. function i18nFormat($template, $args) { try { $out = @vsprintf($template, $args); } catch (Throwable $e) { return null; } return is_string($out) ? $out : null; } function t($key, ...$args) { foreach ([false, true] as $english) { // the chosen language, then English if its text is broken $out = i18nFormat(i18nTemplate($key, $english), $args); if ($out !== null) return $out; } return $key; } // Same as t() but returns HTML: arguments and text are escaped, and only , , , are kept as tags. function th($key, ...$args) { $esc = array_map('h', $args); foreach ([false, true] as $english) { $tpl = i18nTemplate($key, $english); if (substr_count($tpl, '') !== substr_count($tpl, '') || substr_count($tpl, '') !== substr_count($tpl, '')) continue; $html = str_replace(['<code>', '</code>', '<b>', '</b>'], ['', '', '', ''], h($tpl)); $out = i18nFormat($html, $esc); if ($out !== null) return $out; } return h($key); } function i18nDir() { return in_array(substr(i18nCode(), 0, 2), ['ar', 'fa', 'he', 'ur'], true) ? 'rtl' : 'ltr'; } // The language picker, shown at the top of every human page. Works without JavaScript (the button). function langSwitcher() { $cur = i18nCode(); $out = '
'; } function fmtBytes($n) { $n = (float)$n; foreach (['B', 'KB', 'MB', 'GB'] as $u) { if ($n < 1024 || $u === 'GB') return ($u === 'B' ? (int)$n : round($n, 1)) . ' ' . $u; $n /= 1024; } } function fmtTime($t) { return $t ? gmdate('Y-m-d H:i:s', (int)$t) : ''; } function isHttps() { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https'); } function cookiePath() { return rtrim(str_replace("\\", '/', dirname(strtok($_SERVER['REQUEST_URI'] ?? '/', '?'))), '/') . '/'; } function adminCookie() { global $cfg; return hash_hmac('sha256', 'mytools-bridge-admin', (string)$cfg['admin_token']); } function adminHead($title) { echo '' . '' . h($title) . '
' . langSwitcher(); } function adminFoot() { echo '
'; } function adminTable($headers, $rows) { if (!$rows) { echo '

' . h(t('table.nothing')) . '

'; return; } echo ''; foreach ($headers as $head) echo ''; echo ''; foreach ($rows as $row) { echo ''; foreach ($row as $cell) echo ''; // cells are already escaped HTML echo ''; } echo '
' . h($head) . '
' . $cell . '
'; } function blockButton($kind, $value) { return '
' . '' . '
'; } function kindLabel($kind) { return in_array($kind, ['ip', 'room'], true) ? t('kind.' . $kind) : $kind; } function adminPage() { global $cfg; i18nHandlePost(); header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: no-store'); header('X-Robots-Tag: noindex'); header('Vary: Accept-Language, Cookie'); if ($cfg['admin_token'] === '') { adminHead(t('admin.title')); echo '

' . h(t('admin.off.title')) . '

' . th('admin.off.body') . '

'; adminFoot(); return; } $pdo = database(); $self = strtok($_SERVER['REQUEST_URI'] ?? '', '?') . '?a=admin'; $post = ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST'; $in = isset($_COOKIE['mtadmin']) && hash_equals(adminCookie(), (string)$_COOKIE['mtadmin']); if (!$in) { $error = ''; if ($post && isset($_POST['token'])) { limit('a', 10); if (hash_equals($cfg['admin_token'], (string)$_POST['token'])) { setcookie('mtadmin', adminCookie(), ['expires' => time() + 8 * 3600, 'path' => cookiePath(), 'secure' => isHttps(), 'httponly' => true, 'samesite' => 'Strict']); ctx('event', 'adminlogin'); header('Location: ' . $self); return; } http_response_code(403); ctx('event', 'adminfail'); $error = t('login.wrong'); } adminHead(t('admin.title')); echo '

' . h(t('admin.title')) . '

' . ($error ? '

' . h($error) . '

' : '') . '
'; adminFoot(); return; } if ($post) { $do = $_POST['do'] ?? ''; if ($do === 'logout') { setcookie('mtadmin', '', ['expires' => time() - 3600, 'path' => cookiePath(), 'secure' => isHttps(), 'httponly' => true, 'samesite' => 'Strict']); } elseif ($do === 'block' || $do === 'unblock') { $kind = $_POST['kind'] ?? ''; $value = trim((string)($_POST['value'] ?? '')); $valid = $kind === 'room' ? validRoom($value) : ($kind === 'ip' && preg_match('/^[0-9a-fA-F:.x]{3,45}$/', $value) === 1); if ($valid) { $pdo->prepare('DELETE FROM ' . table('block') . ' WHERE kind = ? AND value = ?')->execute([$kind, $value]); if ($do === 'block') { $pdo->prepare('INSERT INTO ' . table('block') . ' (kind, value, reason, ts) VALUES (?, ?, ?, ?)')->execute([$kind, $value, substr((string)($_POST['reason'] ?? ''), 0, 200), time()]); } ctx('event', 'admin' . $do); ctx('note', substr($kind . ' ' . $value, 0, 80)); } } header('Location: ' . $self); return; } $days = in_array((int)($_GET['p'] ?? 1), [1, 7, 30], true) ? (int)($_GET['p'] ?? 1) : 1; $since = time() - $days * 86400; $day0 = (int)gmdate('Ymd', $since); $st = table('stats'); $lg = table('log'); // Log filters, shared by the table and the CSV export. $where = ['ts >= ?']; $args = [$since]; foreach (['ip' => 'ip LIKE ?', 'room' => 'room = ?', 'ev' => 'ev = ?', 'act' => 'act = ?'] as $key => $clause) { $f = trim((string)($_GET[$key] ?? '')); if ($f !== '') { $where[] = $clause; $args[] = $key === 'ip' ? $f . '%' : $f; } } if (!empty($_GET['bad'])) $where[] = 'status >= 400'; $filterSql = implode(' AND ', $where); if (!empty($_GET['csv'])) { header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename="bridge-log-' . gmdate('Ymd-His') . '.csv"'); $out = fopen('php://output', 'w'); fputcsv($out, ['time_utc', 'ip', 'user_agent', 'method', 'action', 'room', 'status', 'bytes', 'seq', 'ms', 'event', 'note'], ',', '"', ''); $q = $pdo->prepare("SELECT * FROM $lg WHERE $filterSql ORDER BY id DESC LIMIT 50000"); $q->execute($args); while ($r = $q->fetch()) { fputcsv($out, [fmtTime($r['ts']), $r['ip'], $r['ua'], $r['method'], $r['act'], $r['room'], $r['status'], $r['nbytes'], $r['seq'], $r['ms'], $r['ev'], $r['note']], ',', '"', ''); } return; } $one = function ($sql, $params) use ($pdo) { $q = $pdo->prepare($sql); $q->execute($params); return $q->fetch(PDO::FETCH_NUM); }; $all = function ($sql, $params) use ($pdo) { $q = $pdo->prepare($sql); $q->execute($params); return $q->fetchAll(PDO::FETCH_NUM); }; adminHead(t('admin.title')); echo '

' . h(t('admin.title')) . '

'; foreach ([1, 7, 30] as $d) { $label = t('period.' . $d); echo $d === $days ? '' . h($label) . '' : '' . h($label) . ''; echo ' · '; } echo '
'; // ---- summary ---- [$ips, $rooms, $req, $bytes] = $one("SELECT COUNT(DISTINCT ip), COUNT(DISTINCT CASE WHEN room <> '' THEN room END), COALESCE(SUM(req), 0), COALESCE(SUM(nbytes), 0) FROM $st WHERE d >= ?", [$day0]); [$sends, $sendBytes] = $one("SELECT COUNT(*), COALESCE(SUM(nbytes), 0) FROM $lg WHERE act = 'send' AND status = 200 AND ts >= ?", [$since]); [$stored] = $one('SELECT COUNT(*) FROM ' . table('msgs'), []); echo '

' . h(t('summary.title')) . '

' . h(t('summary.line', (int)$req, (int)$ips, (int)$rooms, (int)$sends, fmtBytes($sendBytes), fmtBytes($bytes), (int)$stored)) . '

'; $events = $all("SELECT ev, COUNT(*) FROM $lg WHERE ts >= ? AND ev <> '' GROUP BY ev ORDER BY COUNT(*) DESC", [$since]); if ($events) { echo '

' . h(t('summary.events')) . ' '; foreach ($events as $e) echo '' . h($e[0]) . ' ' . (int)$e[1] . ' · '; echo '

'; } echo '
'; // ---- things that look like abuse ---- $thrRooms = (int)$cfg['alert_rooms_per_ip']; $thrIps = (int)$cfg['alert_ips_per_room']; echo '

' . h(t('look.title')) . '

'; echo '

' . h(t('look.rooms', $thrRooms)) . '

'; $rows = []; foreach ($all("SELECT ip, COUNT(DISTINCT room), SUM(req), SUM(nbytes) FROM $st WHERE d >= ? AND room <> '' GROUP BY ip HAVING COUNT(DISTINCT room) >= $thrRooms ORDER BY COUNT(DISTINCT room) DESC LIMIT 20", [$day0]) as $r) { $rows[] = ['' . h($r[0]) . '', (int)$r[1], (int)$r[2], h(fmtBytes($r[3])), blockButton('ip', $r[0])]; } adminTable([t('th.address'), t('th.rooms'), t('th.requests'), t('th.traffic'), ''], $rows); echo '

' . h(t('look.addresses', $thrIps)) . '

'; $rows = []; foreach ($all("SELECT room, COUNT(DISTINCT ip), SUM(req), SUM(nbytes) FROM $st WHERE d >= ? AND room <> '' GROUP BY room HAVING COUNT(DISTINCT ip) >= $thrIps ORDER BY COUNT(DISTINCT ip) DESC LIMIT 20", [$day0]) as $r) { $rows[] = ['' . h($r[0]) . '', (int)$r[1], (int)$r[2], h(fmtBytes($r[3])), blockButton('room', $r[0])]; } adminTable([t('th.room'), t('th.addresses'), t('th.requests'), t('th.traffic'), ''], $rows); echo '

' . h(t('look.failed')) . '

'; $rows = []; foreach ($all("SELECT ip, COUNT(*), MAX(ts), MAX(ev) FROM $lg WHERE ts >= ? AND status >= 400 GROUP BY ip ORDER BY COUNT(*) DESC LIMIT 20", [$since]) as $r) { $rows[] = ['' . h($r[0]) . '', (int)$r[1], h(fmtTime($r[2])), '' . h($r[3]) . '', blockButton('ip', $r[0])]; } adminTable([t('th.address'), t('th.failures'), t('th.latest'), t('th.event'), ''], $rows); echo '
'; // ---- busiest ---- echo '

' . h(t('busiest.addresses')) . '

'; $rows = []; foreach ($all("SELECT ip, SUM(req), SUM(nbytes), COUNT(DISTINCT CASE WHEN room <> '' THEN room END), MAX(t2) FROM $st WHERE d >= ? GROUP BY ip ORDER BY SUM(nbytes) DESC, SUM(req) DESC LIMIT 15", [$day0]) as $r) { $rows[] = ['' . h($r[0]) . '', (int)$r[1], h(fmtBytes($r[2])), (int)$r[3], h(fmtTime($r[4])), blockButton('ip', $r[0])]; } adminTable([t('th.address'), t('th.requests'), t('th.traffic'), t('th.rooms'), t('th.lastSeen'), ''], $rows); echo '

' . h(t('busiest.rooms')) . '

'; $rows = []; foreach ($all("SELECT room, SUM(req), SUM(nbytes), COUNT(DISTINCT ip), MAX(t2) FROM $st WHERE d >= ? AND room <> '' GROUP BY room ORDER BY SUM(nbytes) DESC, SUM(req) DESC LIMIT 15", [$day0]) as $r) { $rows[] = ['' . h($r[0]) . '', (int)$r[1], h(fmtBytes($r[2])), (int)$r[3], h(fmtTime($r[4])), blockButton('room', $r[0])]; } adminTable([t('th.room'), t('th.requests'), t('th.traffic'), t('th.addresses'), t('th.lastSeen'), ''], $rows); echo '
'; // ---- blocks ---- echo '

' . h(t('blocked.title')) . '

'; $rows = []; foreach ($all('SELECT kind, value, reason, ts FROM ' . table('block') . ' ORDER BY ts DESC', []) as $r) { $rows[] = [h(kindLabel($r[0])), '' . h($r[1]) . '', h($r[2]), h(fmtTime($r[3])), '
']; } adminTable([t('th.kind'), t('th.value'), t('th.reason'), t('th.since'), ''], $rows); echo '
' . '
' . '

' . th('blocked.note') . '

'; // ---- the log ---- $q = $pdo->prepare("SELECT ts, ip, ua, act, room, status, nbytes, seq, ms, ev, note FROM $lg WHERE $filterSql ORDER BY id DESC LIMIT 200"); $q->execute($args); $rows = []; foreach ($q->fetchAll(PDO::FETCH_NUM) as $r) { $rows[] = [h(fmtTime($r[0])), '' . h($r[1]) . '', h($r[3]), $r[4] ? '' . h(substr($r[4], 0, 8)) . '…' : '', '' . (int)$r[5] . '', h(fmtBytes($r[6])), h($r[7]), (int)$r[8] . ' ms', '' . h($r[9]) . '', h($r[10]), '' . h($r[2]) . '']; } echo '

' . h(t('log.title')) . '

' . '' . ' ' . '' . h(t('log.csv')) . '
'; adminTable([t('th.timeUtc'), t('th.address'), t('th.action'), t('th.room'), t('th.status'), t('th.bytes'), t('th.seq'), t('th.time'), t('th.event'), t('th.note'), t('th.userAgent')], $rows); echo '

' . h(t('log.note', (int)$cfg['log_keep_days'], (int)$cfg['log_anonymize_days'])) . '

'; adminFoot(); } if ($action === 'admin') { adminPage(); exit; } // ------------------------------------------------------------------ the page people see $url = pageUrl(); $checks = []; i18nHandlePost(); $checks[] = [t('check.php', PHP_VERSION), version_compare(PHP_VERSION, '7.4', '>=')]; $dbName = 'SQLite'; $dbOk = false; $stored = 0; $problem = ''; try { $pdo = database(); $dbName = $pdo->getAttribute(PDO::ATTR_DRIVER_NAME) === 'sqlite' ? 'SQLite' : 'MySQL / MariaDB'; $stored = (int)$pdo->query('SELECT COUNT(*) FROM ' . table('msgs'))->fetchColumn(); $dbOk = true; } catch (Throwable $e) { $problem = $e->getMessage(); } $checks[] = [$dbOk ? t($stored === 1 ? 'check.db.one' : 'check.db', $dbName, $stored) : t('check.db.fail', $dbName, $problem), $dbOk]; $checks[] = [t($cfg['token'] === '' ? 'check.token.open' : 'check.token.on'), true]; $checks[] = [$cfg['log'] ? t('check.log.on', (int)$cfg['log_keep_days'], (int)$cfg['log_anonymize_days']) : t('check.log.off'), true]; $checks[] = [t($cfg['admin_token'] === '' ? 'check.admin.off' : 'check.admin.on'), true]; header('Content-Type: text/html; charset=utf-8'); header('Cache-Control: no-store'); header('Vary: Accept-Language, Cookie'); ?> <?= h(t('page.title')) ?>