run(max(1, min(100, (int) ($argv[2] ?? 50)))); echo sprintf( "USDT wallets=%d transfers=%d credited=%d unmatched=%d duplicates=%d expired=%d errors=%d\n", $stats['wallets'], $stats['transfers'], $stats['credited'], $stats['unmatched'], $stats['duplicates'], $stats['expired'], $stats['errors'] ); return (int) $stats['errors'] === 0; }); } public static function backupJob() { if (!filter_var(Config::get('enable_auto_backup', false), FILTER_VALIDATE_BOOLEAN)) { echo 'Automatic database backup is disabled.' . PHP_EOL; return true; } return self::backup(); } public static function backup() { $password = (string) Config::get('auto_backup_passwd', ''); if (trim($password) === '' || strlen($password) < 12 || strpos($password, "\0") !== false) { fwrite(STDERR, '数据库备份拒绝执行:请先设置至少 12 字节的 auto_backup_passwd 加密口令。' . PHP_EOL); return false; } if (!class_exists(ZipArchive::class) || !defined('ZipArchive::EM_AES_256') || !method_exists(ZipArchive::class, 'setEncryptionName') || !ZipArchive::isEncryptionMethodSupported(ZipArchive::EM_AES_256, true)) { fwrite(STDERR, '数据库备份拒绝执行:请安装支持 AES-256 的 PHP zip/libzip 扩展。' . PHP_EOL); return false; } return self::runLocked('database-backup', function () use ($password) { $directory = BASE_PATH . '/storage/backups'; self::privateDirectory($directory); $working = $directory . '/.working-' . bin2hex(random_bytes(16)); if (!mkdir($working, 0700)) { throw new \RuntimeException('无法创建私有备份临时目录。'); } $temporary = []; $archive = $directory . '/database-' . gmdate('Ymd-His') . '-' . bin2hex(random_bytes(6)) . '.zip'; $complete = false; $zip = null; try { $connections = self::backupConnections(); $binary = self::dumpExecutable(); $entries = []; foreach ($connections as $label => $connection) { $credentials = $working . '/' . $label . '.cnf'; $sql = $working . '/' . $label . '.sql'; $stderr = $working . '/' . $label . '.stderr'; $temporary = array_merge($temporary, [$credentials, $sql, $stderr]); self::privateFile($credentials, self::clientOptions($connection)); self::privateFile($sql, ''); self::privateFile($stderr, ''); $process = proc_open( self::dumpArguments($binary, $credentials, $connection), [0 => ['file', '/dev/null', 'r'], 1 => ['file', $sql, 'w'], 2 => ['file', $stderr, 'w']], $pipes, $working, null, ['bypass_shell' => true] ); if (!is_resource($process)) { throw new \RuntimeException('无法启动数据库导出客户端。'); } $code = proc_close($process); clearstatcache(true, $sql); if ($code !== 0 || filesize($sql) === 0) { // Do not print arguments, credentials, or raw client stderr. throw new \RuntimeException('数据库导出失败:请检查数据库连接、备份权限及 mariadb-dump 客户端。'); } $entries[$label . '.sql'] = $sql; } self::privateFile($archive, ''); $zip = new ZipArchive(); if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { throw new \RuntimeException('无法创建加密数据库归档。'); } foreach ($entries as $name => $sql) { if (!$zip->addFile($sql, $name) || !$zip->setEncryptionName($name, ZipArchive::EM_AES_256, $password)) { throw new \RuntimeException('数据库归档 AES-256 加密失败,未生成可用备份。'); } } if (!$zip->close()) { $zip = null; throw new \RuntimeException('数据库归档写入失败。'); } $zip = null; clearstatcache(true, $archive); if (filesize($archive) === 0 || !chmod($archive, 0600)) { throw new \RuntimeException('数据库归档为空或无法设置私有权限。'); } $complete = true; echo 'Encrypted SQL-only backup: ' . $archive . PHP_EOL; $recipient = trim((string) Config::get('auto_backup_email', '')); if ($recipient !== '') { if (!filter_var($recipient, FILTER_VALIDATE_EMAIL)) { throw new \RuntimeException('备份已保存,但 auto_backup_email 不是有效邮箱。'); } if (!Mail::send( $recipient, Config::get('appName') . '-数据库备份', 'news/backup.tpl', ['text' => '数据库 SQL 备份已使用 AES-256 加密,请使用您配置的备份口令解压。'], [$archive] )) { throw new \RuntimeException('备份已保存,但邮件服务未接受备份邮件。'); } } return true; } finally { if ($zip instanceof ZipArchive) { $zip->close(); } if (!$complete && is_file($archive)) { unlink($archive); } foreach ($temporary as $file) { if (is_file($file)) { unlink($file); } } rmdir($working); } }); } private static function backupConnections() { $connections = ['primary' => self::connectionOptions(Config::getDbConfig())]; if (filter_var(Config::get('enable_log', false), FILTER_VALIDATE_BOOLEAN)) { // An enabled but incomplete log connection must fail, not silently // omit data while reporting a successful complete backup. $log = self::connectionOptions(Config::getLogDbConfig()); if ($log !== $connections['primary']) { $connections['logs'] = $log; } } return $connections; } private static function connectionOptions(array $config) { if (($config['driver'] ?? 'mysql') !== 'mysql') { throw new \RuntimeException('数据库 SQL 备份只支持配置的 MariaDB/MySQL 连接。'); } $host = trim((string) ($config['host'] ?? '')); if ($host === '') { $host = 'localhost'; } $port = (int) ($config['port'] ?? 3306); if (preg_match('/^\[([^\]]+)\]:(\d+)$/', $host, $match) || preg_match('/^([^:]+):(\d+)$/', $host, $match)) { $host = $match[1]; $port = (int) $match[2]; } $database = (string) ($config['database'] ?? ''); $username = (string) ($config['username'] ?? ''); $password = (string) ($config['password'] ?? ''); foreach ([$host, $database, $username, $password] as $value) { if (strpos($value, "\0") !== false) { throw new \RuntimeException('数据库备份连接配置包含无效字符。'); } } if ($host === '' || $database === '' || $username === '' || $port < 1 || $port > 65535) { throw new \RuntimeException('数据库备份连接配置不完整。'); } return compact('host', 'port', 'database', 'username', 'password'); } private static function clientOptions(array $connection) { return "[client]\nprotocol=TCP\n" . 'host=' . self::optionValue($connection['host']) . "\n" . 'port=' . $connection['port'] . "\n" . 'user=' . self::optionValue($connection['username']) . "\n" . 'password=' . self::optionValue($connection['password']) . "\n"; } private static function optionValue($value) { return '"' . strtr((string) $value, [ "\\" => "\\\\", '"' => '\\"', "\n" => '\\n', "\r" => '\\r', "\t" => '\\t', ]) . '"'; } private static function dumpArguments($binary, $credentials, array $connection) { return [ $binary, '--defaults-extra-file=' . $credentials, '--single-transaction', '--quick', '--skip-lock-tables', '--routines', '--events', '--triggers', '--hex-blob', '--default-character-set=utf8mb4', '--databases', '--', $connection['database'], ]; } private static function dumpExecutable() { foreach (['/usr/bin/mariadb-dump', '/usr/bin/mysqldump'] as $binary) { if (is_file($binary) && is_executable($binary)) { return $binary; } } throw new \RuntimeException('请安装 MariaDB/MySQL 的 mariadb-dump 或 mysqldump 客户端。'); } private static function privateDirectory($path) { if (is_link($path) || (!is_dir($path) && !mkdir($path, 0700, true)) || !chmod($path, 0700)) { throw new \RuntimeException('无法创建私有任务目录。'); } } private static function privateFile($path, $contents) { $file = fopen($path, 'x'); if ($file === false) { throw new \RuntimeException('无法安全创建备份文件。'); } try { if (!chmod($path, 0600) || fwrite($file, $contents) !== strlen($contents)) { throw new \RuntimeException('无法写入私有备份文件。'); } } finally { fclose($file); } } private static function runLocked($name, callable $task) { $directory = BASE_PATH . '/storage/locks'; self::privateDirectory($directory); $path = $directory . '/' . $name . '.lock'; if (is_link($path)) { throw new \RuntimeException('任务锁文件不能是符号链接。'); } $lock = fopen($path, 'c'); if ($lock === false || !chmod($path, 0600)) { if (is_resource($lock)) { fclose($lock); } throw new \RuntimeException('无法创建私有任务锁。'); } if (!flock($lock, LOCK_EX | LOCK_NB)) { fclose($lock); echo $name . ' is already running; skipped.' . PHP_EOL; return true; } try { return $task(); } catch (\Throwable $exception) { fwrite(STDERR, $name . ' failed: ' . $exception->getMessage() . PHP_EOL); return false; } finally { flock($lock, LOCK_UN); fclose($lock); } } }