343 lines
17 KiB
Python
343 lines
17 KiB
Python
"""ITOSM recovery archive. Firmware lives in /data, never in the source archive."""
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import re
|
|
import secrets
|
|
import signal
|
|
import struct
|
|
import threading
|
|
import time
|
|
from datetime import datetime, timezone
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
import sys
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
from members import Members
|
|
from device_backups import DeviceBackups
|
|
|
|
DATA = Path(os.environ.get('BACKUP_DATA', '/data'))
|
|
ORIGIN = os.environ.get('PUBLIC_ORIGIN', 'https://tama.itosm.co.kr')
|
|
SIZE = 0x1000000
|
|
EDITIONS = {1: '랜드', 2: '워터', 3: '스카이', 4: '제이드 포레스트', 5: '트로피컬', 6: '글레이셔'}
|
|
SLUGS = {1: 'land', 2: 'water', 3: 'sky', 4: 'jade-forest', 5: 'tropical', 6: 'glacier'}
|
|
CONSTANTS = [0, 0x70169E2C, 0x70169E2C, 0x70169E2C, 0x849633DB, 0x96CB83B8, 0x96CB83B8]
|
|
LOCK = threading.RLock()
|
|
SESSIONS = {}
|
|
ATTEMPTS = {}
|
|
DEFAULTS = {'title': '다마고치 연구소', 'description': '다마고치 파라다이스 펌웨어 에디터. 커스텀 펌웨어 제작과 캐릭터 디자인 변경 및 A+C 치트 메뉴 한글화를 지원합니다.', 'autoBackup': True, 'maxStorageMB': 512}
|
|
FEATURES = ('emu', 'gb', 'sms', 'pm', 'ab', 'doom', 'wolf', 'standalone', 'cards')
|
|
DEFAULTS.update(backupMode='server', deviceStorageMB=512, deviceRetentionHours=24, features={key: False for key in FEATURES})
|
|
MEMBERS = None
|
|
DEVICE_BACKUPS = None
|
|
|
|
|
|
def device_backups():
|
|
global DEVICE_BACKUPS
|
|
with LOCK:
|
|
if DEVICE_BACKUPS is None or DEVICE_BACKUPS.folder.parent != DATA:
|
|
DEVICE_BACKUPS = DeviceBackups(DATA, config, LOCK, detect)
|
|
return DEVICE_BACKUPS
|
|
|
|
|
|
def members():
|
|
global MEMBERS
|
|
with LOCK:
|
|
if MEMBERS is None or MEMBERS.data != DATA:
|
|
MEMBERS = Members(DATA, config, password_hash, password_ok, detect, EDITIONS, now)
|
|
return MEMBERS
|
|
|
|
|
|
def now():
|
|
return datetime.now(timezone.utc).isoformat()
|
|
|
|
|
|
def password_hash(password, salt=None):
|
|
salt = salt or secrets.token_hex(16)
|
|
return salt + ':' + hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384, r=8, p=1).hex()
|
|
|
|
|
|
def password_ok(password, stored):
|
|
try:
|
|
return hmac.compare_digest(password_hash(password, stored.split(':')[0]), stored)
|
|
except (ValueError, TypeError):
|
|
return False
|
|
|
|
|
|
def read_json(path):
|
|
return json.loads(path.read_text(encoding='utf-8'))
|
|
|
|
|
|
def atomic_json(path, value):
|
|
temp = path.with_suffix('.tmp')
|
|
with temp.open('w', encoding='utf-8') as output:
|
|
json.dump(value, output, ensure_ascii=False, indent=2)
|
|
output.flush()
|
|
os.fsync(output.fileno())
|
|
os.replace(temp, path)
|
|
|
|
|
|
def config():
|
|
return dict(DEFAULTS, **read_json(DATA / 'config.json'))
|
|
|
|
|
|
def records():
|
|
return [read_json(p) for p in sorted(DATA.glob('*/metadata.json'))]
|
|
|
|
|
|
def image_path(record):
|
|
return DATA / SLUGS[record['edition']] / (record['sha256'] + '.bin')
|
|
|
|
|
|
def detect(data):
|
|
if len(data) != SIZE or data[:8] != b'SONIXDEV':
|
|
raise ValueError('16 MB 파라다이스 ROM 파일이 아닙니다.')
|
|
for address, ids in [(0xD29000, [5, 6]), (0xD49000, [1, 2, 3, 4]), (0xEFD000, [1, 2, 3, 4, 5, 6])]:
|
|
edition = struct.unpack_from('<I', data, address)[0]
|
|
a, b = struct.unpack_from('<II', data, address + 0xFF8)
|
|
if edition in ids and (a + edition) & 0xFFFFFFFF == CONSTANTS[edition] and b == (~a & 0xFFFFFFFF):
|
|
return edition
|
|
raise ValueError('기종 정보를 확인할 수 없어 서버에 보관하지 않았습니다. PC 파일은 별도로 저장할 수 있습니다.')
|
|
|
|
|
|
def store_image(data, label=None, published=False, protected=False, source_date=None):
|
|
edition = detect(data)
|
|
digest = hashlib.sha256(data).hexdigest()
|
|
with LOCK:
|
|
cfg = config()
|
|
folder = DATA / SLUGS[edition]
|
|
if (folder / 'metadata.json').exists():
|
|
return {'status': 'already-held', 'edition': edition, 'name': EDITIONS[edition]}
|
|
if not protected and not cfg['autoBackup']:
|
|
return {'status': 'disabled'}
|
|
used = sum(p.stat().st_size for p in DATA.glob('*/*.bin'))
|
|
if used + len(data) > cfg['maxStorageMB'] * 1024 * 1024:
|
|
raise ValueError('서버 백업 용량이 가득 찼습니다. PC 파일은 별도로 저장하세요.')
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
path = folder / (digest + '.bin')
|
|
# A crash after writing the image but before its metadata may leave an orphan.
|
|
# Only reuse that exact verified image; never replace an established record.
|
|
if not path.exists():
|
|
with path.open('xb') as output:
|
|
output.write(data)
|
|
output.flush()
|
|
os.fsync(output.fileno())
|
|
if hashlib.sha256(path.read_bytes()).hexdigest() != digest:
|
|
path.unlink()
|
|
raise ValueError('서버 파일 검증에 실패했습니다.')
|
|
record = {'edition': edition, 'name': EDITIONS[edition], 'slug': SLUGS[edition], 'sha256': digest, 'size': len(data), 'createdAt': now(), 'sourceDate': source_date, 'label': label or EDITIONS[edition] + ' 추출 백업 (원본 여부 미확인)', 'published': published, 'protected': protected, 'verifiedOnDevice': False}
|
|
atomic_json(folder / 'metadata.json', record)
|
|
return {'status': 'stored', 'edition': edition, 'name': EDITIONS[edition], 'sha256': digest}
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
protocol_version = 'HTTP/1.1'
|
|
|
|
def log_message(self, fmt, *args):
|
|
# Do not log credentials, cookies, client filenames or binary data.
|
|
pass
|
|
|
|
def reply(self, status, body, content_type='application/json; charset=utf-8', headers=None):
|
|
if not isinstance(body, bytes):
|
|
body = json.dumps(body, ensure_ascii=False).encode()
|
|
self.send_response(status)
|
|
self.send_header('Content-Type', content_type)
|
|
self.send_header('Content-Length', str(len(body)))
|
|
self.send_header('Cache-Control', 'no-store')
|
|
self.send_header('X-Content-Type-Options', 'nosniff')
|
|
self.send_header('X-Robots-Tag', 'noindex')
|
|
for key, val in (headers or {}).items():
|
|
for value in val if isinstance(val, list) else [val]:
|
|
self.send_header(key, value)
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def authorized(self):
|
|
user = members().user(self)
|
|
if user and user['username'] == config()['username'].lower():
|
|
return True
|
|
cookie = self.headers.get('Cookie', '')
|
|
match = re.search(r'(?:^|;\s*)tama_admin=([a-f0-9]{64})(?:;|$)', cookie)
|
|
token = match.group(1) if match else None
|
|
with LOCK:
|
|
for key, expiry in list(SESSIONS.items()):
|
|
if expiry <= time.time():
|
|
del SESSIONS[key]
|
|
return bool(token and token in SESSIONS)
|
|
|
|
def clear_admin_session(self):
|
|
match = re.search(r'(?:^|;\s*)tama_admin=([a-f0-9]{64})(?:;|$)', self.headers.get('Cookie', ''))
|
|
with LOCK:
|
|
if match:
|
|
SESSIONS.pop(match[1], None)
|
|
|
|
def body(self, limit):
|
|
if self.headers.get('Transfer-Encoding'):
|
|
raise ValueError('지원하지 않는 전송 방식입니다.')
|
|
length = int(self.headers.get('Content-Length', '-1'))
|
|
if not 0 <= length <= limit:
|
|
raise ValueError('파일 또는 요청 크기가 잘못되었습니다.')
|
|
self.connection.settimeout(90)
|
|
data = self.rfile.read(length)
|
|
if len(data) != length:
|
|
raise ValueError('전송이 끝나지 않았습니다.')
|
|
return data
|
|
|
|
def do_GET(self):
|
|
try:
|
|
self.get()
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
pass
|
|
except Exception:
|
|
self.reply(500, {'error': '서버 요청을 처리하지 못했습니다.'})
|
|
|
|
def get(self):
|
|
path = self.path.split('?')[0]
|
|
if path.startswith('/api/member/') or path == '/api/admin/members':
|
|
return members().get(self, path)
|
|
match = re.fullmatch(r'/api/device-backups/([a-f0-9]{32})', path)
|
|
if match:
|
|
return device_backups().download(self, match[1])
|
|
if path == '/api/health':
|
|
return self.reply(200, {'ok': True})
|
|
if path == '/api/catalog':
|
|
with LOCK:
|
|
items = [r for r in records() if r['published']]
|
|
cfg = config()
|
|
return self.reply(200, {'items': items, 'title': cfg['title'], 'description': cfg['description'], 'features': cfg['features'], 'backupMode': cfg['backupMode']})
|
|
if path == '/api/backup-status':
|
|
with LOCK:
|
|
cfg = config()
|
|
held = [r['edition'] for r in records()]
|
|
return self.reply(200, {'enabled': cfg['autoBackup'], 'held': held, 'mode': cfg['backupMode'], 'retentionHours': cfg['deviceRetentionHours']})
|
|
if path.startswith('/api/admin/') and not self.authorized():
|
|
return self.reply(401, {'error': '관리자 로그인이 필요합니다.'})
|
|
if path == '/api/admin/state':
|
|
with LOCK:
|
|
cfg = config()
|
|
items = records()
|
|
return self.reply(200, {'settings': {k: cfg[k] for k in DEFAULTS}, 'username': cfg['username'], 'items': items, 'usedMB': sum(r['size'] for r in items) // 1048576})
|
|
match = re.fullmatch(r'/api/(?:admin/)?file/([a-f0-9]{64})', path)
|
|
if match:
|
|
with LOCK:
|
|
item = next((r for r in records() if r['sha256'] == match.group(1)), None)
|
|
if not item or (not item['published'] and not path.startswith('/api/admin/')):
|
|
return self.reply(404, {'error': '공개된 복원 파일이 없습니다.'})
|
|
data = image_path(item).read_bytes()
|
|
return self.reply(200, data, 'application/octet-stream', {'Content-Disposition': 'attachment; filename="paradise-' + item['slug'] + '-' + item['sha256'][:12] + '.bin"'})
|
|
self.reply(404, {'error': '페이지가 없습니다.'})
|
|
|
|
def do_POST(self):
|
|
try:
|
|
if self.headers.get('Origin') != ORIGIN:
|
|
self.close_connection = True
|
|
return self.reply(403, {'error': '홈페이지에서 다시 시도하세요.'})
|
|
self.post()
|
|
except (ValueError, KeyError, TypeError) as exc:
|
|
self.close_connection = True
|
|
self.reply(400, {'error': str(exc)})
|
|
except (BrokenPipeError, ConnectionResetError):
|
|
pass
|
|
except Exception:
|
|
self.close_connection = True
|
|
self.reply(500, {'error': '서버 저장에 실패했습니다. PC 백업을 보관하세요.'})
|
|
|
|
def post(self):
|
|
path = self.path
|
|
if path == '/api/login':
|
|
return members().post(self, '/api/member/login', admin_only=True)
|
|
if path == '/api/admin/logout':
|
|
return members().post(self, '/api/member/logout')
|
|
if path.startswith('/api/member/') or path == '/api/admin/members':
|
|
return members().post(self, path)
|
|
if path == '/api/device-backups':
|
|
if self.headers.get('Content-Type') != 'application/octet-stream':
|
|
self.close_connection = True
|
|
return self.reply(400, {'error': '기기 백업 파일이 필요합니다.'})
|
|
result, headers = device_backups().store(self, self.body(SIZE))
|
|
return self.reply(200, result, headers=headers)
|
|
if path == '/api/backups':
|
|
if self.headers.get('X-Backup-Notice') != 'shown' or self.headers.get('Content-Type') != 'application/octet-stream':
|
|
self.close_connection = True
|
|
return self.reply(400, {'error': 'ROM 추출 화면에서 백업 안내를 확인하세요.'})
|
|
data = self.body(SIZE)
|
|
return self.reply(200, store_image(data))
|
|
if self.headers.get('Content-Type', '').split(';')[0] != 'application/json':
|
|
self.close_connection = True
|
|
return self.reply(400, {'error': 'JSON 요청이 필요합니다.'})
|
|
if path != '/api/login' and not self.authorized():
|
|
self.close_connection = True
|
|
return self.reply(401, {'error': '관리자 로그인이 필요합니다.'})
|
|
body = json.loads(self.body(4096))
|
|
if path == '/api/admin/settings':
|
|
with LOCK:
|
|
cfg = config()
|
|
title, description = body.get('title', ''), body.get('description', '')
|
|
size = body.get('maxStorageMB')
|
|
if not isinstance(title, str) or not 1 <= len(title.strip()) <= 60 or not isinstance(description, str) or not 1 <= len(description.strip()) <= 300:
|
|
raise ValueError('제목은 1~60자, 소개는 1~300자로 입력하세요.')
|
|
if type(size) is not int or not 16 <= size <= 4096 or type(body.get('autoBackup')) is not bool:
|
|
raise ValueError('용량은 16~4096 MB로 입력하세요.')
|
|
mode = body.get('backupMode', cfg['backupMode'])
|
|
capacity = body.get('deviceStorageMB', cfg['deviceStorageMB'])
|
|
retention = body.get('deviceRetentionHours', cfg['deviceRetentionHours'])
|
|
flags = body.get('features', cfg['features'])
|
|
if mode not in ('server', 'local') or type(capacity) is not int or not 16 <= capacity <= 20480 or type(retention) is not int or not 1 <= retention <= 168:
|
|
raise ValueError('백업 방식과 임시 보관 용량 및 보관 시간을 확인하세요.')
|
|
if not isinstance(flags, dict) or set(flags) - set(FEATURES) or any(type(v) is not bool for v in flags.values()):
|
|
raise ValueError('추가 기능 설정이 잘못되었습니다.')
|
|
cfg.update(title=title.strip(), description=description.strip(), maxStorageMB=size, autoBackup=body['autoBackup'], backupMode=mode, deviceStorageMB=capacity, deviceRetentionHours=retention, features={key: flags.get(key, False) for key in FEATURES})
|
|
atomic_json(DATA / 'config.json', cfg)
|
|
return self.reply(200, {'ok': True})
|
|
if path == '/api/admin/password':
|
|
with LOCK:
|
|
cfg = config()
|
|
password = body.get('newPassword', '')
|
|
if not password_ok(str(body.get('currentPassword', '')), cfg['passwordHash']):
|
|
raise ValueError('현재 비밀번호가 다릅니다.')
|
|
if not isinstance(password, str) or not 10 <= len(password) <= 128:
|
|
raise ValueError('새 비밀번호는 10~128자로 입력하세요.')
|
|
cfg['passwordHash'] = password_hash(password)
|
|
atomic_json(DATA / 'config.json', cfg)
|
|
SESSIONS.clear()
|
|
with members().db() as db:
|
|
db.execute('DELETE FROM sessions WHERE user IN (SELECT id FROM users WHERE username=?)', (cfg['username'].lower(),))
|
|
return self.reply(200, {'ok': True}, headers={'Set-Cookie': 'tama_admin=; Path=/api; HttpOnly; Secure; SameSite=Strict; Max-Age=0'})
|
|
if path == '/api/admin/record':
|
|
digest = body.get('sha256')
|
|
with LOCK:
|
|
item = next((r for r in records() if r['sha256'] == digest), None)
|
|
if not item:
|
|
raise ValueError('백업을 찾지 못했습니다.')
|
|
folder = DATA / item['slug']
|
|
if body.get('action') == 'delete':
|
|
if item['protected']:
|
|
raise ValueError('최초 원본은 삭제할 수 없습니다.')
|
|
if item['published']:
|
|
raise ValueError('비공개로 전환한 뒤 삭제하세요.')
|
|
image_path(item).unlink()
|
|
(folder / 'metadata.json').unlink()
|
|
else:
|
|
label = body.get('label', '')
|
|
if not isinstance(label, str) or not 1 <= len(label.strip()) <= 100 or type(body.get('published')) is not bool:
|
|
raise ValueError('표시 이름과 공개 여부를 확인하세요.')
|
|
item.update(label=label.strip(), published=body['published'])
|
|
atomic_json(folder / 'metadata.json', item)
|
|
return self.reply(200, {'ok': True})
|
|
self.reply(404, {'error': '요청 경로가 없습니다.'})
|
|
|
|
|
|
if __name__ == '__main__':
|
|
DATA.mkdir(parents=True, exist_ok=True)
|
|
if not (DATA / 'config.json').exists():
|
|
raise SystemExit('Initialize protected config.json before starting.')
|
|
server = ThreadingHTTPServer(('0.0.0.0', int(os.environ.get('PORT', '8080'))), Handler)
|
|
server.daemon_threads = True
|
|
signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=server.shutdown, daemon=True).start())
|
|
try:
|
|
server.serve_forever()
|
|
finally:
|
|
server.server_close()
|