diff --git a/extensions/firefox-i2p-torrent.xpi b/extensions/firefox-i2p-torrent.xpi index f0b1806..1778711 100644 Binary files a/extensions/firefox-i2p-torrent.xpi and b/extensions/firefox-i2p-torrent.xpi differ diff --git a/extensions/firefox-i2p-torrent/background.js b/extensions/firefox-i2p-torrent/background.js index cce3ec8..1d58eb7 100644 --- a/extensions/firefox-i2p-torrent/background.js +++ b/extensions/firefox-i2p-torrent/background.js @@ -22,36 +22,38 @@ async function loadSettings() { async function syncFromNativeEnv(force = false) { const st = await nativeCommand("status"); if (st && st.appimage && (!syncedAppImageEnv || force)) { - let changed = false; + const patch = {}; if (st.env_proxy_host && st.env_proxy_host !== cachedSettings.proxyHost) { - cachedSettings.proxyHost = st.env_proxy_host; - changed = true; + patch.proxyHost = st.env_proxy_host; } if (st.env_proxy_port > 0 && st.env_proxy_port !== Number(cachedSettings.proxyPort)) { - cachedSettings.proxyPort = st.env_proxy_port; - changed = true; + patch.proxyPort = st.env_proxy_port; } if (st.env_api_host && st.env_api_host !== cachedSettings.apiHost) { - cachedSettings.apiHost = st.env_api_host; - changed = true; + patch.apiHost = st.env_api_host; } if (st.env_api_port > 0 && st.env_api_port !== Number(cachedSettings.apiPort)) { - cachedSettings.apiPort = st.env_api_port; - changed = true; + patch.apiPort = st.env_api_port; } if (st.env_download_dir && !cachedSettings.downloadDir) { - cachedSettings.downloadDir = st.env_download_dir; - changed = true; + patch.downloadDir = st.env_download_dir; } syncedAppImageEnv = true; - if (changed) { - await browser.storage.local.set(cachedSettings); + if (Object.keys(patch).length > 0) { + cachedSettings = { ...cachedSettings, ...patch }; + await browser.storage.local.set(patch); } } return st; } -loadSettings().then(() => syncFromNativeEnv()); +let startupCompleted = false; +const startupReady = loadSettings() + .then(() => syncFromNativeEnv()) + .catch(() => null) + .finally(() => { + startupCompleted = true; + }); browser.storage.onChanged.addListener((changes, area) => { if (area !== "local") return; @@ -69,26 +71,33 @@ function isLoopbackHost(hostname) { ); } +function resolveProxyForRequest(requestInfo) { + try { + const url = new URL(requestInfo.url); + const host = url.hostname.toLowerCase(); + if (isLoopbackHost(host)) { + return { type: "direct" }; + } + if (cachedSettings.proxyEnabled && host.endsWith(".i2p")) { + return { + type: "http", + host: cachedSettings.proxyHost || "127.0.0.1", + port: Number(cachedSettings.proxyPort) || 4444, + }; + } + } catch (_e) { + // Fall through to direct + } + return { type: "direct" }; +} + // Route *.i2p URLs through moon-i2p HTTP proxy; never proxy loopback API calls. browser.proxy.onRequest.addListener( (requestInfo) => { - try { - const url = new URL(requestInfo.url); - const host = url.hostname.toLowerCase(); - if (isLoopbackHost(host)) { - return { type: "direct" }; - } - if (cachedSettings.proxyEnabled && host.endsWith(".i2p")) { - return { - type: "http", - host: cachedSettings.proxyHost || "127.0.0.1", - port: Number(cachedSettings.proxyPort) || 4444, - }; - } - } catch (_e) { - // Fall through to direct + if (!startupCompleted && !syncedAppImageEnv) { + return startupReady.then(() => resolveProxyForRequest(requestInfo)); } - return { type: "direct" }; + return resolveProxyForRequest(requestInfo); }, { urls: [""] } ); @@ -99,26 +108,37 @@ function apiBaseUrl() { return `http://${host}:${port}`; } -async function apiJson(path, method = "GET", bodyObj = null) { +async function apiJson(path, method = "GET", bodyObj = null, timeoutMs = 3000) { const headers = {}; - const opts = { method, headers, cache: "no-store" }; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + const opts = { method, headers, cache: "no-store", signal: controller.signal }; if (method === "POST") { headers["X-Moon-I2P"] = "1"; headers["Content-Type"] = "application/json"; opts.body = JSON.stringify(bodyObj || {}); } - const resp = await fetch(`${apiBaseUrl()}${path}`, opts); - const text = await resp.text(); - let data = null; try { - data = JSON.parse(text); - } catch (_e) { - data = { ok: resp.ok, raw: text }; + const resp = await fetch(`${apiBaseUrl()}${path}`, opts); + const text = await resp.text(); + let data = null; + try { + data = JSON.parse(text); + } catch (_e) { + data = { ok: resp.ok, raw: text }; + } + if (!resp.ok && data && !data.error) { + data.error = `HTTP ${resp.status}`; + } + return data; + } catch (err) { + if (err && err.name === "AbortError") { + throw new Error(`Router API timeout (${timeoutMs}ms)`); + } + throw err; + } finally { + clearTimeout(timer); } - if (!resp.ok && data && !data.error) { - data.error = `HTTP ${resp.status}`; - } - return data; } function bytesToBase64(bytes) { @@ -132,10 +152,15 @@ function bytesToBase64(bytes) { async function addTorrentBytes(uint8Bytes) { const b64 = bytesToBase64(uint8Bytes); - return apiJson("/api/torrents/add", "POST", { - torrent_b64: b64, - download_dir: cachedSettings.downloadDir || "", - }); + return apiJson( + "/api/torrents/add", + "POST", + { + torrent_b64: b64, + download_dir: cachedSettings.downloadDir || "", + }, + 15000 + ); } async function addTorrentFromUrl(urlStr) { @@ -167,9 +192,9 @@ async function gatherFullState() { await loadSettings(); const nativeStatus = await syncFromNativeEnv(); const [routerStatus, torrents, dht] = await Promise.all([ - apiJson("/api/status").catch((e) => ({ ok: false, error: String(e) })), - apiJson("/api/torrents").catch(() => ({ ok: false, torrents: [] })), - apiJson("/api/dht/nodes").catch(() => ({ ok: false, nodes: [] })), + apiJson("/api/status", "GET", null, 2500).catch((e) => ({ ok: false, error: String(e) })), + apiJson("/api/torrents", "GET", null, 2500).catch(() => ({ ok: false, torrents: [] })), + apiJson("/api/dht/nodes", "GET", null, 2500).catch(() => ({ ok: false, nodes: [] })), ]); return { settings: cachedSettings, @@ -202,12 +227,22 @@ browser.downloads.onCreated.addListener(async (item) => { browser.runtime.onMessage.addListener(async (msg) => { await loadSettings(); switch (msg?.type) { + case "getSettings": + return { ok: true, settings: cachedSettings }; case "getState": return gatherFullState(); case "saveSettings": { - const next = { ...cachedSettings, ...(msg.settings || {}) }; - await browser.storage.local.set(next); - cachedSettings = next; + const incoming = msg.settings || {}; + const patch = {}; + for (const key of Object.keys(DEFAULT_SETTINGS)) { + if (incoming[key] !== undefined) { + patch[key] = incoming[key]; + } + } + if (Object.keys(patch).length > 0) { + await browser.storage.local.set(patch); + cachedSettings = { ...cachedSettings, ...patch }; + } return { ok: true, settings: cachedSettings }; } case "startRouter": @@ -215,10 +250,15 @@ browser.runtime.onMessage.addListener(async (msg) => { case "stopRouter": return nativeCommand("stop_router"); case "addMagnet": - return apiJson("/api/torrents/magnet", "POST", { - uri: msg.uri || "", - download_dir: cachedSettings.downloadDir || "", - }); + return apiJson( + "/api/torrents/magnet", + "POST", + { + uri: msg.uri || "", + download_dir: cachedSettings.downloadDir || "", + }, + 15000 + ); case "addTorrentUrl": try { return await addTorrentFromUrl(msg.url); @@ -226,21 +266,31 @@ browser.runtime.onMessage.addListener(async (msg) => { return { ok: false, error: String(e) }; } case "addTorrentB64": - return apiJson("/api/torrents/add", "POST", { - torrent_b64: msg.torrentB64 || "", - download_dir: cachedSettings.downloadDir || "", - }); + return apiJson( + "/api/torrents/add", + "POST", + { + torrent_b64: msg.torrentB64 || "", + download_dir: cachedSettings.downloadDir || "", + }, + 15000 + ); case "pauseTorrent": - return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }); + return apiJson("/api/torrents/pause", "POST", { info_hash: msg.infoHash }, 10000); case "resumeTorrent": - return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }); + return apiJson("/api/torrents/resume", "POST", { info_hash: msg.infoHash }, 10000); case "removeTorrent": - return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash }); + return apiJson("/api/torrents/remove", "POST", { info_hash: msg.infoHash }, 10000); case "bootstrapDht": - return apiJson("/api/dht/bootstrap", "POST", { - b32: msg.b32 || "", - port: Number(msg.port) || 6881, - }); + return apiJson( + "/api/dht/bootstrap", + "POST", + { + b32: msg.b32 || "", + port: Number(msg.port) || 6881, + }, + 10000 + ); case "openManager": { const url = browser.runtime.getURL("manager.html"); const existing = await browser.tabs.query({ url }); diff --git a/extensions/firefox-i2p-torrent/content.js b/extensions/firefox-i2p-torrent/content.js index c005dfa..c318a85 100644 --- a/extensions/firefox-i2p-torrent/content.js +++ b/extensions/firefox-i2p-torrent/content.js @@ -1,6 +1,23 @@ "use strict"; (function () { + let interceptTorrents = true; + if (browser.storage && browser.storage.local) { + browser.storage.local + .get({ interceptTorrents: true }) + .then((res) => { + interceptTorrents = !!res.interceptTorrents; + }) + .catch(() => {}); + } + if (browser.storage && browser.storage.onChanged) { + browser.storage.onChanged.addListener((changes, area) => { + if (area === "local" && Object.prototype.hasOwnProperty.call(changes, "interceptTorrents")) { + interceptTorrents = !!changes.interceptTorrents.newValue; + } + }); + } + function showToast(text, isError) { let el = document.getElementById("moon-i2p-torrent-toast"); if (!el) { @@ -33,6 +50,9 @@ document.addEventListener( "click", async (ev) => { + if (!interceptTorrents) { + return; + } if (ev.button !== 0 || ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey) { return; } diff --git a/extensions/firefox-i2p-torrent/manifest.json b/extensions/firefox-i2p-torrent/manifest.json index b3297cc..d995dca 100644 --- a/extensions/firefox-i2p-torrent/manifest.json +++ b/extensions/firefox-i2p-torrent/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 2, "name": "Moon I2P Torrent & Proxy", - "version": "0.1.2", + "version": "0.1.3", "description": "Route .i2p browsing through moon-i2p and manage I2P BitTorrent + I2P DHT torrents from Firefox.", "icons": { "48": "icon.svg", diff --git a/extensions/firefox-i2p-torrent/ui.js b/extensions/firefox-i2p-torrent/ui.js index f147d59..ec199ac 100644 --- a/extensions/firefox-i2p-torrent/ui.js +++ b/extensions/firefox-i2p-torrent/ui.js @@ -40,88 +40,152 @@ function bytesToBase64(bytes) { return btoa(bin); } -let settingsPopulated = false; +const DEFAULT_SETTINGS = { + proxyEnabled: true, + proxyHost: "127.0.0.1", + proxyPort: 4444, + apiHost: "127.0.0.1", + apiPort: 4445, + downloadDir: "", + interceptTorrents: true, +}; -async function refresh() { - const st = await browser.runtime.sendMessage({ type: "getState" }); - const cfg = st.settings || {}; - const rs = st.routerStatus || {}; - const ns = st.nativeStatus || {}; - const dht = st.dht || {}; +let currentSettings = { ...DEFAULT_SETTINGS }; +const dirtyFields = new Set(); +let refreshInFlight = false; +let refreshPending = false; +let initialSettingsPromise = null; - $("proxy-enabled").checked = !!cfg.proxyEnabled; - $("proxy-addr").textContent = `${cfg.proxyHost || "127.0.0.1"}:${cfg.proxyPort || 4444}`; - - if (!settingsPopulated) { - settingsPopulated = true; - $("cfg-proxy-port").value = cfg.proxyPort || 4444; - $("cfg-api-port").value = cfg.apiPort || 4445; - $("cfg-dl-dir").value = cfg.downloadDir || ""; - $("cfg-intercept").checked = !!cfg.interceptTorrents; +function parsePort(raw, fallback) { + const s = String(raw ?? "").trim(); + if (!s) return fallback; + const n = Number(s); + if (Number.isInteger(n) && n >= 1 && n <= 65535) { + return n; } + return fallback; +} - const pill = $("router-pill"); - const startBtn = $("start-router-btn"); - const stopBtn = $("stop-router-btn"); - if (rs.ok) { - pill.textContent = rs.public_mode ? "Public Online" : "Online"; - pill.className = "pill online"; - startBtn.style.display = "none"; - stopBtn.style.display = ns.managed_running ? "" : "none"; - $("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`; - $("torrent-b32").textContent = rs.torrent_b32 || "--"; - const d = rs.dht || {}; - $("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`; - $("dht-node-id").textContent = d.node_id_hex || "--"; - $("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`; - } else { - pill.textContent = "Offline"; - pill.className = "pill offline"; - startBtn.style.display = ""; - stopBtn.style.display = "none"; - $("net-summary").textContent = "Router unreachable"; - $("torrent-b32").textContent = "--"; +function applySettingsToUi(cfg) { + currentSettings = { ...currentSettings, ...(cfg || {}) }; + $("proxy-enabled").checked = !!currentSettings.proxyEnabled; + $("proxy-addr").textContent = `${currentSettings.proxyHost || "127.0.0.1"}:${currentSettings.proxyPort || 4444}`; + if (!dirtyFields.has("proxyPort")) { + $("cfg-proxy-port").value = currentSettings.proxyPort || 4444; } - - const nodesEl = $("dht-nodes-list"); - if (nodesEl) { - const nodes = dht.nodes || []; - nodesEl.innerHTML = - nodes.length === 0 - ? "No DHT nodes yet. Bootstrap above or connect to a peer." - : nodes - .map( - (n) => - `
${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)
` - ) - .join(""); + if (!dirtyFields.has("apiPort")) { + $("cfg-api-port").value = currentSettings.apiPort || 4445; } + if (!dirtyFields.has("downloadDir")) { + $("cfg-dl-dir").value = currentSettings.downloadDir || ""; + } + if (!dirtyFields.has("interceptTorrents")) { + $("cfg-intercept").checked = !!currentSettings.interceptTorrents; + } +} - const list = st.torrents || []; - $("torrent-count").textContent = String(list.length); - const tEl = $("torrents-list"); - if (list.length === 0) { - tEl.innerHTML = "
No active torrents. Paste a magnet link or drop a .torrent file above.
"; - } else { - tEl.innerHTML = list - .map((t) => { - const pct = Number(t.progress_pct || 0); - const toggleLabel = t.paused ? "Resume" : "Pause"; - const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent"; - const infTxt = t.inflight_blocks > 0 ? ` (+${t.inflight_blocks} blks)` : ""; - const trackerHtml = t.last_tracker_status - ? `
Tracker: ${escapeHtml(t.last_tracker_status)}
` - : ""; - const peers = Array.isArray(t.peers) ? t.peers : []; - const peersHtml = peers.length - ? `
${peers +async function loadSettingsFast() { + let cfg = null; + try { + if (browser.storage && browser.storage.local) { + cfg = await browser.storage.local.get(DEFAULT_SETTINGS); + } else { + const res = await browser.runtime.sendMessage({ type: "getSettings" }); + cfg = res && res.settings ? res.settings : null; + } + } catch (_e) { + try { + const res = await browser.runtime.sendMessage({ type: "getSettings" }); + cfg = res && res.settings ? res.settings : null; + } catch (_e2) { + cfg = null; + } + } + if (cfg) { + applySettingsToUi(cfg); + } +} + +async function refresh(force = false) { + if (refreshInFlight) { + if (force) { + refreshPending = true; + } + return; + } + refreshInFlight = true; + try { + const st = await browser.runtime.sendMessage({ type: "getState" }); + if (!st) return; + const cfg = st.settings || {}; + const rs = st.routerStatus || {}; + const ns = st.nativeStatus || {}; + const dht = st.dht || {}; + + applySettingsToUi(cfg); + + const pill = $("router-pill"); + const startBtn = $("start-router-btn"); + const stopBtn = $("stop-router-btn"); + if (rs.ok) { + pill.textContent = rs.public_mode ? "Public Online" : "Online"; + pill.className = "pill online"; + startBtn.style.display = "none"; + stopBtn.style.display = ns.managed_running ? "" : "none"; + $("net-summary").textContent = `${rs.netdb_routers || 0} peers · ${rs.inbound_tunnels || 0}in/${rs.outbound_tunnels || 0}out`; + $("torrent-b32").textContent = rs.torrent_b32 || "--"; + const d = rs.dht || {}; + $("dht-summary").textContent = `${d.routing_table_nodes || 0} nodes (UDP-over-I2CP ${d.query_port || 6881}/${d.reply_port || 6882})`; + $("dht-node-id").textContent = d.node_id_hex || "--"; + $("dht-stats").textContent = `${d.queries_sent || 0} / ${d.responses_recv || 0} / ${d.peers_discovered || 0}`; + } else { + pill.textContent = "Offline"; + pill.className = "pill offline"; + startBtn.style.display = ""; + stopBtn.style.display = "none"; + $("net-summary").textContent = "Router unreachable"; + $("torrent-b32").textContent = "--"; + } + + const nodesEl = $("dht-nodes-list"); + if (nodesEl) { + const nodes = dht.nodes || []; + nodesEl.innerHTML = + nodes.length === 0 + ? "No DHT nodes yet. Bootstrap above or connect to a peer." + : nodes .map( - (p) => - `
peer ${escapeHtml(p.b32)}${p.client ? ` [${escapeHtml(p.client)}]` : ""} · st=${escapeHtml(String(p.state ?? ""))} ${p.choking ? "choked" : "unchoked"} · ${p.pieces || 0} pcs · inf=${p.in_flight || 0} · blks=${p.blocks_recv || 0}
` + (n) => + `
${escapeHtml(n.b32)}:${n.port} (${escapeHtml((n.node_id_hex || "").slice(0, 12))}...)
` ) - .join("")}
` - : ""; - return ` + .join(""); + } + + const list = st.torrents || []; + $("torrent-count").textContent = String(list.length); + const tEl = $("torrents-list"); + if (list.length === 0) { + tEl.innerHTML = "
No active torrents. Paste a magnet link or drop a .torrent file above.
"; + } else { + tEl.innerHTML = list + .map((t) => { + const pct = Number(t.progress_pct || 0); + const toggleLabel = t.paused ? "Resume" : "Pause"; + const toggleType = t.paused ? "resumeTorrent" : "pauseTorrent"; + const infTxt = t.inflight_blocks > 0 ? ` (+${t.inflight_blocks} blks)` : ""; + const trackerHtml = t.last_tracker_status + ? `
Tracker: ${escapeHtml(t.last_tracker_status)}
` + : ""; + const peers = Array.isArray(t.peers) ? t.peers : []; + const peersHtml = peers.length + ? `
${peers + .map( + (p) => + `
peer ${escapeHtml(p.b32)}${p.client ? ` [${escapeHtml(p.client)}]` : ""} · st=${escapeHtml(String(p.state ?? ""))} ${p.choking ? "choked" : "unchoked"} · ${p.pieces || 0} pcs · inf=${p.in_flight || 0} · blks=${p.blocks_recv || 0}
` + ) + .join("")}
` + : ""; + return `
${escapeHtml(t.name)} @@ -140,12 +204,45 @@ async function refresh() { ${t.error ? `
${escapeHtml(t.error)}
` : ""}
`; - }) - .join(""); + }) + .join(""); + } + } catch (_e) { + // Ignore transient runtime errors during refresh + } finally { + refreshInFlight = false; + if (refreshPending) { + refreshPending = false; + refresh(false); + } } } document.addEventListener("DOMContentLoaded", () => { + for (const [id, field] of [ + ["cfg-proxy-port", "proxyPort"], + ["cfg-api-port", "apiPort"], + ["cfg-dl-dir", "downloadDir"], + ["cfg-intercept", "interceptTorrents"], + ]) { + const el = $(id); + if (el) { + el.addEventListener("input", () => dirtyFields.add(field)); + el.addEventListener("change", () => dirtyFields.add(field)); + } + } + + if (browser.storage && browser.storage.onChanged) { + browser.storage.onChanged.addListener((changes, area) => { + if (area !== "local") return; + const patch = {}; + for (const [key, val] of Object.entries(changes)) { + patch[key] = val.newValue; + } + applySettingsToUi(patch); + }); + } + if ($("open-manager-btn")) { $("open-manager-btn").addEventListener("click", () => browser.runtime.sendMessage({ type: "openManager" }) @@ -157,7 +254,7 @@ document.addEventListener("DOMContentLoaded", () => { type: "saveSettings", settings: { proxyEnabled: e.target.checked }, }); - refresh(); + refresh(true); }); $("start-router-btn").addEventListener("click", async () => { @@ -168,13 +265,13 @@ document.addEventListener("DOMContentLoaded", () => { } else { setMsg(`Failed to start router: ${(res && res.error) || "run just extension"}`, true); } - setTimeout(refresh, 700); + setTimeout(() => refresh(true), 700); }); $("stop-router-btn").addEventListener("click", async () => { await browser.runtime.sendMessage({ type: "stopRouter" }); setMsg("Stopped router."); - setTimeout(refresh, 400); + setTimeout(() => refresh(true), 400); }); $("bootstrap-form").addEventListener("submit", async (e) => { @@ -184,7 +281,7 @@ document.addEventListener("DOMContentLoaded", () => { if (!b32) return; const res = await browser.runtime.sendMessage({ type: "bootstrapDht", b32, port }); setMsg(res && res.ok ? `Sent DHT ping to ${res.b32}:${res.port}` : `DHT error: ${res?.error || "failed"}`, !res?.ok); - refresh(); + refresh(true); }); $("magnet-form").addEventListener("submit", async (e) => { @@ -198,7 +295,7 @@ document.addEventListener("DOMContentLoaded", () => { } else { setMsg(`Magnet failed: ${res?.error || "router offline"}`, true); } - refresh(); + refresh(true); }); const dz = $("dropzone"); @@ -211,7 +308,7 @@ document.addEventListener("DOMContentLoaded", () => { torrentB64: bytesToBase64(buf), }); setMsg(res && res.ok ? `Added ${file.name} (${res.info_hash.slice(0, 12)}...)` : `Add failed: ${res?.error}`, !res?.ok); - refresh(); + refresh(true); }; dz.addEventListener("click", () => fileIn.click()); fileIn.addEventListener("change", () => handleFile(fileIn.files[0])); @@ -233,24 +330,41 @@ document.addEventListener("DOMContentLoaded", () => { type: btn.dataset.act, infoHash: btn.dataset.ih, }); - refresh(); + refresh(true); }); $("settings-form").addEventListener("submit", async (e) => { e.preventDefault(); - await browser.runtime.sendMessage({ - type: "saveSettings", - settings: { - proxyPort: Number($("cfg-proxy-port").value) || 4444, - apiPort: Number($("cfg-api-port").value) || 4445, - downloadDir: $("cfg-dl-dir").value.trim(), - interceptTorrents: $("cfg-intercept").checked, - }, - }); - setMsg("Settings saved."); - refresh(); + if (initialSettingsPromise) { + await initialSettingsPromise; + } + const nextSettings = { + proxyPort: dirtyFields.has("proxyPort") + ? parsePort($("cfg-proxy-port").value, currentSettings.proxyPort || 4444) + : (currentSettings.proxyPort || 4444), + apiPort: dirtyFields.has("apiPort") + ? parsePort($("cfg-api-port").value, currentSettings.apiPort || 4445) + : (currentSettings.apiPort || 4445), + downloadDir: dirtyFields.has("downloadDir") + ? $("cfg-dl-dir").value.trim() + : (currentSettings.downloadDir || ""), + interceptTorrents: $("cfg-intercept").checked, + }; + try { + const res = await browser.runtime.sendMessage({ + type: "saveSettings", + settings: nextSettings, + }); + dirtyFields.clear(); + applySettingsToUi((res && res.settings) || nextSettings); + setMsg("Settings saved."); + refresh(true); + } catch (err) { + setMsg(`Failed to save settings: ${err}`, true); + } }); - refresh(); - setInterval(refresh, 2000); + initialSettingsPromise = loadSettingsFast(); + refresh(false); + setInterval(() => refresh(false), 2000); }); diff --git a/ntcp2_net/net_stub.c b/ntcp2_net/net_stub.c index 2a8412c..314923e 100644 --- a/ntcp2_net/net_stub.c +++ b/ntcp2_net/net_stub.c @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -30,6 +31,10 @@ #define MSG_NOSIGNAL 0 #endif +#ifndef MSG_DONTWAIT +#define MSG_DONTWAIT 0 +#endif + static char g_net_last_error[256] = {0}; static void net_set_error(const char *msg) { @@ -329,7 +334,7 @@ int32_t moon_i2p_net_tcp_send( moonbit_bytes_t data, int32_t offset, int32_t len) { - ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL); + ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL | MSG_DONTWAIT); if (n < 0) { if (errno == EAGAIN || errno == EWOULDBLOCK) { return -2; @@ -340,6 +345,26 @@ int32_t moon_i2p_net_tcp_send( return (int32_t)n; } +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_set_peer_timeouts(int32_t fd, int32_t user_timeout_ms) { + (void)user_timeout_ms; + int keepalive = 1; + if (setsockopt((int)fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) < 0) { + net_set_error(strerror(errno)); + return -1; + } +#ifdef TCP_USER_TIMEOUT + if (user_timeout_ms > 0) { + unsigned int uto = (unsigned int)user_timeout_ms; + if (setsockopt((int)fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &uto, sizeof(uto)) < 0) { + net_set_error(strerror(errno)); + return -1; + } + } +#endif + return 0; +} + MOONBIT_FFI_EXPORT int32_t moon_i2p_net_tcp_poll_writable(int32_t fd, int32_t timeout_ms) { struct pollfd pfd; diff --git a/ntcp2_net/ntcp2_net_test.mbt b/ntcp2_net/ntcp2_net_test.mbt index be132b8..d6aaad2 100644 --- a/ntcp2_net/ntcp2_net_test.mbt +++ b/ntcp2_net/ntcp2_net_test.mbt @@ -55,3 +55,142 @@ test "extract_ntcp2_peer from signed RouterInfo" { assert_eq(peer.iv, iv) assert_eq(peer.router_hash, ri_id.hash().as_bytes()) } + +///| +test "TcpSocket::write_all times out instead of blocking on a full unread socket" { + let listener = @ntcp2_net.TcpListener::bind("127.0.0.1", 0) + let client = @ntcp2_net.TcpSocket::connect("127.0.0.1", listener.local_port()) + let server = match listener.accept(timeout_ms=2000) { + Some(s) => s + None => fail("expected accepted TCP socket") + } + let chunk = Bytes::make(65536, b'\xab') + let mut got_timeout = false + for _i = 0; _i < 512; _i = _i + 1 { + let timed_out = try { + client.write_all(chunk, timeout_ms=100) + false + } catch { + Timeout => true + _ => false + } + if timed_out { + got_timeout = true + break + } + } + assert_true(got_timeout) + client.close() + server.close() + listener.close() +} + +///| +test "PendingNtcp2Dial/Accept stay non-blocking and Ntcp2Conn::send_blocks_nb transfers frames" { + let alice_ed_seed = @ntcp2_net.random_bytes(32) + let alice_ed_pub = @crypto.ed25519_public_key(alice_ed_seed) + let alice_x_priv = @ntcp2_net.random_bytes(32) + let alice_static = @noise.KeyPair::from_private(alice_x_priv) + let alice_iv = @ntcp2_net.random_bytes(16) + let alice_id = @common.RouterIdentity::new_x25519_ed25519( + alice_static.public_key, + alice_ed_pub, + ) + + let bob_ed_seed = @ntcp2_net.random_bytes(32) + let bob_ed_pub = @crypto.ed25519_public_key(bob_ed_seed) + let bob_x_priv = @ntcp2_net.random_bytes(32) + let bob_static = @noise.KeyPair::from_private(bob_x_priv) + let bob_iv = @ntcp2_net.random_bytes(16) + let bob_id = @common.RouterIdentity::new_x25519_ed25519( + bob_static.public_key, + bob_ed_pub, + ) + + let listener = @ntcp2_net.TcpListener::bind("127.0.0.1", 0) + let listen_port = listener.local_port() + + let alice_ri : @common.RouterInfo = { + identity: alice_id, + published: @ntcp2_net.unix_time_ms(), + addresses: [ + @common.RouterAddress::new( + b'\x03', + "NTCP2", + @common.Mapping::from_entries([ + ("host", "127.0.0.1"), + ("i", @encoding.base64_encode(alice_iv)), + ("port", "1"), + ("s", @encoding.base64_encode(alice_static.public_key)), + ("v", "2"), + ]), + ), + ], + options: @common.Mapping::from_entries([("caps", "LR"), ("netId", "2")]), + signature: b"", + } + let signed_alice_ri = alice_ri.sign_ed25519(alice_ed_seed) + + let bob_peer : @ntcp2_net.Ntcp2PeerInfo = { + router_hash: bob_id.hash().as_bytes(), + static_key: bob_static.public_key, + iv: bob_iv, + host: "127.0.0.1", + port: listen_port, + } + let dial = @ntcp2_net.PendingNtcp2Dial::start( + bob_peer, alice_static, signed_alice_ri, + ) + let acc_sock = match listener.accept(timeout_ms=2000) { + Some(s) => s + None => fail("expected incoming NTCP2 TCP connection") + } + let acc = @ntcp2_net.PendingNtcp2Accept::start( + acc_sock, + bob_static, + bob_id.hash().as_bytes(), + bob_iv, + ) + + let mut alice_conn_opt : @ntcp2_net.Ntcp2Conn? = None + let mut bob_conn_opt : @ntcp2_net.Ntcp2Conn? = None + for _step = 0; _step < 100; _step = _step + 1 { + if alice_conn_opt is None { + alice_conn_opt = dial.step() + } + if bob_conn_opt is None { + bob_conn_opt = acc.step() + } + if alice_conn_opt is Some(_) && bob_conn_opt is Some(_) { + break + } + } + let alice_conn = match alice_conn_opt { + Some(c) => c + None => fail("PendingNtcp2Dial did not finish") + } + let bob_conn = match bob_conn_opt { + Some(c) => c + None => fail("PendingNtcp2Accept did not finish") + } + + alice_conn.send_blocks_nb([@ntcp2.Ntcp2Block::Padding(b"nb-ntcp2-ok")]) + let _ = alice_conn.flush_nonblocking() + let mut got_blocks : Array[@ntcp2.Ntcp2Block]? = None + for _i = 0; _i < 100; _i = _i + 1 { + if bob_conn.poll_readable(10) { + got_blocks = bob_conn.try_recv_blocks() + if got_blocks is Some(_) { + break + } + } + } + match got_blocks { + Some(blks) => assert_eq(blks, [@ntcp2.Ntcp2Block::Padding(b"nb-ntcp2-ok")]) + None => fail("expected NTCP2 non-blocking blocks on responder") + } + + alice_conn.close() + bob_conn.close() + listener.close() +} diff --git a/ntcp2_net/transport.mbt b/ntcp2_net/transport.mbt index 543b428..d1566a3 100644 --- a/ntcp2_net/transport.mbt +++ b/ntcp2_net/transport.mbt @@ -45,6 +45,12 @@ extern "C" fn c_tcp_check_connected(fd : Int32) -> Int32 = "moon_i2p_net_tcp_che ///| extern "C" fn c_tcp_set_nonblocking(fd : Int32, nonblocking : Int32) -> Int32 = "moon_i2p_net_tcp_set_nonblocking" +///| +extern "C" fn c_tcp_set_peer_timeouts( + fd : Int32, + user_timeout_ms : Int32, +) -> Int32 = "moon_i2p_net_tcp_set_peer_timeouts" + ///| #borrow(host) extern "C" fn c_tcp_listen( @@ -384,20 +390,32 @@ pub fn TcpSocket::poll_readable( pub fn TcpSocket::write_all( self : TcpSocket, data : Bytes, + timeout_ms~ : Int32 = 5000, ) -> Unit raise Ntcp2NetError { if self.fd < 0 { raise Closed } let total = data.length() + if total == 0 { + return + } + let budget = if timeout_ms > 0 { timeout_ms.to_uint64() } else { 1UL } + let deadline_ms = unix_time_ms() + budget let mut sent = 0 while sent < total { let n = c_tcp_send(self.fd, data, sent, total - sent) if n == -2 { - let rc = c_tcp_poll_writable(self.fd, 5000) + let now_ms = unix_time_ms() + if now_ms >= deadline_ms { + raise Timeout + } + let rem64 = deadline_ms - now_ms + let rem_ms = if rem64 > 5000UL { 5000 } else { rem64.to_int() } + let rc = c_tcp_poll_writable(self.fd, if rem_ms > 0 { rem_ms } else { 1 }) if rc < 0 { raise IoError("poll writable failed: \{last_os_error()}") } - if rc == 0 { + if rc == 0 && unix_time_ms() >= deadline_ms { raise Timeout } continue @@ -745,6 +763,10 @@ pub struct Ntcp2Conn { remote_router_info : @common.RouterInfo? priv frame_buf : Array[Byte] priv mut expected_frame_len : Int32 + priv send_queue : Array[Bytes] + priv mut send_head_off : Int32 + priv mut send_queued_bytes : Int32 + priv mut send_blocked_since_ms : UInt64 } ///| @@ -759,6 +781,10 @@ fn make_ntcp2_conn( remote_router_info, frame_buf: [], expected_frame_len: -1, + send_queue: [], + send_head_off: 0, + send_queued_bytes: 0, + send_blocked_since_ms: 0UL, } } @@ -877,6 +903,7 @@ pub fn PendingNtcp2Dial::start( "connect_nb(\{peer.host}:\{peer.port}) failed: \{last_os_error()}", ) } + let _ = c_tcp_set_peer_timeouts(fd, 15000) let sock : TcpSocket = { fd, buf: FixedArray::make(4096, b'\x00'), @@ -933,8 +960,7 @@ pub fn PendingNtcp2Dial::step( self.sock.close() raise IoError("non-blocking connect failed: \{msg}") } - let _ = c_tcp_set_nonblocking(self.sock.fd, 0) - self.sock.write_all(self.m1_bytes) catch { + self.sock.write_all(self.m1_bytes, timeout_ms=250) catch { e => { self.sock.close() raise e @@ -1002,7 +1028,7 @@ pub fn PendingNtcp2Dial::step( raise Protocol(e) } } - self.sock.write_all(msg3) catch { + self.sock.write_all(msg3, timeout_ms=250) catch { e => { self.sock.close() raise e @@ -1068,6 +1094,8 @@ pub fn PendingNtcp2Accept::start( } } hs.set_ephemeral(ephem) + let _ = c_tcp_set_nonblocking(sock.fd, 1) + let _ = c_tcp_set_peer_timeouts(sock.fd, 15000) { sock, hs, @@ -1182,7 +1210,7 @@ pub fn PendingNtcp2Accept::step( raise Protocol(e) } } - self.sock.write_all(msg2) catch { + self.sock.write_all(msg2, timeout_ms=250) catch { e => { self.sock.close() raise e @@ -1416,12 +1444,113 @@ pub fn Ntcp2Conn::try_recv_blocks( Some(blocks) } +///| +/// Flushes queued outbound NTCP2 frames without blocking. Returns `true` if any bytes were written. +/// Raises `Timeout` if outbound socket stays un-writable with queued data for >10s. +pub fn Ntcp2Conn::flush_nonblocking( + self : Ntcp2Conn, +) -> Bool raise Ntcp2NetError { + if self.send_queue.length() == 0 { + self.send_head_off = 0 + self.send_queued_bytes = 0 + self.send_blocked_since_ms = 0UL + return false + } + if self.socket.fd < 0 { + raise Closed + } + let mut wrote_any = false + while self.send_queue.length() > 0 { + let head = self.send_queue[0] + let rem = head.length() - self.send_head_off + if rem <= 0 { + let _ = self.send_queue.remove(0) + self.send_head_off = 0 + continue + } + let n = c_tcp_send(self.socket.fd, head, self.send_head_off, rem) + if n == -2 { + break + } + if n < 0 { + raise IoError("non-blocking send failed: \{last_os_error()}") + } + if n == 0 { + raise Closed + } + wrote_any = true + self.send_head_off += n + self.send_queued_bytes -= n + if self.send_head_off >= head.length() { + let _ = self.send_queue.remove(0) + self.send_head_off = 0 + } + } + let now_ms = unix_time_ms() + if self.send_queue.length() == 0 { + self.send_blocked_since_ms = 0UL + } else if wrote_any { + self.send_blocked_since_ms = now_ms + } else if self.send_blocked_since_ms == 0UL { + self.send_blocked_since_ms = now_ms + } else if now_ms > self.send_blocked_since_ms + 10000UL { + raise Timeout + } + wrote_any +} + +///| +/// Encrypts and queues a data-phase frame for non-blocking transmission. +pub fn Ntcp2Conn::send_blocks_nb( + self : Ntcp2Conn, + blocks : Array[@ntcp2.Ntcp2Block], +) -> Unit raise Ntcp2NetError { + if self.send_queued_bytes > 262144 { + raise IoError("NTCP2 outbound send queue full") + } + let frame = self.session.encrypt_frame(blocks) catch { + e => raise Protocol(e) + } + self.send_queue.push(frame) + self.send_queued_bytes += frame.length() + let _ = self.flush_nonblocking() +} + +///| +/// Encrypts and queues a single I2NP message for non-blocking NTCP2 transmission. +pub fn Ntcp2Conn::send_i2np_nb( + self : Ntcp2Conn, + msg_id : UInt32, + expiration_sec : UInt32, + payload : @i2np.I2npPayload, +) -> Unit raise Ntcp2NetError { + let blk = @ntcp2.i2np_block(msg_id, expiration_sec, payload) catch { + e => raise Protocol(e) + } + self.send_blocks_nb([blk]) +} + ///| /// Encrypts and sends a data-phase frame containing `blocks`. pub fn Ntcp2Conn::send_blocks( self : Ntcp2Conn, blocks : Array[@ntcp2.Ntcp2Block], ) -> Unit raise Ntcp2NetError { + if self.send_queue.length() > 0 { + let head = self.send_queue[0] + if self.send_head_off > 0 && self.send_head_off < head.length() { + self.socket.write_all(head[self.send_head_off:].to_owned()) + } else if self.send_head_off == 0 { + self.socket.write_all(head) + } + let _ = self.send_queue.remove(0) + self.send_head_off = 0 + while self.send_queue.length() > 0 { + self.socket.write_all(self.send_queue.remove(0)) + } + self.send_queued_bytes = 0 + self.send_blocked_since_ms = 0UL + } let frame = self.session.encrypt_frame(blocks) catch { e => raise Protocol(e) } diff --git a/ratchet/ecies.mbt b/ratchet/ecies.mbt index 83ec3a6..2e1890f 100644 --- a/ratchet/ecies.mbt +++ b/ratchet/ecies.mbt @@ -296,12 +296,16 @@ pub struct RatchetPeerSession { mut local_next_pub : Bytes? mut remote_next_pub : Bytes? mut last_used_sec : UInt32 + mut send_enabled : Bool + mut confirmed : Bool + mut sent_es : Bool + mut last_recv_sec : UInt32 } ///| fn RatchetPeerSession::refill_recv_window( self : RatchetPeerSession, - target_size~ : Int32 = 32, + target_size~ : Int32 = 64, ) -> Unit raise RatchetError { while self.recv_window.length() < target_size { let (n, tag, key) = self.recv_tagset.next_entry() @@ -435,6 +439,10 @@ pub fn encrypt_new_session_reply( local_next_pub: None, remote_next_pub: None, last_used_sec: 0U, + send_enabled: true, + confirmed: true, + sent_es: false, + last_recv_sec: 0U, } sess.refill_recv_window() (w.to_bytes(), sess) @@ -508,6 +516,10 @@ pub fn decrypt_new_session_reply( local_next_pub: None, remote_next_pub: None, last_used_sec: 0U, + send_enabled: true, + confirmed: false, + sent_es: false, + last_recv_sec: 0U, } sess.refill_recv_window() (blocks, sess) @@ -632,19 +644,123 @@ pub fn RatchetSessionManager::new( { local_static, sessions: [], outbound_pending: [], inbound_pending: [], } } +///| +fn is_ratchet_session_expired( + sess : RatchetPeerSession, + now_sec : UInt32, +) -> Bool { + if now_sec == 0U || sess.last_used_sec == 0U { + return false + } + if now_sec > sess.last_used_sec + 300U { + return true + } + if !sess.confirmed && now_sec > sess.last_used_sec + 45U { + return true + } + false +} + ///| fn RatchetSessionManager::find_session( self : RatchetSessionManager, remote_static_pub : Bytes, ) -> Int32 { - for i = 0; i < self.sessions.length(); i = i + 1 { - if @crypto.ct_eq(self.sessions[i].remote_static_pub, remote_static_pub) { + let mut i = self.sessions.length() - 1 + while i >= 0 { + let sess = self.sessions[i] + if sess.send_enabled && + @crypto.ct_eq(sess.remote_static_pub, remote_static_pub) { return i } + i -= 1 } -1 } +///| +pub fn RatchetSessionManager::has_active_session( + self : RatchetSessionManager, + remote_static_pub : Bytes, + now_sec~ : UInt32 = 0U, +) -> Bool { + let mut i = self.sessions.length() - 1 + while i >= 0 { + let sess = self.sessions[i] + if sess.send_enabled && + @crypto.ct_eq(sess.remote_static_pub, remote_static_pub) && + !is_ratchet_session_expired(sess, now_sec) { + return true + } + i -= 1 + } + false +} + +///| +pub fn RatchetSessionManager::last_recv_sec( + self : RatchetSessionManager, + remote_static_pub : Bytes, +) -> UInt32 { + let mut best = 0U + for sess in self.sessions { + if @crypto.ct_eq(sess.remote_static_pub, remote_static_pub) && + sess.last_recv_sec > best { + best = sess.last_recv_sec + } + } + best +} + +///| +/// Marks established outbound send state stale for `remote_static_pub` so the next +/// send initiates a fresh Bound `NewSession`, while preserving existing receive windows +/// and pending `NSR` tags so in-flight peer replies can still decrypt. +pub fn RatchetSessionManager::mark_send_stale( + self : RatchetSessionManager, + remote_static_pub : Bytes, +) -> Unit { + for sess in self.sessions { + if @crypto.ct_eq(sess.remote_static_pub, remote_static_pub) { + sess.send_enabled = false + } + } +} + +///| +fn RatchetSessionManager::cap_peer_sessions( + self : RatchetSessionManager, + remote_static_pub : Bytes, + max_per_peer : Int32, +) -> Unit { + while true { + let mut count = 0 + let mut oldest_stale = -1 + let mut oldest_any = -1 + for i = 0; i < self.sessions.length(); i = i + 1 { + let s = self.sessions[i] + if @crypto.ct_eq(s.remote_static_pub, remote_static_pub) { + count += 1 + if oldest_any < 0 { + oldest_any = i + } + if !s.send_enabled && oldest_stale < 0 { + oldest_stale = i + } + } + } + if count <= max_per_peer { + break + } + let victim = if oldest_stale >= 0 { oldest_stale } else { oldest_any } + if victim >= 0 { + let _ = self.sessions.remove(victim) + } else { + break + } + } +} + ///| /// Drops any established or pending outbound ratchet state for `remote_static_pub` /// so subsequent sends start a fresh Bound `NewSession` handshake. @@ -744,15 +860,23 @@ pub fn RatchetSessionManager::encrypt_to_peer( now_sec : UInt32, next_rand_32 : () -> Bytes, ) -> Bytes raise RatchetError { + let mut ei = 0 + while ei < self.sessions.length() { + let s = self.sessions[ei] + if @crypto.ct_eq(s.remote_static_pub, remote_static_pub) && + is_ratchet_session_expired(s, now_sec) { + let _ = self.sessions.remove(ei) + } else { + ei += 1 + } + } let sidx = self.find_session(remote_static_pub) if sidx >= 0 { let sess = self.sessions[sidx] - if sess.last_used_sec != 0U && now_sec > sess.last_used_sec + 300U { - let _ = self.sessions.remove(sidx) - } else { - sess.last_used_sec = now_sec - return sess.encrypt_existing(blocks) - } + sess.last_used_sec = now_sec + sess.sent_es = true + sess.confirmed = true + return sess.encrypt_existing(blocks) } // Check if we owe this peer an NSR for i = 0; i < self.inbound_pending.length(); i = i + 1 { @@ -762,7 +886,11 @@ pub fn RatchetSessionManager::encrypt_to_peer( let ephem_b = generate_elligator_keypair(next_rand_32) let (wire, sess) = encrypt_new_session_reply(p, ephem_b, blocks) sess.last_used_sec = now_sec + sess.last_recv_sec = now_sec + sess.confirmed = true + sess.send_enabled = true self.sessions.push(sess) + self.cap_peer_sessions(remote_static_pub, 4) return wire } } @@ -789,10 +917,10 @@ pub fn RatchetSessionManager::encrypt_to_peer( ) match pending_opt { Some(p) => - // Pre-register first 4 NSR tags so any reply matches - for _k = 0; _k < 4; _k = _k + 1 { + // Pre-register first 6 NSR tags so any reply (or multi-NSR) matches + for _k = 0; _k < 6; _k = _k + 1 { let (_n, tag, _k32) = p.nsr_tagset.next_entry() - while self.outbound_pending.length() >= 64 { + while self.outbound_pending.length() >= 128 { let _ = self.outbound_pending.remove(0) } self.outbound_pending.push((tag, p)) @@ -808,19 +936,33 @@ pub fn RatchetSessionManager::encrypt_to_peer( pub fn RatchetSessionManager::decrypt_incoming( self : RatchetSessionManager, garlic_data : Bytes, + now_sec~ : UInt32 = 0U, ) -> (Bytes?, Array[RatchetBlock]) raise RatchetError { if garlic_data.length() >= 24 { let tag_8 = r_slice(garlic_data, 0, 8) let ct = r_slice(garlic_data, 8, garlic_data.length() - 8) - // 1. Existing Session lookup - for sess in self.sessions { + // 1. Existing Session lookup (newest first) + let mut si = self.sessions.length() - 1 + while si >= 0 { + let sess = self.sessions[si] match sess.try_decrypt_es(tag_8, ct) { Some(blocks) => { self.process_next_keys(sess, blocks) + sess.confirmed = true + sess.send_enabled = true + if now_sec > 0U { + sess.last_used_sec = now_sec + sess.last_recv_sec = now_sec + } + if si != self.sessions.length() - 1 { + let _ = self.sessions.remove(si) + self.sessions.push(sess) + } return (Some(sess.remote_static_pub), blocks) } None => () } + si -= 1 } // 2. New Session Reply lookup for i = 0; i < self.outbound_pending.length(); i = i + 1 { @@ -831,21 +973,21 @@ pub fn RatchetSessionManager::decrypt_incoming( p, garlic_data, ) - // Remove all pending entries sharing this PendingNewSession - let mut j = 0 - while j < self.outbound_pending.length() { - if @crypto.ct_eq(self.outbound_pending[j].1.h, p.h) { - let _ = self.outbound_pending.remove(j) - } else { - j += 1 + let _ = self.outbound_pending.remove(i) + sess.last_used_sec = now_sec + sess.last_recv_sec = now_sec + let mut already_has_active_es = false + for s in self.sessions { + if s.send_enabled && + s.sent_es && + @crypto.ct_eq(s.remote_static_pub, sess.remote_static_pub) { + already_has_active_es = true + break } } - let existing_idx = self.find_session(sess.remote_static_pub) - if existing_idx >= 0 { - self.sessions[existing_idx] = sess - } else { - self.sessions.push(sess) - } + sess.send_enabled = !already_has_active_es + self.sessions.push(sess) + self.cap_peer_sessions(sess.remote_static_pub, 4) return (Some(sess.remote_static_pub), blocks) } } diff --git a/ratchet/pkg.generated.mbti b/ratchet/pkg.generated.mbti index a83c769..df6245a 100644 --- a/ratchet/pkg.generated.mbti +++ b/ratchet/pkg.generated.mbti @@ -109,6 +109,10 @@ pub struct RatchetPeerSession { mut local_next_pub : Bytes? mut remote_next_pub : Bytes? mut last_used_sec : UInt32 + mut send_enabled : Bool + mut confirmed : Bool + mut sent_es : Bool + mut last_recv_sec : UInt32 } pub fn RatchetPeerSession::apply_dh_ratchet(Self, Bytes, Bytes, for_send~ : Bool) -> Unit raise RatchetError pub fn RatchetPeerSession::encrypt_existing(Self, Array[RatchetBlock]) -> Bytes raise RatchetError @@ -120,9 +124,12 @@ pub struct RatchetSessionManager { inbound_pending : Array[PendingNewSession] } pub fn RatchetSessionManager::create_next_key_block(Self, Bytes, () -> Bytes) -> RatchetBlock? raise RatchetError -pub fn RatchetSessionManager::decrypt_incoming(Self, Bytes) -> (Bytes?, Array[RatchetBlock]) raise RatchetError +pub fn RatchetSessionManager::decrypt_incoming(Self, Bytes, now_sec? : UInt32) -> (Bytes?, Array[RatchetBlock]) raise RatchetError pub fn RatchetSessionManager::drop_session(Self, Bytes) -> Unit pub fn RatchetSessionManager::encrypt_to_peer(Self, Bytes, Array[RatchetBlock], UInt32, () -> Bytes) -> Bytes raise RatchetError +pub fn RatchetSessionManager::has_active_session(Self, Bytes, now_sec? : UInt32) -> Bool +pub fn RatchetSessionManager::last_recv_sec(Self, Bytes) -> UInt32 +pub fn RatchetSessionManager::mark_send_stale(Self, Bytes) -> Unit pub fn RatchetSessionManager::new(@noise.KeyPair) -> Self pub struct TagSet { diff --git a/ratchet/ratchet_test.mbt b/ratchet/ratchet_test.mbt index 9165c34..1608eff 100644 --- a/ratchet/ratchet_test.mbt +++ b/ratchet/ratchet_test.mbt @@ -298,3 +298,196 @@ test "Proposal 144 ECIES Ratchet idle session expiry (>300s) and drop_session re assert_eq(from6, Some(alice_s.public_key)) assert_eq(dec6.length(), 2) } + +///| +test "Proposal 144 multi-NSR replies, mark_send_stale preservation, and unconfirmed expiry" { + let alice_s = @noise.KeyPair::from_private(@crypto.sha256(b"alice-multi-nsr")) + let bob_s = @noise.KeyPair::from_private(@crypto.sha256(b"bob-multi-nsr")) + let rand_a = det_rand_gen(b'\x31') + let rand_b = det_rand_gen(b'\x71') + + // 1. Multi-NSR: two NSR replies (tag 0 + tag 1) to one Bound NS both decrypt cleanly + // and do not clobber an already-confirmed ES session for sending/receiving. + let alice_mgr = @ratchet.RatchetSessionManager::new(alice_s) + let c_ns = @ratchet.garlic_clove_block( + Local, + 10U, + 1700000900U, + Data(data=b"ns-init"), + ) + let ns_wire = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c_ns], + 1700000100U, + rand_a, + ) + let (_, pending_opt) = @ratchet.decrypt_new_session(bob_s, ns_wire) + let pending = match pending_opt { + Some(p) => p + None => fail("expected bound PendingNewSession") + } + let c_nsr0 = @ratchet.garlic_clove_block( + Local, + 11U, + 1700000900U, + Data(data=b"nsr-0"), + ) + let c_nsr1 = @ratchet.garlic_clove_block( + Local, + 12U, + 1700000900U, + Data(data=b"nsr-1"), + ) + let (nsr0, bob_sess0) = @ratchet.encrypt_new_session_reply( + pending, + @ratchet.generate_elligator_keypair(rand_b), + [c_nsr0], + ) + let (nsr1, bob_sess1) = @ratchet.encrypt_new_session_reply( + pending, + @ratchet.generate_elligator_keypair(rand_b), + [c_nsr1], + ) + let (from0, dec0) = alice_mgr.decrypt_incoming(nsr0, now_sec=1700000101U) + assert_eq(from0, Some(bob_s.public_key)) + assert_eq(dec0, [c_nsr0]) + + // Confirm session 0 by sending ES from Alice -> Bob and receiving ES from Bob -> Alice + let c_es_ab = @ratchet.garlic_clove_block( + Local, + 13U, + 1700000900U, + Data(data=b"es-confirm"), + ) + let es_ab = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c_es_ab], + 1700000102U, + rand_a, + ) + assert_true(es_ab.length() < 96) + let c_es_b0 = @ratchet.garlic_clove_block( + Local, + 14U, + 1700000900U, + Data(data=b"es-bob0"), + ) + let es_b0 = bob_sess0.encrypt_existing([c_es_b0]) + let (_, dec_b0) = alice_mgr.decrypt_incoming(es_b0, now_sec=1700000103U) + assert_eq(dec_b0, [c_es_b0]) + assert_eq(alice_mgr.last_recv_sec(bob_s.public_key), 1700000103U) + + // Second NSR (tag 1) still decrypts cleanly without discarding session 0's recv window + let (from1, dec1) = alice_mgr.decrypt_incoming(nsr1, now_sec=1700000104U) + assert_eq(from1, Some(bob_s.public_key)) + assert_eq(dec1, [c_nsr1]) + assert_true( + alice_mgr.has_active_session(bob_s.public_key, now_sec=1700000104U), + ) + let es_after_nsr1 = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c_es_ab], + 1700000104U, + rand_a, + ) + assert_true(es_after_nsr1.length() < 96) + + // Session 0 ES continues decrypting on Alice, and Session 1 can also receive ES + let c_es_b0_2 = @ratchet.garlic_clove_block( + Local, + 15U, + 1700000900U, + Data(data=b"es-bob0-still-alive"), + ) + let (_, dec_b0_2) = alice_mgr.decrypt_incoming( + bob_sess0.encrypt_existing([c_es_b0_2]), + now_sec=1700000105U, + ) + assert_eq(dec_b0_2, [c_es_b0_2]) + let c_es_b1 = @ratchet.garlic_clove_block( + Local, + 16U, + 1700000900U, + Data(data=b"es-bob1"), + ) + let (_, dec_b1) = alice_mgr.decrypt_incoming( + bob_sess1.encrypt_existing([c_es_b1]), + now_sec=1700000106U, + ) + assert_eq(dec_b1, [c_es_b1]) + + // 2. mark_send_stale forces a fresh Bound NS while keeping old recv_window & re-enabling on ES recv + alice_mgr.mark_send_stale(bob_s.public_key) + assert_true( + !alice_mgr.has_active_session(bob_s.public_key, now_sec=1700000107U), + ) + let c_re_ns = @ratchet.garlic_clove_block( + Local, + 17U, + 1700000900U, + Data(data=b"re-ns-after-stale"), + ) + let re_ns_wire = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c_re_ns], + 1700000107U, + rand_a, + ) + assert_true(re_ns_wire.length() >= 96) + let bob_fresh = @ratchet.RatchetSessionManager::new(bob_s) + let (f_re, dec_re) = bob_fresh.decrypt_incoming( + re_ns_wire, + now_sec=1700000107U, + ) + assert_eq(f_re, Some(alice_s.public_key)) + assert_eq(dec_re.length(), 2) + + // Receiving ES on a send-stale session still succeeds and re-enables it + let c_stale_rx = @ratchet.garlic_clove_block( + Local, + 18U, + 1700000900U, + Data(data=b"bob1-re-enable"), + ) + let (_, dec_stale_rx) = alice_mgr.decrypt_incoming( + bob_sess1.encrypt_existing([c_stale_rx]), + now_sec=1700000108U, + ) + assert_eq(dec_stale_rx, [c_stale_rx]) + assert_true( + alice_mgr.has_active_session(bob_s.public_key, now_sec=1700000108U), + ) + + // mark_send_stale also preserves in-flight outbound_pending NSR tags + let a2 = @ratchet.RatchetSessionManager::new(alice_s) + let b2 = @ratchet.RatchetSessionManager::new(bob_s) + let w_a2 = a2.encrypt_to_peer(bob_s.public_key, [c_ns], 1700000200U, rand_a) + let _ = b2.decrypt_incoming(w_a2, now_sec=1700000200U) + a2.mark_send_stale(bob_s.public_key) + let w_b2 = b2.encrypt_to_peer( + alice_s.public_key, + [c_nsr0], + 1700000201U, + rand_b, + ) + let (f_b2, dec_b2) = a2.decrypt_incoming(w_b2, now_sec=1700000201U) + assert_eq(f_b2, Some(bob_s.public_key)) + assert_eq(dec_b2, [c_nsr0]) + + // 3. Unconfirmed NSR expiry (>45s) forces a fresh Bound NS when no ES was sent/received + assert_true(a2.has_active_session(bob_s.public_key, now_sec=1700000240U)) + assert_true(!a2.has_active_session(bob_s.public_key, now_sec=1700000247U)) + let w_expired_ns = a2.encrypt_to_peer( + bob_s.public_key, + [c_re_ns], + 1700000247U, + rand_a, + ) + let bob_clean = @ratchet.RatchetSessionManager::new(bob_s) + let (f_exp, dec_exp) = bob_clean.decrypt_incoming( + w_expired_ns, + now_sec=1700000247U, + ) + assert_eq(f_exp, Some(alice_s.public_key)) + assert_eq(dec_exp.length(), 2) +} diff --git a/router/http_proxy.mbt b/router/http_proxy.mbt index 1f96e6c..d0ecae8 100644 --- a/router/http_proxy.mbt +++ b/router/http_proxy.mbt @@ -463,10 +463,10 @@ fn send_http_proxy_error( let body = "\{refresh_meta}\{status} \{safe_reason}

\{status} \{safe_reason}

\{safe_detail}


moon-i2p HTTP Proxy\n" let body_bytes = @encoding.string_to_utf8_bytes(body) let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\n\{refresh_hdr}Connection: close\r\n\r\n" - let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch { + let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr), timeout_ms=500) catch { _ => return } - let _ = sock.write_all(body_bytes) catch { _ => () } + let _ = sock.write_all(body_bytes, timeout_ms=500) catch { _ => () } } ///| @@ -475,7 +475,9 @@ fn send_http_proxy_redirect( location : String, ) -> Unit { let hdr = "HTTP/1.1 302 Found\r\nLocation: \{location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" - let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch { _ => () } + let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr), timeout_ms=500) catch { + _ => () + } } ///| diff --git a/router/ntcp2_peers.mbt b/router/ntcp2_peers.mbt index c436f2b..3b20d83 100644 --- a/router/ntcp2_peers.mbt +++ b/router/ntcp2_peers.mbt @@ -166,7 +166,7 @@ fn Router::send_i2np_to_peer( while idx >= 0 { if self.peers[idx].hash == target_hash { let ok = try { - self.peers[idx].conn.send_i2np(mid, exp_sec, payload) + self.peers[idx].conn.send_i2np_nb(mid, exp_sec, payload) true } catch { _ => false @@ -177,6 +177,9 @@ fn Router::send_i2np_to_peer( } self.peers[idx].conn.close() let _ = self.peers.remove(idx) + if self.public_mode { + self.mark_peer_failed(target_hash, 60000UL) + } } idx -= 1 } @@ -246,7 +249,7 @@ fn Router::flush_pending_sends_for( let ps = self.pending_sends[i] if ps.target_hash == target_hash { let ok = try { - peer.conn.send_i2np(ps.msg_id, ps.expiration_sec, ps.payload) + peer.conn.send_i2np_nb(ps.msg_id, ps.expiration_sec, ps.payload) true } catch { _ => false @@ -456,33 +459,53 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool { ) } - // 5. Non-blocking read & dispatch on all active NTCP2 peer sessions + // 5. Flush non-blocking outbound frames & read incoming frames on all active NTCP2 peers let mut pi = 0 while pi < self.peers.length() { let peer = self.peers[pi] let mut alive = true - for _frame = 0; _frame < 32; _frame = _frame + 1 { - let recv_opt = peer.conn.try_recv_blocks() catch { - _ => { - alive = false - None - } + let flushed = peer.conn.flush_nonblocking() catch { + _ => { + alive = false + false } - match recv_opt { - Some(blocks) => { - did_work = true - peer.last_active_ms = now_ms - if self.handle_peer_blocks(peer.hash, blocks) { + } + if flushed { + did_work = true + peer.last_active_ms = now_ms + } + if alive { + for _frame = 0; _frame < 32; _frame = _frame + 1 { + let recv_opt = peer.conn.try_recv_blocks() catch { + _ => { alive = false - break + None } } - None => break + match recv_opt { + Some(blocks) => { + did_work = true + peer.last_active_ms = now_ms + if self.handle_peer_blocks(peer.hash, blocks) { + alive = false + break + } + } + None => break + } } } if !alive || now_ms > peer.last_active_ms + 180000UL { peer.conn.close() let _ = self.peers.remove(pi) + if self.public_mode && !alive { + self.mark_peer_failed(peer.hash, 60000UL) + if self.debug { + println( + "[debug] NTCP2 peer closed/stalled: \{peer.hash.to_b32_address()}", + ) + } + } } else { pi += 1 } diff --git a/router/public_bootstrap.mbt b/router/public_bootstrap.mbt index 6fabcf1..8867d61 100644 --- a/router/public_bootstrap.mbt +++ b/router/public_bootstrap.mbt @@ -247,7 +247,7 @@ fn Router::step_public_bootstrap(self : Router) -> Unit { if is_peer_in_list(p.hash, tunnel_peers) && now_ms > p.last_active_ms + 90000UL { let ok = try { - p.conn.send_blocks([@ntcp2.Ntcp2Block::Padding(b"\x00\x00\x00\x00")]) + p.conn.send_blocks_nb([@ntcp2.Ntcp2Block::Padding(b"\x00\x00\x00\x00")]) true } catch { _ => false @@ -258,6 +258,9 @@ fn Router::step_public_bootstrap(self : Router) -> Unit { } else { p.conn.close() let _ = self.peers.remove(pi) + if self.public_mode { + self.mark_peer_failed(p.hash, 60000UL) + } } } else { pi += 1 diff --git a/router/router.mbt b/router/router.mbt index 21024b4..5bf42aa 100644 --- a/router/router.mbt +++ b/router/router.mbt @@ -68,6 +68,7 @@ pub struct Router { priv aliases : Array[(String, String)] // hostname -> pub_b64 priv b32_aliases : Array[(String, String)] // hostname -> lowercase <52>.b32.i2p priv failed_peers : Array[(@common.Hash, UInt64)] // (router_hash, retry_after_ms) + priv ratchet_resets : Array[(@common.Hash, UInt64)] // (peer_hash, last_reset_ms) priv mut http_proxy_listener : @ntcp2_net.TcpListener? priv http_proxy_conns : Array[HttpProxyConn] priv mut http_proxy_session_id : String? @@ -263,6 +264,7 @@ pub fn Router::start( aliases: [], b32_aliases: [], failed_peers: [], + ratchet_resets: [], http_proxy_listener: None, http_proxy_conns: [], http_proxy_session_id: None, diff --git a/router/router_test.mbt b/router/router_test.mbt index 3dc1263..253182f 100644 --- a/router/router_test.mbt +++ b/router/router_test.mbt @@ -721,3 +721,134 @@ test "2-router I2P DHT + BEP 9 Magnet + Streaming torrent download and HTTP API ) assert_true(nodes_json.contains(router_a.torrent_b32_address())) } + +///| +test "POST /api/torrents/add accepts standard, URL-safe, and rejects invalid Base64" { + let dl_dir = "/tmp/moon_i2p_bt_b64_test" + @ntcp2_net.mkdir_p(dl_dir) + let r = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer r.close() + let api_port = r.start_torrent_api( + host="127.0.0.1", + port=0, + download_dir=dl_dir, + ) + let rs = [r] + + let make_b64 = fn(tbytes : Bytes, to_std : Bool, strip_pad : Bool) -> String { + let i2p_b64 = @encoding.base64_encode(tbytes) + let sb = StringBuilder() + for ch in i2p_b64 { + if strip_pad && ch == '=' { + continue + } + if to_std { + match ch { + '-' => sb.write_char('+') + '~' => sb.write_char('/') + _ => sb.write_char(ch) + } + } else { + match ch { + '~' => sb.write_char('_') + _ => sb.write_char(ch) + } + } + } + sb.to_string() + } + + let t1 = @bittorrent.bencode_encode( + BDict([ + (b"comment", BBytes(b"\xfb\xff\xbf\xfb\xff")), + ( + b"info", + BDict([ + (b"length", BInt(16L)), + (b"name", BBytes(b"std-b64.bin")), + (b"piece length", BInt(16384L)), + (b"pieces", BBytes(Bytes::make(20, b'\xfb'))), + ]), + ), + ]), + ) + let ih1 = @encoding.hex_encode(@bittorrent.parse_torrent(t1).info_hash) + let std_b64 = make_b64(t1, true, false) + assert_true(std_b64.contains("+")) + assert_true(std_b64.contains("/")) + let resp1 = test_http_api_request( + api_port, + rs, + "POST", + "/api/torrents/add", + "127.0.0.1:\{api_port}", + [("Content-Type", "application/json"), ("X-Moon-I2P", "1")], + "{\"torrent_b64\":\"\{std_b64}\"}", + ) + assert_true(resp1.contains("200 OK")) + assert_true(resp1.contains(ih1)) + + // Unpadded URL-safe Base64 (ensure length % 3 != 0 so stripping '=' exercises padding recovery) + let mut t2 = @bittorrent.bencode_encode( + BDict([ + (b"comment", BBytes(b"\xfb\xff\xbf\xfb\xff")), + ( + b"info", + BDict([ + (b"length", BInt(16L)), + (b"name", BBytes(b"url-b64-a.bin")), + (b"piece length", BInt(16384L)), + (b"pieces", BBytes(Bytes::make(20, b'\xff'))), + ]), + ), + ]), + ) + if t2.length() % 3 == 0 { + t2 = @bittorrent.bencode_encode( + BDict([ + (b"comment", BBytes(b"\xfb\xff\xbf\xfb\xff")), + ( + b"info", + BDict([ + (b"length", BInt(16L)), + (b"name", BBytes(b"url-b64-ab.bin")), + (b"piece length", BInt(16384L)), + (b"pieces", BBytes(Bytes::make(20, b'\xff'))), + ]), + ), + ]), + ) + } + let ih2 = @encoding.hex_encode(@bittorrent.parse_torrent(t2).info_hash) + let url_b64 = make_b64(t2, false, true) + assert_true(url_b64.contains("-") && url_b64.contains("_")) + assert_true(!url_b64.contains("=")) + let resp2 = test_http_api_request( + api_port, + rs, + "POST", + "/api/torrents/add", + "127.0.0.1:\{api_port}", + [("Content-Type", "application/json"), ("X-Moon-I2P", "1")], + "{\"torrent_b64\":\"\{url_b64}\"}", + ) + assert_true(resp2.contains("200 OK")) + assert_true(resp2.contains(ih2)) + + let bad_resp = test_http_api_request( + api_port, + rs, + "POST", + "/api/torrents/add", + "127.0.0.1:\{api_port}", + [("Content-Type", "application/json"), ("X-Moon-I2P", "1")], + "{\"torrent_b64\":\"not*valid*b64!\"}", + ) + assert_true(bad_resp.contains("400 Bad Request")) + assert_true(bad_resp.contains("invalid torrent_b64")) +} diff --git a/router/sam_handler.mbt b/router/sam_handler.mbt index b9f45bd..4796f57 100644 --- a/router/sam_handler.mbt +++ b/router/sam_handler.mbt @@ -192,9 +192,51 @@ fn Router::resolve_name_local( None } +///| +fn Router::has_active_bridge_to( + self : Router, + peer_hash : @common.Hash, +) -> Bool { + for br in self.remote_bridges { + if !br.closed && br.peer_hash == peer_hash && br.state == 1 && !br.local_eof { + return true + } + } + false +} + +///| +fn Router::try_acquire_ratchet_reset( + self : Router, + peer_hash : @common.Hash, + now_ms : UInt64, + cooldown_ms : UInt64, +) -> Bool { + let mut i = 0 + let mut recent = false + while i < self.ratchet_resets.length() { + if now_ms > self.ratchet_resets[i].1 + cooldown_ms { + let _ = self.ratchet_resets.remove(i) + } else { + if self.ratchet_resets[i].0 == peer_hash { + recent = true + } + i += 1 + } + } + if recent { + return false + } + if self.ratchet_resets.length() >= 256 { + let _ = self.ratchet_resets.remove(0) + } + self.ratchet_resets.push((peer_hash, now_ms)) + true +} + ///| fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool { - sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch { + sock.write_all(@encoding.string_to_utf8_bytes(line + "\n"), timeout_ms=500) catch { _ => return false } true @@ -243,9 +285,11 @@ fn Router::flush_stream_outbound( _ => () } let exp_sec = now_sec + 60U + let effective_send_ls2 = send_ls2 || + !ratchet.has_active_session(peer_static_pub, now_sec~) for idx = 0; idx < packets.length(); idx = idx + 1 { let blocks : Array[@ratchet.RatchetBlock] = [] - if send_ls2 && idx == 0 { + if effective_send_ls2 && idx == 0 { match self.build_session_leaseset2(sess, now_sec) { Some(ls2) => { let ls_bytes = ls2.to_bytes() catch { _ => b"" } @@ -287,7 +331,7 @@ fn Router::flush_stream_outbound( } if self.debug { println( - "[debug] send Garlic (\{wire.length()}B, ls2=\{send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}", + "[debug] send Garlic (\{wire.length()}B, ls2=\{effective_send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}", ) } self.send_routed_i2np(gw, Some(tid), Garlic(data=wire)) @@ -436,7 +480,9 @@ fn Router::handle_incoming_garlic( Some(r) => r None => continue } - let res = Some(ratchet.decrypt_incoming(garlic_data)) catch { _ => None } + let res = Some(ratchet.decrypt_incoming(garlic_data, now_sec~)) catch { + _ => None + } match res { Some((_remote_static, blocks)) => { if self.debug { @@ -1158,20 +1204,29 @@ fn Router::step_remote_bridges(self : Router) -> Bool { } } - // 1b. Self-heal stalled SynSent streams by dropping potentially expired ECIES ratchet state - // before the next SYN retransmit so a fresh Bound NewSession + LeaseSet2 is sent + // 1b. Self-heal stalled SynSent streams by marking outbound ECIES send state stale + // so a fresh Bound NewSession + LeaseSet2 is sent without dropping active recv windows for br in self.remote_bridges { if br.state == 0 && !br.ratchet_reset && now_ms > br.started_ms + 7000UL { br.ratchet_reset = true + if self.has_active_bridge_to(br.peer_hash) { + continue + } match self.find_session_by_id(br.session_id) { Some(sess) => match sess.ratchet { Some(r) => { - r.drop_session(br.peer_static_pub) - if self.debug { - println( - "[debug] resetting ECIES ratchet for stalled SYN to \{br.peer_hash.to_b32_address()}", - ) + let lrx = r.last_recv_sec(br.peer_static_pub) + let recent_rx = lrx != 0U && now_sec <= lrx + 8U + if r.has_active_session(br.peer_static_pub, now_sec~) && + !recent_rx && + self.try_acquire_ratchet_reset(br.peer_hash, now_ms, 12000UL) { + r.mark_send_stale(br.peer_static_pub) + if self.debug { + println( + "[debug] marking ECIES ratchet send-stale for stalled SYN to \{br.peer_hash.to_b32_address()}", + ) + } } } None => () @@ -1264,11 +1319,18 @@ fn Router::step_remote_bridges(self : Router) -> Bool { "[debug] Streaming failed/timed out to \{br.peer_hash.to_b32_address()}", ) } - match sess.ratchet { - Some(r) => r.drop_session(br.peer_static_pub) - None => () + if !self.has_active_bridge_to(br.peer_hash) { + match sess.ratchet { + Some(r) => { + let lrx = r.last_recv_sec(br.peer_static_pub) + if lrx == 0U || now_sec > lrx + 15U { + r.mark_send_stale(br.peer_static_pub) + let _ = self.netdb.remove_lease_set2(br.peer_hash) + } + } + None => () + } } - let _ = self.netdb.remove_lease_set2(br.peer_hash) if br.is_http_proxy { send_http_proxy_error( br.sock, @@ -1295,7 +1357,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool { "[debug] stream \{br.local_stream_id} recv \{avail.length()}B", ) } - br.sock.write_all(avail) catch { + br.sock.write_all(avail, timeout_ms=500) catch { _ => { br.local_eof = true if br.closing_since_ms == 0UL { @@ -1318,6 +1380,14 @@ fn Router::step_remote_bridges(self : Router) -> Bool { let _ = conn.close(now_ms) catch { _ => () } } } + if conn.state == Reset { + did_work = true + remove_stream_by_id(mgr, br.local_stream_id) + br.sock.close() + br.closed = true + let _ = self.remote_bridges.remove(ri) + continue + } if br.pending_buf.length() > 0 { if conn.state != Established && conn.state != SynSent { br.pending_buf.clear() @@ -1367,11 +1437,13 @@ fn Router::step_remote_bridges(self : Router) -> Bool { br.lease_tid, send_ls2=false, ) - if br.local_eof && conn.is_eof() { + if br.local_eof { if br.closing_since_ms == 0UL { br.closing_since_ms = now_ms } - if !conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL { + let done_gracefully = conn.is_eof() && + (!conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL) + if done_gracefully || now_ms > br.closing_since_ms + 5000UL { did_work = true remove_stream_by_id(mgr, br.local_stream_id) br.sock.close() diff --git a/router/torrent_api.mbt b/router/torrent_api.mbt index de69eb6..8bf1085 100644 --- a/router/torrent_api.mbt +++ b/router/torrent_api.mbt @@ -248,12 +248,44 @@ fn api_send_response( } sb.write_string("Connection: close\r\n\r\n") let hdr_bytes = @encoding.string_to_utf8_bytes(sb.to_string()) - let _ = sock.write_all(hdr_bytes) catch { _ => () } + let _ = sock.write_all(hdr_bytes, timeout_ms=500) catch { _ => () } if body_bytes.length() > 0 { - let _ = sock.write_all(body_bytes) catch { _ => () } + let _ = sock.write_all(body_bytes, timeout_ms=500) catch { _ => () } } } +///| +/// Decodes standard (`+`/`/`), URL-safe (`-`/`_`), or I2P (`-`/`~`) Base64 strings, +/// restoring omitted trailing `=` padding when needed. +fn api_decode_base64_flexible( + b64 : String, +) -> Bytes raise @encoding.EncodingError { + let sb = StringBuilder() + let mut len = 0 + for ch in b64 { + if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' { + continue + } + let mapped = match ch { + '+' => '-' + '/' => '~' + '_' => '~' + _ => ch + } + sb.write_char(mapped) + len += 1 + } + if len > 0 { + let rem = len % 4 + if rem == 2 { + sb.write_string("==") + } else if rem == 3 { + sb.write_char('=') + } + } + @encoding.base64_decode(sb.to_string()) +} + ///| fn api_router_err_msg(e : RouterError) -> String { match e { @@ -641,7 +673,7 @@ fn Router::dispatch_torrent_api_request( (body.length() > 0 && body[0] == b'{') { match api_json_get_string(body_str, "torrent_b64") { Some(b64) => - @encoding.base64_decode(b64) catch { + api_decode_base64_flexible(b64) catch { _ => { api_send_response( ac.sock,