- Save active and paused torrents to torrents.edn on add, remove, pause, resume, and metadata fetch, then restore them on router startup. - Default path is $MOON_I2P_DATA_DIR, then $XDG_DATA_HOME, then ~/.local/share/moon-i2p-browser. Add --torrent-state <file> to override, or --no-torrent-state to disable. - Write the state file atomically (temp file, fsync, rename). A corrupt or unsupported file logs a warning and does not block startup. - Verify restored pieces incrementally in the background for large torrents; these show as state "checking" in /api/torrents. - Expose state_file in /api/status and the startup banner. - Add standard RFC 4648 Base64 encode/decode helpers, used for the info-b64 field. - Add the moonedn dependency and pass --torrent-state from the Android service.
343 lines
11 KiB
Python
Executable File
343 lines
11 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Firefox Native Messaging Host for moon-i2p router + BitTorrent/DHT API."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime, timezone
|
|
import json
|
|
import os
|
|
import platform
|
|
import signal
|
|
import socket
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
|
PID_FILE = Path("/tmp/moon_i2p_native_host_router.pid")
|
|
LOG_FILE = Path("/tmp/moon_i2p_native_router.log")
|
|
|
|
|
|
def read_msg():
|
|
raw_len = sys.stdin.buffer.read(4)
|
|
if len(raw_len) < 4:
|
|
return None
|
|
msg_len = struct.unpack("<I", raw_len)[0]
|
|
if msg_len == 0 or msg_len > 4 * 1024 * 1024:
|
|
return None
|
|
data = sys.stdin.buffer.read(msg_len)
|
|
if len(data) < msg_len:
|
|
return None
|
|
return json.loads(data.decode("utf-8"))
|
|
|
|
|
|
def send_msg(obj):
|
|
encoded = json.dumps(obj).encode("utf-8")
|
|
sys.stdout.buffer.write(struct.pack("<I", len(encoded)))
|
|
sys.stdout.buffer.write(encoded)
|
|
sys.stdout.buffer.flush()
|
|
|
|
|
|
def find_router_binary():
|
|
env_bin = os.environ.get("MOON_I2P_ROUTER_BIN", "").strip()
|
|
if env_bin and Path(env_bin).is_file():
|
|
return env_bin
|
|
candidates = [
|
|
REPO_ROOT / "_build" / "native" / "release" / "build" / "cmd" / "router" / "router.exe",
|
|
REPO_ROOT / "_build" / "native" / "debug" / "build" / "cmd" / "router" / "router.exe",
|
|
]
|
|
for c in candidates:
|
|
if c.is_file():
|
|
return str(c)
|
|
return None
|
|
|
|
|
|
def is_tcp_listening(host: str, port: int) -> bool:
|
|
try:
|
|
with socket.create_connection((host, port), timeout=0.3):
|
|
return True
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def read_managed_pid():
|
|
if not PID_FILE.is_file():
|
|
return None
|
|
try:
|
|
pid = int(PID_FILE.read_text(encoding="utf-8").strip())
|
|
os.kill(pid, 0)
|
|
return pid
|
|
except (ValueError, OSError):
|
|
return None
|
|
|
|
|
|
def resolve_data_dir() -> Path:
|
|
env_dir = os.environ.get("MOON_I2P_DATA_DIR", "").strip()
|
|
if env_dir:
|
|
return Path(env_dir)
|
|
xdg_data = os.environ.get("XDG_DATA_HOME", "").strip()
|
|
base = Path(xdg_data) if xdg_data else (Path.home() / ".local" / "share")
|
|
return base / "moon-i2p-browser"
|
|
|
|
|
|
def pid_alive(raw_pid) -> int | None:
|
|
if raw_pid is None or str(raw_pid).strip() == "":
|
|
return None
|
|
try:
|
|
pid = int(str(raw_pid).strip())
|
|
if pid <= 0:
|
|
return None
|
|
os.kill(pid, 0)
|
|
return pid
|
|
except (ValueError, OSError):
|
|
return None
|
|
|
|
|
|
def read_active_ports(data_dir: Path):
|
|
path = data_dir / "active_ports.json"
|
|
if not path.is_file():
|
|
return None
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
return data if isinstance(data, dict) else None
|
|
except (OSError, ValueError):
|
|
return None
|
|
|
|
|
|
def resolve_log_file(is_appimage: bool) -> Path:
|
|
env_log = os.environ.get("MOON_I2P_LOG_FILE", "").strip()
|
|
if env_log:
|
|
return Path(env_log)
|
|
appimage_log = resolve_data_dir() / "router.log"
|
|
if is_appimage:
|
|
return appimage_log
|
|
if read_managed_pid() is not None:
|
|
return LOG_FILE
|
|
log_exists = LOG_FILE.is_file()
|
|
app_exists = appimage_log.is_file()
|
|
if log_exists and app_exists:
|
|
try:
|
|
return (
|
|
appimage_log
|
|
if appimage_log.stat().st_mtime >= LOG_FILE.stat().st_mtime
|
|
else LOG_FILE
|
|
)
|
|
except OSError:
|
|
return appimage_log
|
|
if app_exists:
|
|
return appimage_log
|
|
return LOG_FILE
|
|
|
|
|
|
def read_file_tail(
|
|
path: Path, max_bytes: int = 32768
|
|
) -> tuple[bool, int, str, str, str]:
|
|
clamped = max(1024, min(int(max_bytes), 262144))
|
|
if not path.is_file():
|
|
return (False, 0, "", "", "")
|
|
try:
|
|
st = path.stat()
|
|
size = st.st_size
|
|
with open(path, "rb") as fp:
|
|
if size > clamped:
|
|
fp.seek(size - clamped)
|
|
raw = fp.read(clamped)
|
|
text = raw.decode("utf-8", errors="replace")
|
|
if size > clamped and "\n" in text:
|
|
text = text.split("\n", 1)[1]
|
|
mtime_iso = datetime.fromtimestamp(st.st_mtime, tz=timezone.utc).strftime(
|
|
"%Y-%m-%dT%H:%M:%SZ"
|
|
)
|
|
return (True, size, mtime_iso, text, "")
|
|
except OSError as exc:
|
|
return (True, 0, "", "", str(exc))
|
|
|
|
|
|
def summarize_log_tail(log_tail: str) -> dict:
|
|
lines = log_tail.splitlines()
|
|
unhandled_garlic = 0
|
|
garlic_decrypted = 0
|
|
stream_connect_timeouts = 0
|
|
bt_handshake_timeouts = 0
|
|
ls2_lookup_timeouts = 0
|
|
pieces_verified = 0
|
|
last_public_line = ""
|
|
for line in lines:
|
|
if "unhandled incoming Garlic" in line:
|
|
unhandled_garlic += 1
|
|
if "Garlic decrypted for" in line:
|
|
garlic_decrypted += 1
|
|
if "stream connect timeout" in line:
|
|
stream_connect_timeouts += 1
|
|
if "bt handshake timeout" in line:
|
|
bt_handshake_timeouts += 1
|
|
if "ls2 lookup timeout" in line:
|
|
ls2_lookup_timeouts += 1
|
|
if "bt piece #" in line:
|
|
pieces_verified += 1
|
|
if line.startswith("[public]"):
|
|
last_public_line = line
|
|
return {
|
|
"lines": len(lines),
|
|
"unhandled_garlic": unhandled_garlic,
|
|
"garlic_decrypted": garlic_decrypted,
|
|
"stream_connect_timeouts": stream_connect_timeouts,
|
|
"bt_handshake_timeouts": bt_handshake_timeouts,
|
|
"ls2_lookup_timeouts": ls2_lookup_timeouts,
|
|
"pieces_verified": pieces_verified,
|
|
"last_public_line": last_public_line,
|
|
}
|
|
|
|
|
|
def handle_request(req: dict) -> dict:
|
|
cmd = req.get("cmd", "")
|
|
is_appimage = os.environ.get("MOON_I2P_APPIMAGE") == "1"
|
|
env_proxy_host = os.environ.get("MOON_I2P_PROXY_HOST") or ""
|
|
env_proxy_port = int(os.environ.get("MOON_I2P_PROXY_PORT") or 0)
|
|
env_api_host = os.environ.get("MOON_I2P_API_HOST") or ""
|
|
env_api_port = int(os.environ.get("MOON_I2P_API_PORT") or 0)
|
|
env_download_dir = (os.environ.get("MOON_I2P_DOWNLOAD_DIR") or "").strip()
|
|
|
|
proxy_host = env_proxy_host if (is_appimage and env_proxy_host) else str(req.get("proxy_host") or "127.0.0.1")
|
|
proxy_port = env_proxy_port if (is_appimage and env_proxy_port > 0) else int(req.get("proxy_port") or 4444)
|
|
api_host = env_api_host if (is_appimage and env_api_host) else str(req.get("api_host") or "127.0.0.1")
|
|
api_port = env_api_port if (is_appimage and env_api_port > 0) else int(req.get("api_port") or 4445)
|
|
download_dir = env_download_dir if (is_appimage and env_download_dir) else str(req.get("download_dir") or "").strip()
|
|
|
|
if cmd == "status":
|
|
managed_pid = read_managed_pid()
|
|
return {
|
|
"ok": True,
|
|
"available": True,
|
|
"appimage": is_appimage,
|
|
"env_proxy_host": env_proxy_host,
|
|
"env_proxy_port": env_proxy_port,
|
|
"env_api_host": env_api_host,
|
|
"env_api_port": env_api_port,
|
|
"env_download_dir": env_download_dir,
|
|
"api_reachable": is_tcp_listening(api_host, api_port),
|
|
"managed_running": managed_pid is not None,
|
|
"managed_pid": managed_pid,
|
|
"router_bin": find_router_binary(),
|
|
"log_path": str(resolve_log_file(is_appimage)),
|
|
}
|
|
|
|
if cmd == "diagnostics":
|
|
try:
|
|
raw_mb = req.get("max_bytes")
|
|
max_bytes = int(raw_mb) if raw_mb is not None else 32768
|
|
except (TypeError, ValueError):
|
|
max_bytes = 32768
|
|
data_dir = resolve_data_dir()
|
|
log_path = resolve_log_file(is_appimage)
|
|
active_ports = read_active_ports(data_dir)
|
|
managed_pid = read_managed_pid()
|
|
router_pid = (
|
|
pid_alive(os.environ.get("MOON_I2P_ROUTER_PID"))
|
|
or managed_pid
|
|
or pid_alive((active_ports or {}).get("router_pid"))
|
|
)
|
|
log_exists, log_size_bytes, log_mtime_iso, log_tail, log_error = read_file_tail(
|
|
log_path, max_bytes
|
|
)
|
|
return {
|
|
"ok": True,
|
|
"available": True,
|
|
"appimage": is_appimage,
|
|
"platform": platform.platform(),
|
|
"python": platform.python_version(),
|
|
"api_reachable": is_tcp_listening(api_host, api_port),
|
|
"proxy_reachable": is_tcp_listening(proxy_host, proxy_port),
|
|
"managed_running": managed_pid is not None,
|
|
"router_pid": router_pid,
|
|
"router_bin": find_router_binary(),
|
|
"data_dir": str(data_dir),
|
|
"active_ports": active_ports,
|
|
"env_proxy_host": env_proxy_host,
|
|
"env_proxy_port": env_proxy_port,
|
|
"env_api_host": env_api_host,
|
|
"env_api_port": env_api_port,
|
|
"env_download_dir": env_download_dir,
|
|
"log_path": str(log_path),
|
|
"log_exists": log_exists,
|
|
"log_size_bytes": log_size_bytes,
|
|
"log_mtime_iso": log_mtime_iso,
|
|
"log_error": log_error,
|
|
"log_summary": summarize_log_tail(log_tail),
|
|
"log_tail": log_tail,
|
|
}
|
|
|
|
if cmd == "start_router":
|
|
if is_tcp_listening(api_host, api_port):
|
|
return {
|
|
"ok": True,
|
|
"already_running": True,
|
|
"managed_pid": read_managed_pid(),
|
|
}
|
|
router_bin = find_router_binary()
|
|
if not router_bin:
|
|
return {
|
|
"ok": False,
|
|
"error": "router.exe not found; run `moon build --target native cmd/router`",
|
|
}
|
|
args = [
|
|
router_bin,
|
|
"--public",
|
|
"--debug",
|
|
"--http-proxy",
|
|
f"{proxy_host}:{proxy_port}",
|
|
"--torrent-api",
|
|
f"{api_host}:{api_port}",
|
|
]
|
|
if download_dir:
|
|
args.extend(["--download-dir", download_dir])
|
|
args.extend(["--torrent-state", str(resolve_data_dir() / "torrents.edn")])
|
|
with open(LOG_FILE, "ab") as log_fp:
|
|
proc = subprocess.Popen(
|
|
args,
|
|
cwd=str(REPO_ROOT),
|
|
stdin=subprocess.DEVNULL,
|
|
stdout=log_fp,
|
|
stderr=log_fp,
|
|
start_new_session=True,
|
|
)
|
|
PID_FILE.write_text(f"{proc.pid}\n", encoding="utf-8")
|
|
deadline = time.time() + 2.0
|
|
while time.time() < deadline:
|
|
if is_tcp_listening(api_host, api_port):
|
|
return {"ok": True, "pid": proc.pid, "api_reachable": True}
|
|
if proc.poll() is not None:
|
|
return {
|
|
"ok": False,
|
|
"error": f"router.exe exited early (code={proc.returncode}); see {LOG_FILE}",
|
|
}
|
|
time.sleep(0.1)
|
|
return {"ok": True, "pid": proc.pid, "api_reachable": False, "starting": True}
|
|
|
|
if cmd == "stop_router":
|
|
pid = read_managed_pid()
|
|
if pid is None:
|
|
return {"ok": True, "stopped": False}
|
|
try:
|
|
os.kill(pid, signal.SIGTERM)
|
|
PID_FILE.unlink(missing_ok=True)
|
|
return {"ok": True, "stopped": True, "pid": pid}
|
|
except OSError as exc:
|
|
return {"ok": False, "error": str(exc)}
|
|
|
|
return {"ok": False, "error": f"unknown cmd: {cmd}"}
|
|
|
|
|
|
def main():
|
|
while True:
|
|
req = read_msg()
|
|
if req is None:
|
|
break
|
|
send_msg(handle_request(req))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|