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
+466
@@ -0,0 +1,466 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build a self-contained MoonI2P-Browser x86_64 AppImage.
|
||||
|
||||
Bundles:
|
||||
- Official Mozilla Firefox ESR (x86_64)
|
||||
- Native moon-i2p router (--public, HTTP proxy, BitTorrent + I2P DHT API)
|
||||
- Pre-installed moon-i2p-torrent@local Firefox WebExtension & Native Messaging host
|
||||
- Pre-configured homepage http://insulaocculta.i2p/, I2P PAC routing, and HTTPS-First disabled for .i2p
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import urllib.request
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
CACHE_DIR = REPO_ROOT / ".cache" / "appimage"
|
||||
APP_DIR = CACHE_DIR / "AppDir"
|
||||
DIST_DIR = REPO_ROOT / "dist"
|
||||
OUTPUT_APPIMAGE = DIST_DIR / "MoonI2P-Browser-x86_64.AppImage"
|
||||
|
||||
EXT_SRC = REPO_ROOT / "extensions" / "firefox-i2p-torrent"
|
||||
EXT_XPI = REPO_ROOT / "extensions" / "firefox-i2p-torrent.xpi"
|
||||
NATIVE_HOST_SRC = REPO_ROOT / "scripts" / "moon_i2p_native_host.py"
|
||||
|
||||
FIREFOX_ESR_URL = (
|
||||
"https://download.mozilla.org/?product=firefox-esr-latest-ssl&os=linux64&lang=en-US"
|
||||
)
|
||||
APPIMAGE_RUNTIME_URL = (
|
||||
"https://github.com/AppImage/type2-runtime/releases/download/continuous/runtime-x86_64"
|
||||
)
|
||||
|
||||
|
||||
def run(cmd, cwd=None, check=True):
|
||||
print(f"[build_appimage] $ {' '.join(map(str, cmd))}")
|
||||
return subprocess.run(cmd, cwd=str(cwd or REPO_ROOT), check=check)
|
||||
|
||||
|
||||
def download_cached(url: str, dest: Path, min_bytes: int = 100_000) -> Path:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
if dest.is_file() and dest.stat().st_size >= min_bytes:
|
||||
print(f"[build_appimage] Using cached {dest} ({dest.stat().st_size} bytes)")
|
||||
return dest
|
||||
tmp = dest.with_suffix(dest.suffix + ".part")
|
||||
print(f"[build_appimage] Downloading {url} -> {dest}")
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "moon-i2p-appimage-builder/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=180) as resp, open(tmp, "wb") as fp:
|
||||
shutil.copyfileobj(resp, fp, length=1024 * 256)
|
||||
if tmp.stat().st_size < min_bytes:
|
||||
raise RuntimeError(f"Downloaded file too small: {tmp} ({tmp.stat().st_size} bytes)")
|
||||
tmp.replace(dest)
|
||||
return dest
|
||||
|
||||
|
||||
def build_router_binary() -> Path:
|
||||
rel_bin = REPO_ROOT / "_build" / "native" / "release" / "build" / "cmd" / "router" / "router.exe"
|
||||
dbg_bin = REPO_ROOT / "_build" / "native" / "debug" / "build" / "cmd" / "router" / "router.exe"
|
||||
res = subprocess.run(
|
||||
["moon", "build", "--target", "native", "--release", "cmd/router"],
|
||||
cwd=str(REPO_ROOT),
|
||||
)
|
||||
if res.returncode == 0 and rel_bin.is_file():
|
||||
return rel_bin
|
||||
run(["moon", "build", "--target", "native", "cmd/router"])
|
||||
if not dbg_bin.is_file():
|
||||
raise FileNotFoundError(f"router binary not built at {dbg_bin}")
|
||||
return dbg_bin
|
||||
|
||||
|
||||
def build_extension_xpi() -> Path:
|
||||
EXT_XPI.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(EXT_XPI, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
for path in sorted(EXT_SRC.rglob("*")):
|
||||
if path.is_file():
|
||||
zf.write(path, path.relative_to(EXT_SRC).as_posix())
|
||||
return EXT_XPI
|
||||
|
||||
|
||||
def make_executable(path: Path):
|
||||
mode = os.stat(path).st_mode
|
||||
os.chmod(path, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||
|
||||
|
||||
def write_firefox_configs(firefox_dir: Path):
|
||||
pref_dir = firefox_dir / "defaults" / "pref"
|
||||
pref_dir.mkdir(parents=True, exist_ok=True)
|
||||
(pref_dir / "autoconfig.js").write_text(
|
||||
'pref("general.config.filename", "mozilla.cfg");\n'
|
||||
'pref("general.config.obscure_value", 0);\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
# First line MUST be a comment (`//`).
|
||||
(firefox_dir / "mozilla.cfg").write_text(
|
||||
"// Moon I2P Browser defaults (Firefox ESR AppImage)\n"
|
||||
'pref("xpinstall.signatures.required", false);\n'
|
||||
'pref("extensions.autoDisableScopes", 0);\n'
|
||||
'pref("extensions.enabledScopes", 15);\n'
|
||||
'pref("extensions.sideloadScopes", 15);\n'
|
||||
'pref("extensions.startupScanScopes", 15);\n'
|
||||
'pref("extensions.installDistroAddons", true);\n'
|
||||
'defaultPref("browser.startup.homepage", "http://insulaocculta.i2p/");\n'
|
||||
'defaultPref("browser.startup.page", 1);\n'
|
||||
'defaultPref("dom.security.https_only_mode", false);\n'
|
||||
'defaultPref("dom.security.https_only_mode_pbm", false);\n'
|
||||
'defaultPref("dom.security.https_first", false);\n'
|
||||
'defaultPref("dom.security.https_first_pbm", false);\n'
|
||||
'pref("browser.fixup.domainsuffixwhitelist.i2p", true);\n'
|
||||
'pref("network.trr.mode", 5);\n'
|
||||
'pref("network.proxy.socks_remote_dns", true);\n'
|
||||
'pref("network.captive-portal-service.enabled", false);\n'
|
||||
'pref("network.connectivity-service.enabled", false);\n'
|
||||
'pref("browser.shell.checkDefaultBrowser", false);\n'
|
||||
'pref("app.update.auto", false);\n'
|
||||
'pref("app.update.enabled", false);\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
dist_dir = firefox_dir / "distribution"
|
||||
dist_dir.mkdir(parents=True, exist_ok=True)
|
||||
policies = {
|
||||
"policies": {
|
||||
"Homepage": {
|
||||
"URL": "http://insulaocculta.i2p/",
|
||||
"StartPage": "homepage",
|
||||
"Locked": False,
|
||||
},
|
||||
"OverrideFirstRunPage": "",
|
||||
"OverridePostUpdatePage": "",
|
||||
"DontCheckDefaultBrowser": True,
|
||||
"DisableAppUpdate": True,
|
||||
"DisableTelemetry": True,
|
||||
"DisablePocket": True,
|
||||
"DisableFirefoxStudies": True,
|
||||
"DNSOverHTTPS": {"Enabled": False},
|
||||
"Bookmarks": [
|
||||
{
|
||||
"Title": "Insula Occulta",
|
||||
"URL": "http://insulaocculta.i2p/",
|
||||
"Placement": "toolbar",
|
||||
},
|
||||
{
|
||||
"Title": "I2P Stats",
|
||||
"URL": "http://stats.i2p/",
|
||||
"Placement": "toolbar",
|
||||
},
|
||||
{
|
||||
"Title": "zzz.i2p",
|
||||
"URL": "http://zzz.i2p/",
|
||||
"Placement": "toolbar",
|
||||
},
|
||||
{
|
||||
"Title": "Postman Tracker",
|
||||
"URL": "http://tracker2.postman.i2p/",
|
||||
"Placement": "toolbar",
|
||||
},
|
||||
{
|
||||
"Title": "NotBob Directory",
|
||||
"URL": "http://notbob.i2p/",
|
||||
"Placement": "toolbar",
|
||||
},
|
||||
],
|
||||
"ExtensionSettings": {
|
||||
"moon-i2p-torrent@local": {
|
||||
"default_area": "navbar",
|
||||
"private_browsing": True,
|
||||
"updates_disabled": True,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
(dist_dir / "policies.json").write_text(
|
||||
json.dumps(policies, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
APP_RUN_SH = r'''#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
APPDIR="$(dirname "$(readlink -f "$0")")"
|
||||
DATA_DIR="${MOON_I2P_DATA_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/moon-i2p-browser}"
|
||||
PROFILE_DIR="${MOON_I2P_PROFILE_DIR:-$DATA_DIR/profile}"
|
||||
DOWNLOAD_DIR="${MOON_I2P_DOWNLOAD_DIR:-$HOME/Downloads/moon-i2p}"
|
||||
|
||||
mkdir -p "$DATA_DIR" "$PROFILE_DIR/extensions" "$DOWNLOAD_DIR"
|
||||
|
||||
# Ensure the bundled extension XPI is installed in the browser profile.
|
||||
cp -f "$APPDIR/usr/share/moon-i2p/moon-i2p-torrent@local.xpi" \
|
||||
"$PROFILE_DIR/extensions/moon-i2p-torrent@local.xpi"
|
||||
|
||||
# Install a stable Native Messaging host wrapper outside the ephemeral /tmp mount.
|
||||
if [[ "${MOON_I2P_NO_HOST_INSTALL:-0}" != "1" ]]; then
|
||||
HOST_COPY="$DATA_DIR/moon_i2p_native_host.py"
|
||||
cp -f "$APPDIR/usr/bin/moon_i2p_native_host.py" "$HOST_COPY"
|
||||
chmod 755 "$HOST_COPY"
|
||||
for NM_DIR in "$HOME/.mozilla/native-messaging-hosts" "$HOME/.config/mozilla/native-messaging-hosts"; do
|
||||
mkdir -p "$NM_DIR"
|
||||
cat > "$NM_DIR/moon_i2p_torrent.json" <<EOF
|
||||
{
|
||||
"name": "moon_i2p_torrent",
|
||||
"description": "moon-i2p native I2P router & BitTorrent/DHT controller",
|
||||
"path": "$HOST_COPY",
|
||||
"type": "stdio",
|
||||
"allowed_extensions": [
|
||||
"moon-i2p-torrent@local"
|
||||
]
|
||||
}
|
||||
EOF
|
||||
done
|
||||
fi
|
||||
|
||||
PYTHON_BIN="$(command -v python3 || true)"
|
||||
if [[ -n "$PYTHON_BIN" ]]; then
|
||||
read -r PROXY_PORT API_PORT SAM_PORT < <("$PYTHON_BIN" -c '
|
||||
import socket
|
||||
def pick(pref):
|
||||
for p in (pref, 0):
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.bind(("127.0.0.1", p))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
except OSError:
|
||||
s.close()
|
||||
raise RuntimeError("no free port")
|
||||
print(pick(4444), pick(4445), pick(7656))
|
||||
')
|
||||
else
|
||||
PROXY_PORT=4444
|
||||
API_PORT=4445
|
||||
SAM_PORT=7656
|
||||
fi
|
||||
|
||||
cat > "$PROFILE_DIR/i2p.pac" <<EOF
|
||||
function FindProxyForURL(url, host) {
|
||||
var h = (host || "").toLowerCase();
|
||||
if (h === "127.0.0.1" || h === "localhost" || h === "::1" || h === "[::1]") {
|
||||
return "DIRECT";
|
||||
}
|
||||
if (h === "i2p" || h.endsWith(".i2p")) {
|
||||
return "PROXY 127.0.0.1:$PROXY_PORT";
|
||||
}
|
||||
return "DIRECT";
|
||||
}
|
||||
EOF
|
||||
|
||||
cat > "$PROFILE_DIR/user.js" <<EOF
|
||||
user_pref("browser.startup.homepage", "http://insulaocculta.i2p/");
|
||||
user_pref("browser.startup.page", 1);
|
||||
user_pref("network.proxy.type", 2);
|
||||
user_pref("network.proxy.autoconfig_url", "file://$PROFILE_DIR/i2p.pac");
|
||||
user_pref("xpinstall.signatures.required", false);
|
||||
user_pref("extensions.autoDisableScopes", 0);
|
||||
user_pref("extensions.enabledScopes", 15);
|
||||
user_pref("dom.security.https_only_mode", false);
|
||||
user_pref("dom.security.https_only_mode_pbm", false);
|
||||
user_pref("dom.security.https_first", false);
|
||||
user_pref("dom.security.https_first_pbm", false);
|
||||
user_pref("browser.fixup.domainsuffixwhitelist.i2p", true);
|
||||
user_pref("network.trr.mode", 5);
|
||||
user_pref("network.proxy.socks_remote_dns", true);
|
||||
user_pref("network.captive-portal-service.enabled", false);
|
||||
user_pref("browser.shell.checkDefaultBrowser", false);
|
||||
EOF
|
||||
|
||||
ROUTER_BIN="$APPDIR/usr/bin/moon-i2p-router"
|
||||
ROUTER_PID=""
|
||||
FF_PID=""
|
||||
|
||||
cleanup() {
|
||||
local rc=$?
|
||||
rm -f "$DATA_DIR/active_ports.json"
|
||||
if [[ -n "$FF_PID" ]] && kill -0 "$FF_PID" 2>/dev/null; then
|
||||
kill -TERM "$FF_PID" 2>/dev/null || true
|
||||
wait "$FF_PID" 2>/dev/null || true
|
||||
fi
|
||||
if [[ -n "$ROUTER_PID" ]] && kill -0 "$ROUTER_PID" 2>/dev/null; then
|
||||
kill -TERM "$ROUTER_PID" 2>/dev/null || true
|
||||
for _ in $(seq 1 20); do
|
||||
kill -0 "$ROUTER_PID" 2>/dev/null || break
|
||||
sleep 0.1
|
||||
done
|
||||
if kill -0 "$ROUTER_PID" 2>/dev/null; then
|
||||
kill -KILL "$ROUTER_PID" 2>/dev/null || true
|
||||
fi
|
||||
wait "$ROUTER_PID" 2>/dev/null || true
|
||||
fi
|
||||
exit "$rc"
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
"$ROUTER_BIN" \
|
||||
--public \
|
||||
--sam "127.0.0.1:$SAM_PORT" \
|
||||
--http-proxy "127.0.0.1:$PROXY_PORT" \
|
||||
--torrent-api "127.0.0.1:$API_PORT" \
|
||||
--download-dir "$DOWNLOAD_DIR" \
|
||||
>> "$DATA_DIR/router.log" 2>&1 &
|
||||
ROUTER_PID=$!
|
||||
|
||||
cat > "$DATA_DIR/active_ports.json" <<EOF
|
||||
{"proxy_port": $PROXY_PORT, "api_port": $API_PORT, "sam_port": $SAM_PORT, "router_pid": $ROUTER_PID}
|
||||
EOF
|
||||
|
||||
if [[ -n "$PYTHON_BIN" ]]; then
|
||||
"$PYTHON_BIN" -c '
|
||||
import socket, sys, time
|
||||
port = int(sys.argv[1])
|
||||
deadline = time.time() + 5.0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
|
||||
sys.exit(0)
|
||||
except OSError:
|
||||
time.sleep(0.1)
|
||||
' "$API_PORT" || true
|
||||
else
|
||||
sleep 1
|
||||
fi
|
||||
|
||||
export MOON_I2P_APPIMAGE=1
|
||||
export MOON_I2P_ROUTER_BIN="$ROUTER_BIN"
|
||||
export MOON_I2P_PROXY_HOST=127.0.0.1
|
||||
export MOON_I2P_PROXY_PORT="$PROXY_PORT"
|
||||
export MOON_I2P_API_HOST=127.0.0.1
|
||||
export MOON_I2P_API_PORT="$API_PORT"
|
||||
export MOON_I2P_DOWNLOAD_DIR="$DOWNLOAD_DIR"
|
||||
|
||||
"$APPDIR/usr/lib/firefox/firefox" \
|
||||
--no-remote \
|
||||
--profile "$PROFILE_DIR" \
|
||||
--class "MoonI2PBrowser" \
|
||||
"$@" &
|
||||
FF_PID=$!
|
||||
wait "$FF_PID"
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
DIST_DIR.mkdir(parents=True, exist_ok=True)
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
router_bin = build_router_binary()
|
||||
xpi_path = build_extension_xpi()
|
||||
firefox_tar = download_cached(
|
||||
FIREFOX_ESR_URL, CACHE_DIR / "firefox-esr-linux64.tar.xz", min_bytes=20_000_000
|
||||
)
|
||||
runtime_bin = download_cached(
|
||||
APPIMAGE_RUNTIME_URL, CACHE_DIR / "runtime-x86_64", min_bytes=100_000
|
||||
)
|
||||
if runtime_bin.read_bytes()[:4] != b"\x7fELF":
|
||||
raise RuntimeError(f"Invalid ELF AppImage runtime at {runtime_bin}")
|
||||
|
||||
if APP_DIR.exists():
|
||||
shutil.rmtree(APP_DIR)
|
||||
(APP_DIR / "usr" / "bin").mkdir(parents=True)
|
||||
(APP_DIR / "usr" / "lib").mkdir(parents=True)
|
||||
(APP_DIR / "usr" / "share" / "moon-i2p").mkdir(parents=True)
|
||||
|
||||
print(f"[build_appimage] Extracting {firefox_tar.name}...")
|
||||
with tarfile.open(firefox_tar, "r:*") as tf:
|
||||
tf.extractall(APP_DIR / "usr" / "lib")
|
||||
|
||||
firefox_dir = APP_DIR / "usr" / "lib" / "firefox"
|
||||
if not (firefox_dir / "firefox").is_file():
|
||||
raise RuntimeError(f"Expected Firefox binary at {firefox_dir / 'firefox'}")
|
||||
|
||||
dist_ext_dir = firefox_dir / "distribution" / "extensions"
|
||||
dist_ext_dir.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(xpi_path, dist_ext_dir / "moon-i2p-torrent@local.xpi")
|
||||
shutil.copy2(xpi_path, APP_DIR / "usr" / "share" / "moon-i2p" / "moon-i2p-torrent@local.xpi")
|
||||
write_firefox_configs(firefox_dir)
|
||||
|
||||
router_dest = APP_DIR / "usr" / "bin" / "moon-i2p-router"
|
||||
shutil.copy2(router_bin, router_dest)
|
||||
make_executable(router_dest)
|
||||
|
||||
host_dest = APP_DIR / "usr" / "bin" / "moon_i2p_native_host.py"
|
||||
shutil.copy2(NATIVE_HOST_SRC, host_dest)
|
||||
make_executable(host_dest)
|
||||
|
||||
# Render desktop PNG icon via rsvg-convert (fallback magick).
|
||||
icon_png = APP_DIR / "moon-i2p-browser.png"
|
||||
svg_src = EXT_SRC / "icon.svg"
|
||||
if shutil.which("rsvg-convert"):
|
||||
run(["rsvg-convert", "-w", "256", "-h", "256", str(svg_src), "-o", str(icon_png)])
|
||||
elif shutil.which("magick"):
|
||||
run(["magick", "-background", "none", str(svg_src), "-resize", "256x256", str(icon_png)])
|
||||
else:
|
||||
raise RuntimeError("Need rsvg-convert or magick to render AppImage icon")
|
||||
|
||||
dir_icon = APP_DIR / ".DirIcon"
|
||||
if dir_icon.exists() or dir_icon.is_symlink():
|
||||
dir_icon.unlink()
|
||||
dir_icon.symlink_to("moon-i2p-browser.png")
|
||||
|
||||
(APP_DIR / "MoonI2P-Browser.desktop").write_text(
|
||||
"[Desktop Entry]\n"
|
||||
"Version=1.0\n"
|
||||
"Type=Application\n"
|
||||
"Name=Moon I2P Browser\n"
|
||||
"Comment=Zero-setup I2P browser and BitTorrent/DHT client powered by moon-i2p\n"
|
||||
"Exec=AppRun %u\n"
|
||||
"Icon=moon-i2p-browser\n"
|
||||
"Categories=Network;WebBrowser;P2P;\n"
|
||||
"MimeType=text/html;x-scheme-handler/magnet;application/x-bittorrent;\n"
|
||||
"StartupWMClass=MoonI2PBrowser\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
app_run = APP_DIR / "AppRun"
|
||||
app_run.write_text(APP_RUN_SH, encoding="utf-8")
|
||||
make_executable(app_run)
|
||||
|
||||
squashfs_img = CACHE_DIR / "moon-i2p-browser.squashfs"
|
||||
if squashfs_img.exists():
|
||||
squashfs_img.unlink()
|
||||
mk_res = subprocess.run(
|
||||
[
|
||||
"mksquashfs",
|
||||
str(APP_DIR),
|
||||
str(squashfs_img),
|
||||
"-root-owned",
|
||||
"-noappend",
|
||||
"-comp",
|
||||
"zstd",
|
||||
"-b",
|
||||
"1M",
|
||||
]
|
||||
)
|
||||
if mk_res.returncode != 0:
|
||||
run(
|
||||
[
|
||||
"mksquashfs",
|
||||
str(APP_DIR),
|
||||
str(squashfs_img),
|
||||
"-root-owned",
|
||||
"-noappend",
|
||||
"-comp",
|
||||
"gzip",
|
||||
"-b",
|
||||
"1M",
|
||||
]
|
||||
)
|
||||
|
||||
tmp_out = OUTPUT_APPIMAGE.with_suffix(".AppImage.part")
|
||||
with open(tmp_out, "wb") as out_fp:
|
||||
with open(runtime_bin, "rb") as rt_fp:
|
||||
shutil.copyfileobj(rt_fp, out_fp, length=1024 * 256)
|
||||
with open(squashfs_img, "rb") as sq_fp:
|
||||
shutil.copyfileobj(sq_fp, out_fp, length=1024 * 1024)
|
||||
make_executable(tmp_out)
|
||||
tmp_out.replace(OUTPUT_APPIMAGE)
|
||||
size_mb = OUTPUT_APPIMAGE.stat().st_size / (1024 * 1024)
|
||||
print(f"[build_appimage] Built {OUTPUT_APPIMAGE} ({size_mb:.1f} MiB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install Firefox Native Messaging manifest and build unsigned .xpi bundle."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
HOST_SCRIPT = REPO_ROOT / "scripts" / "moon_i2p_native_host.py"
|
||||
EXT_DIR = REPO_ROOT / "extensions" / "firefox-i2p-torrent"
|
||||
XPI_PATH = REPO_ROOT / "extensions" / "firefox-i2p-torrent.xpi"
|
||||
|
||||
MANIFEST_DIRS = [
|
||||
Path.home() / ".mozilla" / "native-messaging-hosts",
|
||||
Path.home() / ".config" / "mozilla" / "native-messaging-hosts",
|
||||
]
|
||||
|
||||
HOST_MANIFEST = {
|
||||
"name": "moon_i2p_torrent",
|
||||
"description": "moon-i2p native I2P router & BitTorrent/DHT controller",
|
||||
"path": str(HOST_SCRIPT),
|
||||
"type": "stdio",
|
||||
"allowed_extensions": ["moon-i2p-torrent@local"],
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
mode = os.stat(HOST_SCRIPT).st_mode
|
||||
os.chmod(HOST_SCRIPT, mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||
|
||||
for target_dir in MANIFEST_DIRS:
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
dest = target_dir / "moon_i2p_torrent.json"
|
||||
dest.write_text(json.dumps(HOST_MANIFEST, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Installed native messaging manifest: {dest}")
|
||||
|
||||
XPI_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(XPI_PATH, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
for path in sorted(EXT_DIR.rglob("*")):
|
||||
if path.is_file():
|
||||
arcname = path.relative_to(EXT_DIR).as_posix()
|
||||
zf.write(path, arcname)
|
||||
print(f"Built Firefox extension bundle: {XPI_PATH}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
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