feat: add diagnostics report to Firefox torrent extension
- Add a Diagnostics panel to the extension popup and manager page with copy and refresh actions - Collect extension settings, router API status, torrents, DHT nodes, and a tail of the router log into one report - Add a native host `diagnostics` command that reports router PID, active ports, log path, and log summary counters - Export data dir, log file, router PID, and SAM port from the AppImage launcher - Start the router with `--debug` so the log tail has detailed output - Bump extension version to 0.1.4 and request clipboardWrite permission
This commit is contained in:
1 parent
9aa15f9ae8
commit
4bb81f1b80
9 files changed
+486
-1
No files matched your search
Binary file not shown.
@@ -205,6 +205,128 @@ async function gatherFullState() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function safePrettyJson(obj, compact = false) {
|
||||||
|
try {
|
||||||
|
return compact ? JSON.stringify(obj) : JSON.stringify(obj, null, 2);
|
||||||
|
} catch (err) {
|
||||||
|
return `{"ok":false,"error":${JSON.stringify(String(err))}}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDiagnosticsReport(cfg, nativeDiag, routerStatus, dht, torrents) {
|
||||||
|
const manifest = browser.runtime.getManifest ? browser.runtime.getManifest() : {};
|
||||||
|
const nd = nativeDiag || {};
|
||||||
|
const lines = [];
|
||||||
|
lines.push("=== Moon I2P Firefox Diagnostics ===");
|
||||||
|
lines.push(`Timestamp: ${new Date().toISOString()}`);
|
||||||
|
lines.push(`Extension Version: ${manifest.version || "?"}`);
|
||||||
|
lines.push(`User Agent: ${typeof navigator !== "undefined" ? navigator.userAgent : "?"}`);
|
||||||
|
const modeStr = nd.appimage ? "AppImage" : "Standalone";
|
||||||
|
lines.push(`Mode: ${modeStr}${nd.platform ? ` · ${nd.platform}` : ""}`);
|
||||||
|
|
||||||
|
if (nd.available) {
|
||||||
|
lines.push(
|
||||||
|
`Native Host: available=true · router_pid=${nd.router_pid ?? "none"} · managed_running=${!!nd.managed_running} · api_reachable=${!!nd.api_reachable} · proxy_reachable=${!!nd.proxy_reachable}`
|
||||||
|
);
|
||||||
|
if (nd.router_bin) {
|
||||||
|
lines.push(`Router Binary: ${nd.router_bin}`);
|
||||||
|
}
|
||||||
|
if (nd.active_ports) {
|
||||||
|
lines.push(`Active Ports: ${safePrettyJson(nd.active_ports, true)}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lines.push(
|
||||||
|
`Native Host: available=false · error=${nd.error || "unavailable (run `just extension` to install native host)"}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push(
|
||||||
|
`Settings: proxyEnabled=${!!cfg.proxyEnabled} · proxy=${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444} · api=${cfg.apiHost || "127.0.0.1"}:${cfg.apiPort || 4445} · interceptTorrents=${!!cfg.interceptTorrents}`
|
||||||
|
);
|
||||||
|
lines.push(`Download Dir: ${cfg.downloadDir || "(router default)"}`);
|
||||||
|
|
||||||
|
if (nd.log_path) {
|
||||||
|
if (nd.log_exists) {
|
||||||
|
lines.push(
|
||||||
|
`Log File: ${nd.log_path} (${nd.log_size_bytes || 0} bytes, mtime=${nd.log_mtime_iso || "?"})${nd.log_error ? ` · err=${nd.log_error}` : ""}`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
lines.push(`Log File: MISSING (${nd.log_path})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nd.log_summary) {
|
||||||
|
const s = nd.log_summary;
|
||||||
|
lines.push(
|
||||||
|
`Log Tail Summary (${s.lines || 0} lines): unhandled_garlic=${s.unhandled_garlic || 0} · garlic_decrypted=${s.garlic_decrypted || 0} · stream_connect_timeouts=${s.stream_connect_timeouts || 0} · bt_handshake_timeouts=${s.bt_handshake_timeouts || 0} · ls2_lookup_timeouts=${s.ls2_lookup_timeouts || 0} · pieces_verified=${s.pieces_verified || 0}`
|
||||||
|
);
|
||||||
|
if (s.last_public_line) {
|
||||||
|
lines.push(`Last Router Status: ${s.last_public_line}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
lines.push("");
|
||||||
|
lines.push("=== Router API /api/status ===");
|
||||||
|
lines.push(safePrettyJson(routerStatus));
|
||||||
|
|
||||||
|
lines.push("");
|
||||||
|
lines.push("=== Router API /api/torrents ===");
|
||||||
|
lines.push(safePrettyJson(torrents));
|
||||||
|
|
||||||
|
lines.push("");
|
||||||
|
lines.push("=== Router API /api/dht/nodes ===");
|
||||||
|
lines.push(safePrettyJson(dht, true));
|
||||||
|
|
||||||
|
lines.push("");
|
||||||
|
lines.push("=== Native moon-i2p Router Log (tail 32 KiB) ===");
|
||||||
|
if (!nd.available) {
|
||||||
|
lines.push(
|
||||||
|
`(native host unavailable: ${nd.error || "run `just extension` to inspect desktop router logs"})`
|
||||||
|
);
|
||||||
|
} else if (nd.log_error) {
|
||||||
|
lines.push(`(error reading ${nd.log_path || "router.log"}: ${nd.log_error})`);
|
||||||
|
} else if (!nd.log_exists) {
|
||||||
|
lines.push(`(log file not found at ${nd.log_path || "router.log"})`);
|
||||||
|
} else if (!nd.log_tail) {
|
||||||
|
lines.push("(empty)");
|
||||||
|
} else {
|
||||||
|
lines.push(nd.log_tail.replace(/\n+$/, ""));
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines.join("\n") + "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gatherDiagnostics(maxBytes = 32768) {
|
||||||
|
await loadSettings();
|
||||||
|
if (!syncedAppImageEnv) {
|
||||||
|
await syncFromNativeEnv();
|
||||||
|
}
|
||||||
|
const [nativeDiag, routerStatus, dht, torrents] = await Promise.all([
|
||||||
|
nativeCommand("diagnostics", { max_bytes: maxBytes }),
|
||||||
|
apiJson("/api/status", "GET", null, 3000).catch((e) => ({ ok: false, error: String(e) })),
|
||||||
|
apiJson("/api/dht/nodes", "GET", null, 3000).catch((e) => ({ ok: false, error: String(e) })),
|
||||||
|
apiJson("/api/torrents", "GET", null, 3000).catch((e) => ({ ok: false, error: String(e) })),
|
||||||
|
]);
|
||||||
|
const report = formatDiagnosticsReport(
|
||||||
|
cachedSettings,
|
||||||
|
nativeDiag,
|
||||||
|
routerStatus,
|
||||||
|
dht,
|
||||||
|
torrents
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
report,
|
||||||
|
meta: {
|
||||||
|
logPath: nativeDiag?.log_path || "",
|
||||||
|
logExists: !!nativeDiag?.log_exists,
|
||||||
|
logSizeBytes: Number(nativeDiag?.log_size_bytes || 0),
|
||||||
|
nativeAvailable: !!nativeDiag?.available,
|
||||||
|
nativeError: nativeDiag?.error || "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Intercept completed/started .torrent downloads from .i2p when enabled.
|
// Intercept completed/started .torrent downloads from .i2p when enabled.
|
||||||
browser.downloads.onCreated.addListener(async (item) => {
|
browser.downloads.onCreated.addListener(async (item) => {
|
||||||
try {
|
try {
|
||||||
@@ -231,6 +353,8 @@ browser.runtime.onMessage.addListener(async (msg) => {
|
|||||||
return { ok: true, settings: cachedSettings };
|
return { ok: true, settings: cachedSettings };
|
||||||
case "getState":
|
case "getState":
|
||||||
return gatherFullState();
|
return gatherFullState();
|
||||||
|
case "getDiagnostics":
|
||||||
|
return gatherDiagnostics(msg.maxBytes || 32768);
|
||||||
case "saveSettings": {
|
case "saveSettings": {
|
||||||
const incoming = msg.settings || {};
|
const incoming = msg.settings || {};
|
||||||
const patch = {};
|
const patch = {};
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<span id="router-pill" class="pill offline">Offline</span>
|
<span id="router-pill" class="pill offline">Offline</span>
|
||||||
|
<button id="header-diag-btn" class="secondary" type="button">Diagnostics</button>
|
||||||
<button id="start-router-btn">Start Router</button>
|
<button id="start-router-btn">Start Router</button>
|
||||||
<button id="stop-router-btn" class="secondary" style="display:none;">Stop Router</button>
|
<button id="stop-router-btn" class="secondary" style="display:none;">Stop Router</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -85,6 +86,18 @@
|
|||||||
<div id="torrents-list">No torrents added yet.</div>
|
<div id="torrents-list">No torrents added yet.</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section id="diagnostics-card" class="card">
|
||||||
|
<h2>
|
||||||
|
<span>Diagnostics & Verbose Logs</span>
|
||||||
|
<span class="row">
|
||||||
|
<button id="copy-diag-btn" type="button">Copy Diagnostics</button>
|
||||||
|
<button id="refresh-diag-btn" class="secondary" type="button">Refresh</button>
|
||||||
|
</span>
|
||||||
|
</h2>
|
||||||
|
<div id="diag-status" class="msg"></div>
|
||||||
|
<pre id="diagnostics-log" class="mono diag-log">Loading diagnostics...</pre>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<h2><span>Extension & Router Settings</span></h2>
|
<h2><span>Extension & Router Settings</span></h2>
|
||||||
<form id="settings-form">
|
<form id="settings-form">
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"manifest_version": 2,
|
"manifest_version": 2,
|
||||||
"name": "Moon I2P Torrent & Proxy",
|
"name": "Moon I2P Torrent & Proxy",
|
||||||
"version": "0.1.3",
|
"version": "0.1.4",
|
||||||
"description": "Route .i2p browsing through moon-i2p and manage I2P BitTorrent + I2P DHT torrents from Firefox.",
|
"description": "Route .i2p browsing through moon-i2p and manage I2P BitTorrent + I2P DHT torrents from Firefox.",
|
||||||
"icons": {
|
"icons": {
|
||||||
"48": "icon.svg",
|
"48": "icon.svg",
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"tabs",
|
"tabs",
|
||||||
"downloads",
|
"downloads",
|
||||||
"nativeMessaging",
|
"nativeMessaging",
|
||||||
|
"clipboardWrite",
|
||||||
"http://127.0.0.1/*",
|
"http://127.0.0.1/*",
|
||||||
"http://localhost/*",
|
"http://localhost/*",
|
||||||
"*://*.i2p/*"
|
"*://*.i2p/*"
|
||||||
|
|||||||
@@ -107,6 +107,16 @@
|
|||||||
</form>
|
</form>
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
<details id="diagnostics-details" class="card">
|
||||||
|
<summary>Diagnostics & Verbose Logs</summary>
|
||||||
|
<div class="row" style="margin-top:8px;justify-content:flex-end;">
|
||||||
|
<button id="copy-diag-btn" type="button">Copy Diagnostics</button>
|
||||||
|
<button id="refresh-diag-btn" class="secondary" type="button">Refresh</button>
|
||||||
|
</div>
|
||||||
|
<div id="diag-status" class="msg"></div>
|
||||||
|
<pre id="diagnostics-log" class="mono diag-log">Open to load diagnostics...</pre>
|
||||||
|
</details>
|
||||||
|
|
||||||
<script src="ui.js"></script>
|
<script src="ui.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -238,3 +238,22 @@ details summary {
|
|||||||
padding: 3px 0;
|
padding: 3px 0;
|
||||||
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pre.diag-log {
|
||||||
|
margin: 8px 0 0 0;
|
||||||
|
background: #0b1222;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px;
|
||||||
|
font-size: 11px;
|
||||||
|
line-height: 1.4;
|
||||||
|
max-height: 300px;
|
||||||
|
overflow: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
body.popup pre.diag-log {
|
||||||
|
max-height: 180px;
|
||||||
|
}
|
||||||
@@ -55,6 +55,96 @@ const dirtyFields = new Set();
|
|||||||
let refreshInFlight = false;
|
let refreshInFlight = false;
|
||||||
let refreshPending = false;
|
let refreshPending = false;
|
||||||
let initialSettingsPromise = null;
|
let initialSettingsPromise = null;
|
||||||
|
let latestDiagnosticsReport = "";
|
||||||
|
let diagInFlight = false;
|
||||||
|
let diagPromise = null;
|
||||||
|
let copyBtnTimer = null;
|
||||||
|
|
||||||
|
function setDiagMsg(text, isErr = false) {
|
||||||
|
const el = $("diag-status");
|
||||||
|
if (!el) return;
|
||||||
|
el.textContent = text;
|
||||||
|
el.className = isErr ? "msg err" : "msg";
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copyTextToClipboard(text) {
|
||||||
|
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
return true;
|
||||||
|
} catch (_e) {
|
||||||
|
// Fall through to textarea + execCommand fallback
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const ta = document.createElement("textarea");
|
||||||
|
ta.value = text;
|
||||||
|
ta.setAttribute("readonly", "");
|
||||||
|
ta.style.position = "fixed";
|
||||||
|
ta.style.top = "-9999px";
|
||||||
|
ta.style.left = "-9999px";
|
||||||
|
document.body.appendChild(ta);
|
||||||
|
ta.select();
|
||||||
|
let ok = false;
|
||||||
|
try {
|
||||||
|
ok = document.execCommand("copy");
|
||||||
|
} finally {
|
||||||
|
document.body.removeChild(ta);
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDiagnostics(showStatus = false) {
|
||||||
|
const logEl = $("diagnostics-log");
|
||||||
|
if (!logEl) return latestDiagnosticsReport;
|
||||||
|
if (diagInFlight && diagPromise) {
|
||||||
|
return diagPromise;
|
||||||
|
}
|
||||||
|
diagInFlight = true;
|
||||||
|
if (showStatus) {
|
||||||
|
setDiagMsg("Collecting diagnostics...");
|
||||||
|
}
|
||||||
|
diagPromise = (async () => {
|
||||||
|
try {
|
||||||
|
const res = await browser.runtime.sendMessage({ type: "getDiagnostics" });
|
||||||
|
if (res && res.ok && res.report) {
|
||||||
|
latestDiagnosticsReport = res.report;
|
||||||
|
logEl.textContent = res.report;
|
||||||
|
if (showStatus) {
|
||||||
|
const meta = res.meta || {};
|
||||||
|
if (!meta.nativeAvailable) {
|
||||||
|
setDiagMsg(
|
||||||
|
`Diagnostics refreshed (native host unavailable: ${meta.nativeError || "log tail skipped"}).`,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
} else if (meta.logPath) {
|
||||||
|
setDiagMsg(`Diagnostics refreshed (${meta.logPath}).`);
|
||||||
|
} else {
|
||||||
|
setDiagMsg("Diagnostics refreshed.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
setDiagMsg("");
|
||||||
|
}
|
||||||
|
return res.report;
|
||||||
|
}
|
||||||
|
const errMsg = (res && res.error) || "failed to collect diagnostics";
|
||||||
|
if (!latestDiagnosticsReport) {
|
||||||
|
logEl.textContent = `Error loading diagnostics: ${errMsg}`;
|
||||||
|
}
|
||||||
|
setDiagMsg(`Diagnostics failed: ${errMsg}`, true);
|
||||||
|
return latestDiagnosticsReport;
|
||||||
|
} catch (err) {
|
||||||
|
if (!latestDiagnosticsReport) {
|
||||||
|
logEl.textContent = `Error loading diagnostics: ${err}`;
|
||||||
|
}
|
||||||
|
setDiagMsg(`Diagnostics failed: ${err}`, true);
|
||||||
|
return latestDiagnosticsReport;
|
||||||
|
} finally {
|
||||||
|
diagInFlight = false;
|
||||||
|
diagPromise = null;
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
return diagPromise;
|
||||||
|
}
|
||||||
|
|
||||||
function parsePort(raw, fallback) {
|
function parsePort(raw, fallback) {
|
||||||
const s = String(raw ?? "").trim();
|
const s = String(raw ?? "").trim();
|
||||||
@@ -364,7 +454,62 @@ document.addEventListener("DOMContentLoaded", () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const headerDiagBtn = $("header-diag-btn");
|
||||||
|
if (headerDiagBtn) {
|
||||||
|
headerDiagBtn.addEventListener("click", () => {
|
||||||
|
const card = $("diagnostics-card");
|
||||||
|
if (card) {
|
||||||
|
card.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||||
|
}
|
||||||
|
loadDiagnostics(true);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshDiagBtn = $("refresh-diag-btn");
|
||||||
|
if (refreshDiagBtn) {
|
||||||
|
refreshDiagBtn.addEventListener("click", () => loadDiagnostics(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyDiagBtn = $("copy-diag-btn");
|
||||||
|
if (copyDiagBtn) {
|
||||||
|
copyDiagBtn.addEventListener("click", async () => {
|
||||||
|
const report = (await loadDiagnostics(false)) || latestDiagnosticsReport;
|
||||||
|
if (!report) {
|
||||||
|
setDiagMsg("No diagnostics available to copy.", true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const copied = await copyTextToClipboard(report);
|
||||||
|
if (copied) {
|
||||||
|
setDiagMsg("Copied diagnostics report to clipboard.");
|
||||||
|
copyDiagBtn.textContent = "Copied!";
|
||||||
|
if (copyBtnTimer) clearTimeout(copyBtnTimer);
|
||||||
|
copyBtnTimer = setTimeout(() => {
|
||||||
|
copyDiagBtn.textContent = "Copy Diagnostics";
|
||||||
|
copyBtnTimer = null;
|
||||||
|
}, 1500);
|
||||||
|
} else {
|
||||||
|
setDiagMsg("Clipboard copy blocked by browser; select text below to copy.", true);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setDiagMsg(`Clipboard copy failed: ${err}`, true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const diagDetails = $("diagnostics-details");
|
||||||
|
if (diagDetails) {
|
||||||
|
diagDetails.addEventListener("toggle", () => {
|
||||||
|
if (diagDetails.open) {
|
||||||
|
loadDiagnostics(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
initialSettingsPromise = loadSettingsFast();
|
initialSettingsPromise = loadSettingsFast();
|
||||||
refresh(false);
|
refresh(false);
|
||||||
|
if (document.body && document.body.classList.contains("manager")) {
|
||||||
|
loadDiagnostics(false);
|
||||||
|
}
|
||||||
setInterval(() => refresh(false), 2000);
|
setInterval(() => refresh(false), 2000);
|
||||||
});
|
});
|
||||||
@@ -327,11 +327,15 @@ else
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
export MOON_I2P_APPIMAGE=1
|
export MOON_I2P_APPIMAGE=1
|
||||||
|
export MOON_I2P_DATA_DIR="$DATA_DIR"
|
||||||
|
export MOON_I2P_LOG_FILE="$DATA_DIR/router.log"
|
||||||
|
export MOON_I2P_ROUTER_PID="$ROUTER_PID"
|
||||||
export MOON_I2P_ROUTER_BIN="$ROUTER_BIN"
|
export MOON_I2P_ROUTER_BIN="$ROUTER_BIN"
|
||||||
export MOON_I2P_PROXY_HOST=127.0.0.1
|
export MOON_I2P_PROXY_HOST=127.0.0.1
|
||||||
export MOON_I2P_PROXY_PORT="$PROXY_PORT"
|
export MOON_I2P_PROXY_PORT="$PROXY_PORT"
|
||||||
export MOON_I2P_API_HOST=127.0.0.1
|
export MOON_I2P_API_HOST=127.0.0.1
|
||||||
export MOON_I2P_API_PORT="$API_PORT"
|
export MOON_I2P_API_PORT="$API_PORT"
|
||||||
|
export MOON_I2P_SAM_PORT="$SAM_PORT"
|
||||||
export MOON_I2P_DOWNLOAD_DIR="$DOWNLOAD_DIR"
|
export MOON_I2P_DOWNLOAD_DIR="$DOWNLOAD_DIR"
|
||||||
|
|
||||||
"$APPDIR/usr/lib/firefox/firefox" \
|
"$APPDIR/usr/lib/firefox/firefox" \
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
"""Firefox Native Messaging Host for moon-i2p router + BitTorrent/DHT API."""
|
"""Firefox Native Messaging Host for moon-i2p router + BitTorrent/DHT API."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import platform
|
||||||
import signal
|
import signal
|
||||||
import socket
|
import socket
|
||||||
import struct
|
import struct
|
||||||
@@ -69,6 +73,124 @@ def read_managed_pid():
|
|||||||
return None
|
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:
|
def handle_request(req: dict) -> dict:
|
||||||
cmd = req.get("cmd", "")
|
cmd = req.get("cmd", "")
|
||||||
is_appimage = os.environ.get("MOON_I2P_APPIMAGE") == "1"
|
is_appimage = os.environ.get("MOON_I2P_APPIMAGE") == "1"
|
||||||
@@ -99,6 +221,52 @@ def handle_request(req: dict) -> dict:
|
|||||||
"managed_running": managed_pid is not None,
|
"managed_running": managed_pid is not None,
|
||||||
"managed_pid": managed_pid,
|
"managed_pid": managed_pid,
|
||||||
"router_bin": find_router_binary(),
|
"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 cmd == "start_router":
|
||||||
@@ -117,6 +285,7 @@ def handle_request(req: dict) -> dict:
|
|||||||
args = [
|
args = [
|
||||||
router_bin,
|
router_bin,
|
||||||
"--public",
|
"--public",
|
||||||
|
"--debug",
|
||||||
"--http-proxy",
|
"--http-proxy",
|
||||||
f"{proxy_host}:{proxy_port}",
|
f"{proxy_host}:{proxy_port}",
|
||||||
"--torrent-api",
|
"--torrent-api",
|
||||||
|
|||||||
Reference in new issue
Block a user