feat: add I2P BitTorrent engine, DHT, and Firefox torrent extension
- Add pure-MoonBit bittorrent package: bencode codec, metainfo/magnet parsing with path traversal checks, peer wire protocol (BEP 10/9), and I2P Kademlia DHT with KRPC and 54-byte compact nodes - Add SHA-1 primitive in crypto for torrent info hashes - Add router torrent API and engine, enabled with --torrent-api (default 127.0.0.1:4445) and --download-dir - Add Firefox WebExtension torrent manager with native messaging host and packed .xpi - Add scripts to build a standalone Firefox + router AppImage and install the native host - Add just targets (proxy, appimage, extension), README docs, and ignore .cache/ and dist/
This commit is contained in:
1 parent
14eae00f5c
commit
fbe6818c4e
37 files changed
+8543
-9
No files matched your search
Executable
+172
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Firefox Native Messaging Host for moon-i2p router + BitTorrent/DHT API."""
|
||||
|
||||
import json
|
||||
import os
|
||||
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 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(),
|
||||
}
|
||||
|
||||
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",
|
||||
"--http-proxy",
|
||||
f"{proxy_host}:{proxy_port}",
|
||||
"--torrent-api",
|
||||
f"{api_host}:{api_port}",
|
||||
]
|
||||
if download_dir:
|
||||
args.extend(["--download-dir", download_dir])
|
||||
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()
|
||||
Reference in new issue
Block a user