#!/usr/bin/env python3 """Review/apply approved point flags through a running core, without restarting it. Reads admin credentials only from CONFIG; never includes them in output/backups. EVENT goes through game -> db -> all cores and persists flags in the quest table. """ import argparse import datetime import json from pathlib import Path import re import socket import subprocess import time CHANCES = ('points_mob_chance', 'points_stone_chance') APPROVED = {'points_mob_chance': 5000, 'points_mob_min': 3, 'points_mob_max': 5, 'points_stone_chance': 10000, 'points_stone_min': 15, 'points_stone_max': 30, 'points_min_level': 1, 'points_max_overlevel': 15, 'points_daily_cap': 0} def config_values(path): result = {} for line in path.read_text().splitlines(): words = line.split(None, 1) if len(words) == 2: result[words[0].rstrip(':').lower()] = words[1].strip() return result def db_schemas(path): result = {} for line in path.read_text().splitlines(): match = re.match(r'^\s*(SQL_PLAYER|SQL_ACCOUNT)\s*=\s*"([^"]*)"', line) if match: result[match[1]] = match[2].split()[1] return result def validate_target(config, db_config, player, account, db_port): for schema in (player, account): if not re.fullmatch(r'[A-Za-z0-9_]+', schema): raise RuntimeError('Invalid schema name') values = config_values(config) if int(values.get('db_port', '0')) != db_port: raise RuntimeError('Core DB_PORT does not match the requested target') if db_schemas(db_config) != {'SQL_PLAYER': player, 'SQL_ACCOUNT': account}: raise RuntimeError('DB config does not match the requested schemas') ips = ' '.join(v for k, v in values.items() if k.startswith('adminpage_ip')).split() if '127.0.0.1' not in ips or not values.get('adminpage_password'): raise RuntimeError('A configured loopback admin endpoint is required') if '\n' in values['adminpage_password'] or '\r' in values['adminpage_password']: raise RuntimeError('Invalid admin credential format') return values def mysql(sql): return subprocess.check_output(['mysql', '--batch', '--skip-column-names'], input=sql.encode()).decode().strip() def snapshot(player, account): names = ','.join("'%s'" % k for k in sorted(APPROVED)) rows = mysql('SELECT szName,szState,lValue FROM `%s`.quest ' 'WHERE dwPID=0 AND szName IN (%s) ORDER BY szName,szState' % (player, names)) before = {} for line in rows.splitlines(): name, state, value = line.split('\t') if state or name in before: raise RuntimeError('Ambiguous event flag rows: ' + name) before[name] = int(value) engines = mysql("SELECT COUNT(*) FROM information_schema.tables WHERE ENGINE='InnoDB' AND " "((TABLE_SCHEMA='%s' AND TABLE_NAME='port_point_rewards') OR " "(TABLE_SCHEMA='%s' AND TABLE_NAME='account'))" % (player, account)) if engines != '2': raise RuntimeError('Transactional reward ledger/wallet prerequisites are missing') return before def rollout(before, desired): if all(before.get(k, 0) == v for k, v in desired.items()): return [] # Quotas and eligibility must be active before any nonzero award probability. return ([(k, 0) for k in CHANCES] + [(k, desired[k]) for k in sorted(desired) if k not in CHANCES] + [(k, desired[k]) for k in CHANCES]) class Admin: def __init__(self, values, host): # Some cores bind only the machine's LAN address. Keep the connection's # source on loopback so its existing admin IP allowlist still applies. self.sock = socket.create_connection((host, int(values['port'])), timeout=3, source_address=('127.0.0.1', 0)) # Drain the normal binary phase/handshake before using text admin commands. self.sock.settimeout(.2) try: while self.sock.recv(4096): pass except socket.timeout: pass self.sock.settimeout(3) self.command(values['adminpage_password'], 'UNKNOWN') def command(self, command, expected): self.sock.sendall(b'@' + command.encode() + b'\n') result = b'' while not result.endswith(b'\n'): part = self.sock.recv(4096) if not part or len(result) + len(part) > 4096: raise RuntimeError('Admin response missing or oversized') result += part if result.strip() != expected.encode(): raise RuntimeError('Admin command rejected; no credential/response is logged') def event(self, name, value): self.command('EVENT %s %d' % (name, value), 'EVENT FLAG CHANGE ' + name) def close(self): self.sock.close() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--config', required=True, type=Path) parser.add_argument('--db-config', required=True, type=Path) parser.add_argument('--player', required=True) parser.add_argument('--account', required=True) parser.add_argument('--db-port', required=True, type=int) parser.add_argument('--host', default='127.0.0.1', help='local listening address of the core') parser.add_argument('--apply', action='store_true') parser.add_argument('--backup', type=Path) parser.add_argument('--restore', type=Path, help='restore flag values from this backup') args = parser.parse_args() values = validate_target(args.config, args.db_config, args.player, args.account, args.db_port) before = snapshot(args.player, args.account) desired = dict(APPROVED) if args.restore: saved = json.loads(args.restore.read_text()) if (saved['player'], saved['account'], saved['db_port'], saved['config']) != ( args.player, args.account, args.db_port, str(args.config.resolve())): raise RuntimeError('Backup belongs to a different target') desired = {k: int(saved['before'].get(k, 0)) for k in APPROVED} commands = rollout(before, desired) report = {'config': str(args.config.resolve()), 'player': args.player, 'account': args.account, 'db_port': args.db_port, 'host': args.host, 'created_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'before': before, 'desired': desired, 'commands': commands, 'applied': False} if args.apply and commands: if not args.backup: raise RuntimeError('--apply requires a new --backup path') args.backup.parent.mkdir(parents=True, exist_ok=True) with args.backup.open('x') as file: json.dump(report, file, indent=2) admin = Admin(values, args.host) try: for name, value in commands: admin.event(name, value) deadline = time.monotonic() + 5 while snapshot(args.player, args.account) != desired: if time.monotonic() >= deadline: raise RuntimeError('Flags not persisted; inspect backup and runtime before retry') time.sleep(.1) finally: admin.close() report['applied'] = True args.backup.with_suffix('.result.json').write_text(json.dumps(report, indent=2) + '\n') print(json.dumps(report, sort_keys=True)) if __name__ == '__main__': main()