feat: add Android APK with embedded I2P browser and torrent manager
- Add an Android app (org.mooni2p.browser) with an I2P WebView browser defaulting to insulaocculta.i2p, bookmarks, and a diagnostics dialog. - Run the router in a foreground service and add a Torrents & DHT tab backed by the router API (manager.html). - Handle magnet links and .torrent files from intents, the file picker, and .i2p downloads. - Add scripts/build_apk.py and a `just apk` target that builds arm64-v8a and x86_64 APKs. - Document the APK build and install steps in the README. - Include related bittorrent, router, streaming, and ntcp2_net updates.
This commit is contained in:
1 parent
fbe6818c4e
commit
7a1b4325f9
16 files changed
+3041
-78
No files matched your search
@@ -72,6 +72,10 @@ just proxy
|
|||||||
just appimage
|
just appimage
|
||||||
./dist/MoonI2P-Browser-x86_64.AppImage
|
./dist/MoonI2P-Browser-x86_64.AppImage
|
||||||
|
|
||||||
|
# Build a standalone zero-setup Android APK (arm64-v8a + x86_64, insulaocculta.i2p homepage):
|
||||||
|
just apk
|
||||||
|
# Install dist/MoonI2P-Browser-android.apk via `adb install -r dist/MoonI2P-Browser-android.apk`
|
||||||
|
|
||||||
# Firefox WebExtension + I2P DHT Torrent Manager:
|
# Firefox WebExtension + I2P DHT Torrent Manager:
|
||||||
# Installs native messaging host (~/.mozilla & ~/.config/mozilla) and packs .xpi:
|
# Installs native messaging host (~/.mozilla & ~/.config/mozilla) and packs .xpi:
|
||||||
just extension
|
just extension
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
package="org.mooni2p.browser"
|
||||||
|
android:versionCode="3"
|
||||||
|
android:versionName="0.1.2">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:allowBackup="false"
|
||||||
|
android:extractNativeLibs="true"
|
||||||
|
android:icon="@mipmap/ic_launcher"
|
||||||
|
android:label="Moon I2P Browser"
|
||||||
|
android:networkSecurityConfig="@xml/network_security_config"
|
||||||
|
android:theme="@android:style/Theme.Material.NoActionBar"
|
||||||
|
android:usesCleartextTraffic="true">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|keyboard|navigation"
|
||||||
|
android:exported="true"
|
||||||
|
android:launchMode="singleTask">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:scheme="magnet" />
|
||||||
|
</intent-filter>
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.VIEW" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
<data android:mimeType="application/x-bittorrent" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".RouterService"
|
||||||
|
android:exported="false"
|
||||||
|
android:foregroundServiceType="dataSync" />
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,420 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width,initial-scale=1" />
|
||||||
|
<title>Moon I2P Torrents & DHT</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
color-scheme: dark;
|
||||||
|
--bg: #0b1120;
|
||||||
|
--card: #131c31;
|
||||||
|
--border: #23304d;
|
||||||
|
--text: #e2e8f0;
|
||||||
|
--muted: #94a3b8;
|
||||||
|
--accent: #6d5dfc;
|
||||||
|
--teal: #14b8a6;
|
||||||
|
--danger: #ef4444;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 12px;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: system-ui, -apple-system, sans-serif;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.45;
|
||||||
|
}
|
||||||
|
.card {
|
||||||
|
background: var(--card);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 12px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
h2 {
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
font-size: 12px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.06em;
|
||||||
|
color: var(--muted);
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.stat {
|
||||||
|
background: rgba(15, 23, 42, 0.65);
|
||||||
|
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px;
|
||||||
|
}
|
||||||
|
.stat-label { font-size: 11px; color: var(--muted); }
|
||||||
|
.stat-val { font-size: 13px; font-weight: 600; word-break: break-all; }
|
||||||
|
.mono { font-family: ui-monospace, monospace; font-size: 11px; }
|
||||||
|
.row { display: flex; gap: 8px; align-items: center; }
|
||||||
|
input[type="text"], input[type="number"] {
|
||||||
|
width: 100%;
|
||||||
|
background: #0b1222;
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 9px 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
button {
|
||||||
|
background: var(--accent);
|
||||||
|
color: #fff;
|
||||||
|
border: 0;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 9px 13px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
button.secondary {
|
||||||
|
background: #1e293b;
|
||||||
|
color: var(--text);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
button.danger {
|
||||||
|
background: rgba(239, 68, 68, 0.22);
|
||||||
|
color: #fca5a5;
|
||||||
|
border: 1px solid rgba(239, 68, 68, 0.4);
|
||||||
|
}
|
||||||
|
.pill {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 2px 9px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 600;
|
||||||
|
background: #1e293b;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
.pill.online { background: rgba(20, 184, 166, 0.2); color: #5eead4; }
|
||||||
|
.pill.offline { background: rgba(239, 68, 68, 0.2); color: #fca5a5; }
|
||||||
|
.torrent-item {
|
||||||
|
padding: 10px 0;
|
||||||
|
border-top: 1px solid rgba(255, 255, 255, 0.08);
|
||||||
|
}
|
||||||
|
.torrent-item:first-child { border-top: 0; padding-top: 0; }
|
||||||
|
.track {
|
||||||
|
width: 100%;
|
||||||
|
height: 7px;
|
||||||
|
background: #0b1222;
|
||||||
|
border-radius: 999px;
|
||||||
|
overflow: hidden;
|
||||||
|
margin: 6px 0;
|
||||||
|
}
|
||||||
|
.fill {
|
||||||
|
height: 100%;
|
||||||
|
background: linear-gradient(90deg, var(--accent), var(--teal));
|
||||||
|
}
|
||||||
|
.msg { font-size: 12px; margin-top: 8px; min-height: 16px; color: #5eead4; }
|
||||||
|
.msg.err { color: #fca5a5; }
|
||||||
|
pre {
|
||||||
|
margin: 8px 0 0 0;
|
||||||
|
background: #0b1222;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px;
|
||||||
|
font-size: 11px;
|
||||||
|
max-height: 220px;
|
||||||
|
overflow: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<section class="card">
|
||||||
|
<h2>
|
||||||
|
<span>moon-i2p Router Status</span>
|
||||||
|
<span id="status-pill" class="pill offline">Starting...</span>
|
||||||
|
</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-label">NetDB / Tunnels</div>
|
||||||
|
<div id="net-summary" class="stat-val">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-label">Download Folder</div>
|
||||||
|
<div id="dl-dir" class="stat-val mono">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat" style="margin-top:8px;">
|
||||||
|
<div class="stat-label">Torrent Session .b32.i2p</div>
|
||||||
|
<div class="row" style="margin-top:4px;">
|
||||||
|
<div id="torrent-b32" class="stat-val mono" style="flex:1;">--</div>
|
||||||
|
<button id="copy-b32-btn" class="secondary" type="button">Copy</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>
|
||||||
|
<span>I2P Kademlia DHT (Proto 17 / 18)</span>
|
||||||
|
<span id="dht-summary" class="mono">0 nodes</span>
|
||||||
|
</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-label">DHT Node ID (20B)</div>
|
||||||
|
<div id="dht-node-id" class="stat-val mono">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<div class="stat-label">Sent / Recv / Peers</div>
|
||||||
|
<div id="dht-stats" class="stat-val">0 / 0 / 0</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form id="bootstrap-form" class="row" style="margin-top:10px;">
|
||||||
|
<input id="bootstrap-b32" type="text" placeholder="Bootstrap node .b32.i2p" />
|
||||||
|
<input id="bootstrap-port" type="number" value="6881" style="width:82px;" />
|
||||||
|
<button type="submit" class="secondary">Ping</button>
|
||||||
|
</form>
|
||||||
|
<div id="dht-nodes" class="mono" style="margin-top:8px;color:var(--muted);">No DHT nodes yet.</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2><span>Add I2P Torrent</span></h2>
|
||||||
|
<form id="magnet-form" class="row">
|
||||||
|
<input id="magnet-uri" type="text" placeholder="magnet:?xt=urn:btih:..." />
|
||||||
|
<button type="submit">Add</button>
|
||||||
|
</form>
|
||||||
|
<div class="row" style="margin-top:8px;">
|
||||||
|
<button id="pick-file-btn" class="secondary" type="button" style="width:100%;">
|
||||||
|
Open .torrent File
|
||||||
|
</button>
|
||||||
|
<input id="torrent-file" type="file" accept=".torrent" style="display:none;" />
|
||||||
|
</div>
|
||||||
|
<div id="status-msg" class="msg"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>
|
||||||
|
<span>Active Torrents</span>
|
||||||
|
<span id="torrent-count" class="mono">0</span>
|
||||||
|
</h2>
|
||||||
|
<div id="torrents-list" style="color:var(--muted);">No torrents added yet.</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card">
|
||||||
|
<h2>
|
||||||
|
<span>Diagnostics & Verbose Logs</span>
|
||||||
|
<span class="row">
|
||||||
|
<button id="copy-diag-btn" type="button">Copy Diagnostics</button>
|
||||||
|
<button id="refresh-log-btn" class="secondary" type="button">Refresh</button>
|
||||||
|
</span>
|
||||||
|
</h2>
|
||||||
|
<pre id="router-log" class="mono">Loading diagnostics...</pre>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
"use strict";
|
||||||
|
const $ = (id) => document.getElementById(id);
|
||||||
|
|
||||||
|
function fmtBytes(n) {
|
||||||
|
if (!n || n <= 0) return "0 B";
|
||||||
|
const units = ["B", "KiB", "MiB", "GiB"];
|
||||||
|
let u = 0;
|
||||||
|
let v = n;
|
||||||
|
while (v >= 1024 && u < units.length - 1) {
|
||||||
|
v /= 1024;
|
||||||
|
u++;
|
||||||
|
}
|
||||||
|
return v.toFixed(u === 0 ? 0 : 1) + " " + units[u];
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s) {
|
||||||
|
return String(s || "").replace(/[&<>"']/g, (c) => ({
|
||||||
|
"&": "&",
|
||||||
|
"<": "<",
|
||||||
|
">": ">",
|
||||||
|
'"': """,
|
||||||
|
"'": "'",
|
||||||
|
})[c]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function setMsg(text, isErr) {
|
||||||
|
const el = $("status-msg");
|
||||||
|
el.textContent = text;
|
||||||
|
el.className = isErr ? "msg err" : "msg";
|
||||||
|
}
|
||||||
|
|
||||||
|
function bytesToBase64(bytes) {
|
||||||
|
let bin = "";
|
||||||
|
const chunk = 0x8000;
|
||||||
|
for (let i = 0; i < bytes.length; i += chunk) {
|
||||||
|
bin += String.fromCharCode(...bytes.subarray(i, i + chunk));
|
||||||
|
}
|
||||||
|
return btoa(bin);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function api(path, method, bodyObj) {
|
||||||
|
const headers = {};
|
||||||
|
const opts = { method: method || "GET", headers: headers, cache: "no-store" };
|
||||||
|
if (method === "POST") {
|
||||||
|
headers["X-Moon-I2P"] = "1";
|
||||||
|
headers["Content-Type"] = "application/json";
|
||||||
|
opts.body = JSON.stringify(bodyObj || {});
|
||||||
|
}
|
||||||
|
const resp = await fetch(path, opts);
|
||||||
|
return await resp.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refresh() {
|
||||||
|
try {
|
||||||
|
const [st, tl, dn] = await Promise.all([
|
||||||
|
api("/api/status", "GET"),
|
||||||
|
api("/api/torrents", "GET"),
|
||||||
|
api("/api/dht/nodes", "GET"),
|
||||||
|
]);
|
||||||
|
const pill = $("status-pill");
|
||||||
|
if (st && st.ok) {
|
||||||
|
pill.textContent = "Online";
|
||||||
|
pill.className = "pill online";
|
||||||
|
$("net-summary").textContent =
|
||||||
|
(st.netdb_routers || 0) + " peers · " +
|
||||||
|
(st.inbound_tunnels || 0) + "in/" + (st.outbound_tunnels || 0) + "out";
|
||||||
|
$("dl-dir").textContent = st.download_dir || "--";
|
||||||
|
$("torrent-b32").textContent = st.torrent_b32 || "--";
|
||||||
|
const d = st.dht || {};
|
||||||
|
$("dht-summary").textContent = (d.routing_table_nodes || 0) + " nodes";
|
||||||
|
$("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";
|
||||||
|
}
|
||||||
|
|
||||||
|
const nodes = (dn && dn.nodes) || [];
|
||||||
|
$("dht-nodes").innerHTML = nodes.length === 0
|
||||||
|
? "No DHT nodes yet."
|
||||||
|
: nodes.map((n) => "<div>" + escapeHtml(n.b32) + ":" + n.port + "</div>").join("");
|
||||||
|
|
||||||
|
const list = (tl && tl.torrents) || [];
|
||||||
|
$("torrent-count").textContent = String(list.length);
|
||||||
|
$("torrents-list").innerHTML = list.length === 0
|
||||||
|
? "No torrents added yet."
|
||||||
|
: list.map((t) => {
|
||||||
|
const pct = Number(t.progress_pct || 0);
|
||||||
|
const act = t.paused ? "resume" : "pause";
|
||||||
|
const label = t.paused ? "Resume" : "Pause";
|
||||||
|
const infTxt = t.inflight_blocks > 0 ? " (+" + t.inflight_blocks + " blks)" : "";
|
||||||
|
const peerRows = (t.peers || []).map((p) => {
|
||||||
|
const tag = p.client ? " [" + p.client + "]" : "";
|
||||||
|
const ch = p.choking ? "choked" : "unchoked";
|
||||||
|
return "<div>peer " + escapeHtml(p.b32) + escapeHtml(tag) + " · st=" + p.state + " " + ch + " · " + p.pieces + " pcs · inf=" + p.in_flight + " · blks=" + p.blocks_recv + "</div>";
|
||||||
|
}).join("");
|
||||||
|
return (
|
||||||
|
'<div class="torrent-item">' +
|
||||||
|
'<div class="row" style="justify-content:space-between;">' +
|
||||||
|
"<strong>" + escapeHtml(t.name) + "</strong>" +
|
||||||
|
'<span class="pill ' + (t.completed ? "online" : "") + '">' + escapeHtml(t.state) + " · " + pct + "%</span>" +
|
||||||
|
"</div>" +
|
||||||
|
'<div class="track"><div class="fill" style="width:' + pct + '%"></div></div>' +
|
||||||
|
'<div class="row" style="justify-content:space-between;font-size:12px;color:var(--muted);">' +
|
||||||
|
"<span>" + fmtBytes(t.downloaded_bytes) + " / " + fmtBytes(t.total_length) + " · " + t.have_pieces + "/" + t.num_pieces + " pcs" + infTxt + " · " + t.connected_peers + "/" + t.known_peers + " peers (" + (t.unchoked_peers || 0) + " unchoked)</span>" +
|
||||||
|
'<span class="row">' +
|
||||||
|
'<button type="button" class="secondary act-btn" data-act="' + act + '" data-ih="' + escapeHtml(t.info_hash) + '">' + label + "</button>" +
|
||||||
|
'<button type="button" class="danger act-btn" data-act="remove" data-ih="' + escapeHtml(t.info_hash) + '">Remove</button>' +
|
||||||
|
"</span>" +
|
||||||
|
"</div>" +
|
||||||
|
(t.last_tracker_status ? '<div class="mono" style="margin-top:4px;color:var(--muted);">Tracker: ' + escapeHtml(t.last_tracker_status) + "</div>" : "") +
|
||||||
|
(t.error ? '<div class="mono" style="margin-top:4px;color:#fca5a5;">Error: ' + escapeHtml(t.error) + "</div>" : "") +
|
||||||
|
(peerRows ? '<div class="mono" style="margin-top:4px;color:var(--muted);">' + peerRows + "</div>" : "") +
|
||||||
|
"</div>"
|
||||||
|
);
|
||||||
|
}).join("");
|
||||||
|
} catch (_e) {
|
||||||
|
$("status-pill").textContent = "Starting...";
|
||||||
|
$("status-pill").className = "pill offline";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$("copy-b32-btn").addEventListener("click", () => {
|
||||||
|
const b32 = $("torrent-b32").textContent || "";
|
||||||
|
if (window.MoonAndroid && b32 && b32 !== "--") {
|
||||||
|
window.MoonAndroid.copyText(b32);
|
||||||
|
setMsg("Copied .b32.i2p address", false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$("bootstrap-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const b32 = $("bootstrap-b32").value.trim();
|
||||||
|
const port = Number($("bootstrap-port").value) || 6881;
|
||||||
|
if (!b32) return;
|
||||||
|
const res = await api("/api/dht/bootstrap", "POST", { b32, port });
|
||||||
|
setMsg(res && res.ok ? "Sent DHT ping to " + res.b32 : "DHT error: " + (res?.error || "failed"), !res?.ok);
|
||||||
|
refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
$("magnet-form").addEventListener("submit", async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const uri = $("magnet-uri").value.trim();
|
||||||
|
if (!uri) return;
|
||||||
|
const res = await api("/api/torrents/magnet", "POST", { uri });
|
||||||
|
if (res && res.ok) {
|
||||||
|
$("magnet-uri").value = "";
|
||||||
|
setMsg("Added magnet " + res.info_hash.slice(0, 12) + "...", false);
|
||||||
|
} else {
|
||||||
|
setMsg("Magnet error: " + (res?.error || "router starting"), true);
|
||||||
|
}
|
||||||
|
refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
$("pick-file-btn").addEventListener("click", () => {
|
||||||
|
if (window.MoonAndroid && window.MoonAndroid.pickTorrentFile) {
|
||||||
|
window.MoonAndroid.pickTorrentFile();
|
||||||
|
} else {
|
||||||
|
$("torrent-file").click();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$("torrent-file").addEventListener("change", async () => {
|
||||||
|
const f = $("torrent-file").files[0];
|
||||||
|
if (!f) return;
|
||||||
|
const buf = new Uint8Array(await f.arrayBuffer());
|
||||||
|
const res = await api("/api/torrents/add", "POST", { torrent_b64: bytesToBase64(buf) });
|
||||||
|
setMsg(res && res.ok ? "Added " + f.name : "Add failed: " + (res?.error || "error"), !res?.ok);
|
||||||
|
refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
$("torrents-list").addEventListener("click", async (e) => {
|
||||||
|
const btn = e.target.closest(".act-btn");
|
||||||
|
if (!btn) return;
|
||||||
|
await api("/api/torrents/" + btn.dataset.act, "POST", { info_hash: btn.dataset.ih });
|
||||||
|
refresh();
|
||||||
|
});
|
||||||
|
|
||||||
|
function refreshLog() {
|
||||||
|
if (window.MoonAndroid && window.MoonAndroid.getDiagnosticsReport) {
|
||||||
|
$("router-log").textContent = window.MoonAndroid.getDiagnosticsReport() || "(empty)";
|
||||||
|
} else if (window.MoonAndroid && window.MoonAndroid.getRouterLog) {
|
||||||
|
$("router-log").textContent = window.MoonAndroid.getRouterLog() || "(empty)";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$("copy-diag-btn").addEventListener("click", () => {
|
||||||
|
if (window.MoonAndroid && window.MoonAndroid.copyDiagnostics) {
|
||||||
|
const rep = window.MoonAndroid.copyDiagnostics();
|
||||||
|
if (rep) $("router-log").textContent = rep;
|
||||||
|
setMsg("Copied full diagnostics report to clipboard", false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
$("refresh-log-btn").addEventListener("click", refreshLog);
|
||||||
|
|
||||||
|
refresh();
|
||||||
|
refreshLog();
|
||||||
|
setInterval(refresh, 2000);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,896 @@
|
|||||||
|
package org.mooni2p.browser;
|
||||||
|
|
||||||
|
import android.app.Activity;
|
||||||
|
import android.app.AlertDialog;
|
||||||
|
import android.content.ClipData;
|
||||||
|
import android.content.ClipboardManager;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.pm.PackageManager;
|
||||||
|
import android.graphics.Color;
|
||||||
|
import android.graphics.Typeface;
|
||||||
|
import android.net.Uri;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.os.Bundle;
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.Looper;
|
||||||
|
import android.text.InputType;
|
||||||
|
import android.util.Base64;
|
||||||
|
import android.util.TypedValue;
|
||||||
|
import android.view.Gravity;
|
||||||
|
import android.view.KeyEvent;
|
||||||
|
import android.view.View;
|
||||||
|
import android.view.ViewGroup;
|
||||||
|
import android.view.inputmethod.EditorInfo;
|
||||||
|
import android.webkit.CookieManager;
|
||||||
|
import android.webkit.JavascriptInterface;
|
||||||
|
import android.webkit.WebResourceRequest;
|
||||||
|
import android.webkit.WebResourceResponse;
|
||||||
|
import android.webkit.WebSettings;
|
||||||
|
import android.webkit.WebView;
|
||||||
|
import android.webkit.WebViewClient;
|
||||||
|
import android.widget.Button;
|
||||||
|
import android.widget.EditText;
|
||||||
|
import android.widget.FrameLayout;
|
||||||
|
import android.widget.LinearLayout;
|
||||||
|
import android.widget.ScrollView;
|
||||||
|
import android.widget.TextView;
|
||||||
|
import android.widget.Toast;
|
||||||
|
|
||||||
|
import org.json.JSONObject;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.Proxy;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Embedded I2P WebView browser defaulting to http://insulaocculta.i2p/ paired
|
||||||
|
* with a same-origin Torrents & I2P DHT management dashboard tab and full
|
||||||
|
* diagnostics report export.
|
||||||
|
*/
|
||||||
|
public class MainActivity extends Activity {
|
||||||
|
private static final String HOMEPAGE = "http://insulaocculta.i2p/";
|
||||||
|
private static final int REQ_PICK_TORRENT = 2001;
|
||||||
|
private static final int REQ_NOTIF_PERM = 2002;
|
||||||
|
|
||||||
|
private static final String[][] BOOKMARKS = new String[][] {
|
||||||
|
{ "Insula Occulta", "http://insulaocculta.i2p/" },
|
||||||
|
{ "I2P Stats", "http://stats.i2p/" },
|
||||||
|
{ "zzz.i2p", "http://zzz.i2p/" },
|
||||||
|
{ "Postman Tracker", "http://tracker2.postman.i2p/" },
|
||||||
|
{ "NotBob Directory", "http://notbob.i2p/" },
|
||||||
|
};
|
||||||
|
|
||||||
|
private LinearLayout mTopBar;
|
||||||
|
private EditText mUrlInput;
|
||||||
|
private TextView mRouterBadge;
|
||||||
|
private WebView mBrowserView;
|
||||||
|
private WebView mManagerView;
|
||||||
|
private Button mTabBrowserBtn;
|
||||||
|
private Button mTabTorrentsBtn;
|
||||||
|
|
||||||
|
private final Handler mHandler = new Handler(Looper.getMainLooper());
|
||||||
|
private final ConcurrentHashMap<String, Long> mRecentTorrentUrls = new ConcurrentHashMap<>();
|
||||||
|
private boolean mManagerLoaded = false;
|
||||||
|
private boolean mShowTorrentsTab = false;
|
||||||
|
private String mManagerHtmlCache = null;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onCreate(Bundle savedInstanceState) {
|
||||||
|
super.onCreate(savedInstanceState);
|
||||||
|
|
||||||
|
if (Build.VERSION.SDK_INT >= 33) {
|
||||||
|
if (checkSelfPermission("android.permission.POST_NOTIFICATIONS")
|
||||||
|
!= PackageManager.PERMISSION_GRANTED) {
|
||||||
|
requestPermissions(new String[] { "android.permission.POST_NOTIFICATIONS" }, REQ_NOTIF_PERM);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Intent svc = new Intent(this, RouterService.class);
|
||||||
|
if (Build.VERSION.SDK_INT >= 26) {
|
||||||
|
startForegroundService(svc);
|
||||||
|
} else {
|
||||||
|
startService(svc);
|
||||||
|
}
|
||||||
|
|
||||||
|
buildUi();
|
||||||
|
mBrowserView.loadUrl(HOMEPAGE);
|
||||||
|
handleIntent(getIntent());
|
||||||
|
startStatusPoll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onNewIntent(Intent intent) {
|
||||||
|
super.onNewIntent(intent);
|
||||||
|
handleIntent(intent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onBackPressed() {
|
||||||
|
if (!mShowTorrentsTab && mBrowserView.canGoBack()) {
|
||||||
|
mBrowserView.goBack();
|
||||||
|
} else if (mShowTorrentsTab) {
|
||||||
|
switchTab(false);
|
||||||
|
} else {
|
||||||
|
super.onBackPressed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int dp(int v) {
|
||||||
|
return (int) TypedValue.applyDimension(
|
||||||
|
TypedValue.COMPLEX_UNIT_DIP,
|
||||||
|
v,
|
||||||
|
getResources().getDisplayMetrics()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Button makeIconBtn(String label, View.OnClickListener onClick) {
|
||||||
|
Button b = new Button(this);
|
||||||
|
b.setText(label);
|
||||||
|
b.setTextColor(Color.parseColor("#E2E8F0"));
|
||||||
|
b.setBackgroundColor(Color.parseColor("#1E293B"));
|
||||||
|
b.setPadding(dp(7), dp(4), dp(7), dp(4));
|
||||||
|
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
|
||||||
|
b.setMinWidth(0);
|
||||||
|
b.setMinimumWidth(0);
|
||||||
|
b.setOnClickListener(onClick);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void buildUi() {
|
||||||
|
LinearLayout root = new LinearLayout(this);
|
||||||
|
root.setOrientation(LinearLayout.VERTICAL);
|
||||||
|
root.setBackgroundColor(Color.parseColor("#0B1120"));
|
||||||
|
root.setFitsSystemWindows(true);
|
||||||
|
|
||||||
|
// Top toolbar
|
||||||
|
mTopBar = new LinearLayout(this);
|
||||||
|
mTopBar.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
|
mTopBar.setGravity(Gravity.CENTER_VERTICAL);
|
||||||
|
mTopBar.setBackgroundColor(Color.parseColor("#131C31"));
|
||||||
|
mTopBar.setPadding(dp(6), dp(6), dp(6), dp(6));
|
||||||
|
|
||||||
|
mTopBar.addView(makeIconBtn("<", v -> {
|
||||||
|
if (mBrowserView.canGoBack()) mBrowserView.goBack();
|
||||||
|
}));
|
||||||
|
mTopBar.addView(makeIconBtn("H", v -> navigateBrowser(HOMEPAGE)));
|
||||||
|
mTopBar.addView(makeIconBtn("R", v -> mBrowserView.reload()));
|
||||||
|
|
||||||
|
mUrlInput = new EditText(this);
|
||||||
|
mUrlInput.setText(HOMEPAGE);
|
||||||
|
mUrlInput.setTextColor(Color.parseColor("#F8FAFC"));
|
||||||
|
mUrlInput.setHintTextColor(Color.parseColor("#94A3B8"));
|
||||||
|
mUrlInput.setBackgroundColor(Color.parseColor("#0B1222"));
|
||||||
|
mUrlInput.setSingleLine(true);
|
||||||
|
mUrlInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
|
||||||
|
mUrlInput.setImeOptions(EditorInfo.IME_ACTION_GO);
|
||||||
|
mUrlInput.setPadding(dp(8), dp(6), dp(8), dp(6));
|
||||||
|
mUrlInput.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
|
||||||
|
mUrlInput.setOnEditorActionListener((tv, actionId, event) -> {
|
||||||
|
if (actionId == EditorInfo.IME_ACTION_GO ||
|
||||||
|
(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
|
||||||
|
navigateBrowser(mUrlInput.getText().toString());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
LinearLayout.LayoutParams urlLp = new LinearLayout.LayoutParams(
|
||||||
|
0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f
|
||||||
|
);
|
||||||
|
urlLp.setMargins(dp(4), 0, dp(4), 0);
|
||||||
|
mTopBar.addView(mUrlInput, urlLp);
|
||||||
|
|
||||||
|
mTopBar.addView(makeIconBtn("BM", v -> showBookmarksDialog()));
|
||||||
|
mTopBar.addView(makeIconBtn("DIAG", v -> showDiagnosticsDialog()));
|
||||||
|
|
||||||
|
mRouterBadge = new TextView(this);
|
||||||
|
mRouterBadge.setText("Boot...");
|
||||||
|
mRouterBadge.setTextColor(Color.parseColor("#5EEAD4"));
|
||||||
|
mRouterBadge.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
|
||||||
|
mRouterBadge.setPadding(dp(6), dp(4), dp(4), dp(4));
|
||||||
|
mRouterBadge.setOnClickListener(v -> showDiagnosticsDialog());
|
||||||
|
mTopBar.addView(mRouterBadge);
|
||||||
|
|
||||||
|
root.addView(mTopBar, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
|
||||||
|
));
|
||||||
|
|
||||||
|
// Center content area
|
||||||
|
FrameLayout center = new FrameLayout(this);
|
||||||
|
|
||||||
|
mBrowserView = new WebView(this);
|
||||||
|
configureWebView(mBrowserView);
|
||||||
|
mBrowserView.addJavascriptInterface(new BrowserLinkBridge(), "MoonI2pPage");
|
||||||
|
mBrowserView.setWebViewClient(new I2pWebViewClient());
|
||||||
|
mBrowserView.setDownloadListener((dlUrl, userAgent, contentDisposition, mimetype, contentLength) -> {
|
||||||
|
if (dlUrl == null) return;
|
||||||
|
String lower = dlUrl.toLowerCase(Locale.ROOT);
|
||||||
|
if (lower.startsWith("magnet:")) {
|
||||||
|
submitMagnetAsync(dlUrl);
|
||||||
|
switchTab(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Uri u = Uri.parse(dlUrl);
|
||||||
|
String host = u.getHost() != null ? u.getHost().toLowerCase(Locale.ROOT) : "";
|
||||||
|
boolean isI2p = "i2p".equals(host) || host.endsWith(".i2p");
|
||||||
|
boolean isTorrentMime = mimetype != null && mimetype.toLowerCase(Locale.ROOT).contains("bittorrent");
|
||||||
|
boolean isTorrentDisp = contentDisposition != null && contentDisposition.toLowerCase(Locale.ROOT).contains(".torrent");
|
||||||
|
boolean isTorrentPath = u.getPath() != null && u.getPath().toLowerCase(Locale.ROOT).endsWith(".torrent");
|
||||||
|
if (isI2p && (isTorrentMime || isTorrentDisp || isTorrentPath || lower.contains(".torrent"))) {
|
||||||
|
fetchAndSubmitTorrentUrlAsync(dlUrl, u.getLastPathSegment() != null ? u.getLastPathSegment() : ".torrent");
|
||||||
|
switchTab(true);
|
||||||
|
} else {
|
||||||
|
Toast.makeText(MainActivity.this, "Download not handled: " + (mimetype != null ? mimetype : dlUrl), Toast.LENGTH_SHORT).show();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
center.addView(mBrowserView, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
|
||||||
|
));
|
||||||
|
|
||||||
|
mManagerView = new WebView(this);
|
||||||
|
configureWebView(mManagerView);
|
||||||
|
mManagerView.addJavascriptInterface(new ManagerBridge(), "MoonAndroid");
|
||||||
|
mManagerView.setVisibility(View.GONE);
|
||||||
|
center.addView(mManagerView, new FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT
|
||||||
|
));
|
||||||
|
|
||||||
|
root.addView(center, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, 0, 1.0f
|
||||||
|
));
|
||||||
|
|
||||||
|
// Bottom tab bar
|
||||||
|
LinearLayout bottomBar = new LinearLayout(this);
|
||||||
|
bottomBar.setOrientation(LinearLayout.HORIZONTAL);
|
||||||
|
bottomBar.setBackgroundColor(Color.parseColor("#131C31"));
|
||||||
|
bottomBar.setPadding(dp(6), dp(6), dp(6), dp(6));
|
||||||
|
|
||||||
|
mTabBrowserBtn = new Button(this);
|
||||||
|
mTabBrowserBtn.setText("Browser (.i2p)");
|
||||||
|
mTabBrowserBtn.setOnClickListener(v -> switchTab(false));
|
||||||
|
|
||||||
|
mTabTorrentsBtn = new Button(this);
|
||||||
|
mTabTorrentsBtn.setText("Torrents & DHT");
|
||||||
|
mTabTorrentsBtn.setOnClickListener(v -> switchTab(true));
|
||||||
|
|
||||||
|
LinearLayout.LayoutParams tabLp = new LinearLayout.LayoutParams(
|
||||||
|
0, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f
|
||||||
|
);
|
||||||
|
tabLp.setMargins(dp(4), 0, dp(4), 0);
|
||||||
|
bottomBar.addView(mTabBrowserBtn, tabLp);
|
||||||
|
bottomBar.addView(mTabTorrentsBtn, tabLp);
|
||||||
|
|
||||||
|
root.addView(bottomBar, new LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
|
||||||
|
));
|
||||||
|
|
||||||
|
setContentView(root);
|
||||||
|
switchTab(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void configureWebView(WebView wv) {
|
||||||
|
WebSettings ws = wv.getSettings();
|
||||||
|
ws.setJavaScriptEnabled(true);
|
||||||
|
ws.setDomStorageEnabled(true);
|
||||||
|
ws.setBuiltInZoomControls(true);
|
||||||
|
ws.setDisplayZoomControls(false);
|
||||||
|
ws.setLoadWithOverviewMode(true);
|
||||||
|
ws.setUseWideViewPort(true);
|
||||||
|
ws.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
|
||||||
|
CookieManager.getInstance().setAcceptCookie(true);
|
||||||
|
CookieManager.getInstance().setAcceptThirdPartyCookies(wv, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void switchTab(boolean torrentsTab) {
|
||||||
|
mShowTorrentsTab = torrentsTab;
|
||||||
|
mBrowserView.setVisibility(torrentsTab ? View.GONE : View.VISIBLE);
|
||||||
|
mManagerView.setVisibility(torrentsTab ? View.VISIBLE : View.GONE);
|
||||||
|
mTopBar.setVisibility(torrentsTab ? View.GONE : View.VISIBLE);
|
||||||
|
|
||||||
|
mTabBrowserBtn.setBackgroundColor(
|
||||||
|
Color.parseColor(torrentsTab ? "#1E293B" : "#6D5DFC")
|
||||||
|
);
|
||||||
|
mTabBrowserBtn.setTextColor(Color.parseColor("#FFFFFF"));
|
||||||
|
mTabTorrentsBtn.setBackgroundColor(
|
||||||
|
Color.parseColor(torrentsTab ? "#6D5DFC" : "#1E293B")
|
||||||
|
);
|
||||||
|
mTabTorrentsBtn.setTextColor(Color.parseColor("#FFFFFF"));
|
||||||
|
|
||||||
|
if (torrentsTab) {
|
||||||
|
ensureManagerLoaded();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureManagerLoaded() {
|
||||||
|
int apiPort = RouterService.getApiPort();
|
||||||
|
if (mManagerLoaded || apiPort <= 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (mManagerHtmlCache == null) {
|
||||||
|
try (InputStream in = getAssets().open("manager.html")) {
|
||||||
|
byte[] data = readAllBytes(in, 512 * 1024);
|
||||||
|
mManagerHtmlCache = new String(data, StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mManagerLoaded = true;
|
||||||
|
mManagerView.loadDataWithBaseURL(
|
||||||
|
"http://127.0.0.1:" + apiPort + "/",
|
||||||
|
mManagerHtmlCache,
|
||||||
|
"text/html",
|
||||||
|
"utf-8",
|
||||||
|
null
|
||||||
|
);
|
||||||
|
} catch (Exception e) {
|
||||||
|
Toast.makeText(this, "Failed to load manager UI: " + e.getMessage(), Toast.LENGTH_SHORT).show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void navigateBrowser(String raw) {
|
||||||
|
String s = raw == null ? "" : raw.trim();
|
||||||
|
if (s.isEmpty()) s = HOMEPAGE;
|
||||||
|
if (!s.contains("://") && !s.startsWith("magnet:")) {
|
||||||
|
s = "http://" + s;
|
||||||
|
}
|
||||||
|
mUrlInput.setText(s);
|
||||||
|
if (s.toLowerCase(Locale.ROOT).startsWith("magnet:")) {
|
||||||
|
submitMagnetAsync(s);
|
||||||
|
switchTab(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
switchTab(false);
|
||||||
|
mBrowserView.loadUrl(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void showBookmarksDialog() {
|
||||||
|
String[] titles = new String[BOOKMARKS.length];
|
||||||
|
for (int i = 0; i < BOOKMARKS.length; i++) {
|
||||||
|
titles[i] = BOOKMARKS[i][0] + " (" + BOOKMARKS[i][1] + ")";
|
||||||
|
}
|
||||||
|
new AlertDialog.Builder(this)
|
||||||
|
.setTitle("I2P Bookmarks")
|
||||||
|
.setItems(titles, (dialog, idx) -> navigateBrowser(BOOKMARKS[idx][1]))
|
||||||
|
.show();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void copyToClipboard(String text, String toastMsg) {
|
||||||
|
ClipboardManager cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
|
||||||
|
if (cm != null) {
|
||||||
|
cm.setPrimaryClip(ClipData.newPlainText("moon-i2p-diagnostics", text));
|
||||||
|
}
|
||||||
|
Toast.makeText(this, toastMsg, Toast.LENGTH_SHORT).show();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void showDiagnosticsDialog() {
|
||||||
|
ScrollView sv = new ScrollView(this);
|
||||||
|
sv.setPadding(dp(12), dp(8), dp(12), dp(8));
|
||||||
|
TextView tv = new TextView(this);
|
||||||
|
tv.setText("Loading diagnostics...");
|
||||||
|
tv.setTypeface(Typeface.MONOSPACE);
|
||||||
|
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
|
||||||
|
tv.setTextColor(Color.parseColor("#E2E8F0"));
|
||||||
|
tv.setTextIsSelectable(true);
|
||||||
|
sv.addView(tv);
|
||||||
|
|
||||||
|
final String[] latestReport = new String[] { "" };
|
||||||
|
Runnable loadReport = () -> new Thread(() -> {
|
||||||
|
String rep = RouterService.buildDiagnosticsReport(MainActivity.this);
|
||||||
|
runOnUiThread(() -> {
|
||||||
|
latestReport[0] = rep;
|
||||||
|
tv.setText(rep);
|
||||||
|
});
|
||||||
|
}).start();
|
||||||
|
|
||||||
|
AlertDialog dlg = new AlertDialog.Builder(this)
|
||||||
|
.setTitle("Moon I2P Diagnostics")
|
||||||
|
.setView(sv)
|
||||||
|
.setPositiveButton("Copy Diagnostics", (d, w) -> {
|
||||||
|
if (latestReport[0].isEmpty()) {
|
||||||
|
new Thread(() -> {
|
||||||
|
String rep = RouterService.buildDiagnosticsReport(MainActivity.this);
|
||||||
|
runOnUiThread(() -> copyToClipboard(rep, "Copied diagnostics to clipboard"));
|
||||||
|
}).start();
|
||||||
|
} else {
|
||||||
|
copyToClipboard(latestReport[0], "Copied diagnostics to clipboard");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.setNeutralButton("Refresh", null)
|
||||||
|
.setNegativeButton("Close", null)
|
||||||
|
.create();
|
||||||
|
|
||||||
|
dlg.setOnShowListener(d -> {
|
||||||
|
Button refreshBtn = dlg.getButton(AlertDialog.BUTTON_NEUTRAL);
|
||||||
|
if (refreshBtn != null) {
|
||||||
|
refreshBtn.setOnClickListener(v -> loadReport.run());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
dlg.show();
|
||||||
|
loadReport.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startStatusPoll() {
|
||||||
|
Runnable tick = new Runnable() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
if (RouterService.isApiReady()) {
|
||||||
|
mRouterBadge.setText("I2P:" + RouterService.getProxyPort());
|
||||||
|
ensureManagerLoaded();
|
||||||
|
} else {
|
||||||
|
mRouterBadge.setText("Boot...");
|
||||||
|
}
|
||||||
|
mHandler.postDelayed(this, 1500);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
mHandler.postDelayed(tick, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void handleIntent(Intent intent) {
|
||||||
|
if (intent == null) return;
|
||||||
|
Uri data = intent.getData();
|
||||||
|
if (data == null) return;
|
||||||
|
String s = data.toString();
|
||||||
|
if (s.toLowerCase(Locale.ROOT).startsWith("magnet:")) {
|
||||||
|
submitMagnetAsync(s);
|
||||||
|
switchTab(true);
|
||||||
|
} else if ("application/x-bittorrent".equals(intent.getType()) ||
|
||||||
|
s.toLowerCase(Locale.ROOT).endsWith(".torrent")) {
|
||||||
|
submitContentUriTorrentAsync(data);
|
||||||
|
switchTab(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
|
||||||
|
super.onActivityResult(requestCode, resultCode, data);
|
||||||
|
if (requestCode == REQ_PICK_TORRENT && resultCode == RESULT_OK && data != null && data.getData() != null) {
|
||||||
|
submitContentUriTorrentAsync(data.getData());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] readAllBytes(InputStream in, int maxBytes) throws Exception {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
byte[] buf = new byte[16384];
|
||||||
|
int total = 0;
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) > 0) {
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
total += n;
|
||||||
|
if (total >= maxBytes) break;
|
||||||
|
}
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private JSONObject postTorrentApi(String path, String jsonBody) throws Exception {
|
||||||
|
int port = RouterService.getApiPort();
|
||||||
|
if (port <= 0) {
|
||||||
|
throw new IllegalStateException("Router API not started yet");
|
||||||
|
}
|
||||||
|
HttpURLConnection conn = (HttpURLConnection) new URL("http://127.0.0.1:" + port + path).openConnection();
|
||||||
|
conn.setRequestMethod("POST");
|
||||||
|
conn.setRequestProperty("X-Moon-I2P", "1");
|
||||||
|
conn.setRequestProperty("Content-Type", "application/json");
|
||||||
|
conn.setConnectTimeout(4000);
|
||||||
|
conn.setReadTimeout(8000);
|
||||||
|
conn.setDoOutput(true);
|
||||||
|
try (OutputStream os = conn.getOutputStream()) {
|
||||||
|
os.write(jsonBody.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
int code = conn.getResponseCode();
|
||||||
|
InputStream in = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
|
||||||
|
String respText = in != null ? new String(readAllBytes(in, 64 * 1024), StandardCharsets.UTF_8) : "{}";
|
||||||
|
conn.disconnect();
|
||||||
|
return new JSONObject(respText);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void submitMagnetAsync(String magnetUri) {
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
JSONObject body = new JSONObject();
|
||||||
|
body.put("uri", magnetUri);
|
||||||
|
JSONObject res = postTorrentApi("/api/torrents/magnet", body.toString());
|
||||||
|
String msg = res.optBoolean("ok", false)
|
||||||
|
? "Added magnet " + res.optString("info_hash", "").substring(0, Math.min(12, res.optString("info_hash", "").length()))
|
||||||
|
: "Magnet error: " + res.optString("error", "failed");
|
||||||
|
runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
|
||||||
|
} catch (Exception e) {
|
||||||
|
runOnUiThread(() -> Toast.makeText(this, "Router starting; retry: " + e.getMessage(), Toast.LENGTH_SHORT).show());
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void submitTorrentBytesAsync(byte[] torrentBytes, String label) {
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
JSONObject body = new JSONObject();
|
||||||
|
body.put("torrent_b64", Base64.encodeToString(torrentBytes, Base64.NO_WRAP));
|
||||||
|
JSONObject res = postTorrentApi("/api/torrents/add", body.toString());
|
||||||
|
String msg = res.optBoolean("ok", false)
|
||||||
|
? "Added torrent " + label
|
||||||
|
: "Torrent error: " + res.optString("error", "failed");
|
||||||
|
runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
|
||||||
|
} catch (Exception e) {
|
||||||
|
runOnUiThread(() -> Toast.makeText(this, "Add failed: " + e.getMessage(), Toast.LENGTH_SHORT).show());
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void submitContentUriTorrentAsync(Uri uri) {
|
||||||
|
new Thread(() -> {
|
||||||
|
try (InputStream in = getContentResolver().openInputStream(uri)) {
|
||||||
|
if (in == null) return;
|
||||||
|
byte[] bytes = readAllBytes(in, 4 * 1024 * 1024);
|
||||||
|
submitTorrentBytesAsync(bytes, uri.getLastPathSegment() != null ? uri.getLastPathSegment() : ".torrent");
|
||||||
|
} catch (Exception e) {
|
||||||
|
runOnUiThread(() -> Toast.makeText(this, "Read failed: " + e.getMessage(), Toast.LENGTH_SHORT).show());
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean markRecentTorrentUrl(String url) {
|
||||||
|
if (url == null || url.isEmpty()) return false;
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
Long prev = mRecentTorrentUrls.get(url);
|
||||||
|
if (prev != null && now - prev < 4000L) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
mRecentTorrentUrls.put(url, now);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] fetchUrlViaI2pProxy(String targetUrl) throws Exception {
|
||||||
|
int pPort = RouterService.getProxyPort();
|
||||||
|
if (pPort <= 0) return null;
|
||||||
|
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(RouterService.ipv4Loopback(), pPort));
|
||||||
|
HttpURLConnection conn = (HttpURLConnection) new URL(targetUrl).openConnection(proxy);
|
||||||
|
conn.setConnectTimeout(15000);
|
||||||
|
conn.setReadTimeout(25000);
|
||||||
|
try (InputStream in = conn.getInputStream()) {
|
||||||
|
return readAllBytes(in, 4 * 1024 * 1024);
|
||||||
|
} finally {
|
||||||
|
conn.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fetchAndSubmitTorrentUrlAsync(String url, String fallbackLabel) {
|
||||||
|
if (!markRecentTorrentUrl(url)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
new Thread(() -> {
|
||||||
|
try {
|
||||||
|
byte[] raw = fetchUrlViaI2pProxy(url);
|
||||||
|
if (raw != null && raw.length > 0) {
|
||||||
|
submitTorrentBytesAsync(raw, fallbackLabel != null ? fallbackLabel : ".torrent");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
RouterService.logEvent("TORRENT_ERR", url + " -> " + e.getMessage());
|
||||||
|
runOnUiThread(() -> Toast.makeText(MainActivity.this, "Torrent fetch failed: " + e.getMessage(), Toast.LENGTH_SHORT).show());
|
||||||
|
}
|
||||||
|
}).start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class BrowserLinkBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
public void addMagnet(String uri) {
|
||||||
|
if (uri == null || !uri.trim().toLowerCase(Locale.ROOT).startsWith("magnet:")) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
submitMagnetAsync(uri.trim());
|
||||||
|
runOnUiThread(() -> switchTab(true));
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public void addTorrentUrl(String url) {
|
||||||
|
if (url == null) return;
|
||||||
|
String trimmed = url.trim();
|
||||||
|
Uri u = Uri.parse(trimmed);
|
||||||
|
String host = u.getHost();
|
||||||
|
if (host == null) return;
|
||||||
|
String lh = host.toLowerCase(Locale.ROOT);
|
||||||
|
if (!"i2p".equals(lh) && !lh.endsWith(".i2p")) return;
|
||||||
|
String lower = trimmed.toLowerCase(Locale.ROOT);
|
||||||
|
if (!lower.contains(".torrent")) return;
|
||||||
|
fetchAndSubmitTorrentUrlAsync(trimmed, u.getLastPathSegment());
|
||||||
|
runOnUiThread(() -> switchTab(true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class ManagerBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
public void pickTorrentFile() {
|
||||||
|
runOnUiThread(() -> {
|
||||||
|
Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
|
||||||
|
i.addCategory(Intent.CATEGORY_OPENABLE);
|
||||||
|
i.setType("*/*");
|
||||||
|
startActivityForResult(i, REQ_PICK_TORRENT);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public String getRouterLog() {
|
||||||
|
return RouterService.readFileTail(RouterService.getLogFilePath(), 16384);
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public String getAndroidLog() {
|
||||||
|
return RouterService.getAndroidLogText();
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public String getDiagnosticsReport() {
|
||||||
|
return RouterService.buildDiagnosticsReport(MainActivity.this);
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public String copyDiagnostics() {
|
||||||
|
String report = RouterService.buildDiagnosticsReport(MainActivity.this);
|
||||||
|
runOnUiThread(() -> copyToClipboard(report, "Copied diagnostics to clipboard"));
|
||||||
|
return report;
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public String getDownloadDir() {
|
||||||
|
return RouterService.getDownloadDir();
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public void copyText(String text) {
|
||||||
|
runOnUiThread(() -> copyToClipboard(text, "Copied to clipboard"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
public void openUrl(String url) {
|
||||||
|
runOnUiThread(() -> navigateBrowser(url));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class I2pWebViewClient extends WebViewClient {
|
||||||
|
@Override
|
||||||
|
public void onPageFinished(WebView view, String url) {
|
||||||
|
super.onPageFinished(view, url);
|
||||||
|
if (url != null && !url.startsWith("about:")) {
|
||||||
|
mUrlInput.setText(url);
|
||||||
|
try {
|
||||||
|
Uri u = Uri.parse(url);
|
||||||
|
String h = u.getHost();
|
||||||
|
if (h != null) {
|
||||||
|
String lh = h.toLowerCase(Locale.ROOT);
|
||||||
|
if ("i2p".equals(lh) || lh.endsWith(".i2p")) {
|
||||||
|
String js = "(function(){"
|
||||||
|
+ "if(window.__moonI2pHooked)return;"
|
||||||
|
+ "window.__moonI2pHooked=true;"
|
||||||
|
+ "document.addEventListener('click',function(ev){"
|
||||||
|
+ "var a=ev.target&&ev.target.closest?ev.target.closest('a'):null;"
|
||||||
|
+ "if(!a||!window.MoonI2pPage)return;"
|
||||||
|
+ "var dm=a.getAttribute('data-magnet')||'';"
|
||||||
|
+ "var href=a.getAttribute('href')||'';"
|
||||||
|
+ "var abs='';try{abs=new URL(href,window.location.href).href;}catch(e){abs=href;}"
|
||||||
|
+ "var mag=dm.toLowerCase().indexOf('magnet:')===0?dm:(abs.toLowerCase().indexOf('magnet:')===0?abs:'');"
|
||||||
|
+ "if(mag){ev.preventDefault();ev.stopPropagation();if(ev.stopImmediatePropagation)ev.stopImmediatePropagation();window.MoonI2pPage.addMagnet(mag);return false;}"
|
||||||
|
+ "if(/\\.torrent([?#]|$)/i.test(abs)){ev.preventDefault();ev.stopPropagation();if(ev.stopImmediatePropagation)ev.stopImmediatePropagation();window.MoonI2pPage.addTorrentUrl(abs);return false;}"
|
||||||
|
+ "},true);"
|
||||||
|
+ "})();";
|
||||||
|
view.evaluateJavascript(js, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
|
||||||
|
Uri uri = request.getUrl();
|
||||||
|
String url = uri.toString();
|
||||||
|
String lower = url.toLowerCase(Locale.ROOT);
|
||||||
|
if (lower.startsWith("magnet:")) {
|
||||||
|
submitMagnetAsync(url);
|
||||||
|
switchTab(true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (lower.contains(".torrent") && uri.getHost() != null &&
|
||||||
|
(uri.getHost().toLowerCase(Locale.ROOT).endsWith(".i2p") ||
|
||||||
|
(uri.getPath() != null && uri.getPath().toLowerCase(Locale.ROOT).endsWith(".torrent")))) {
|
||||||
|
fetchAndSubmitTorrentUrlAsync(url, uri.getLastPathSegment());
|
||||||
|
switchTab(true);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private WebResourceResponse autoRefreshPage(int code, String reason, String detail) {
|
||||||
|
String html = "<!doctype html><html><head><meta charset=\"utf-8\">"
|
||||||
|
+ "<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">"
|
||||||
|
+ "<meta http-equiv=\"refresh\" content=\"3\">"
|
||||||
|
+ "<title>" + code + " " + reason + "</title>"
|
||||||
|
+ "<style>body{font-family:system-ui,sans-serif;background:#0b1120;color:#e2e8f0;padding:24px;}"
|
||||||
|
+ ".card{background:#131c31;border:1px solid #23304d;border-radius:12px;padding:16px;}"
|
||||||
|
+ "</style></head><body><div class=\"card\"><h2>" + code + " " + reason + "</h2>"
|
||||||
|
+ "<p>" + escapeSimple(detail) + "</p><p><small>Refreshing automatically every 3s... "
|
||||||
|
+ escapeSimple(RouterService.getStatusText()) + " · Tap DIAG above to inspect/copy logs.</small></p></div></body></html>";
|
||||||
|
Map<String, String> hdrs = new HashMap<>();
|
||||||
|
hdrs.put("Retry-After", "3");
|
||||||
|
return new WebResourceResponse(
|
||||||
|
"text/html",
|
||||||
|
"utf-8",
|
||||||
|
code,
|
||||||
|
reason,
|
||||||
|
hdrs,
|
||||||
|
new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String escapeSimple(String s) {
|
||||||
|
return s == null ? "" : s.replace("&", "&").replace("<", "<").replace(">", ">");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
|
||||||
|
Uri uri = request.getUrl();
|
||||||
|
String host = uri.getHost();
|
||||||
|
if (host == null) return super.shouldInterceptRequest(view, request);
|
||||||
|
String lowerHost = host.toLowerCase(Locale.ROOT);
|
||||||
|
if (!"i2p".equals(lowerHost) && !lowerHost.endsWith(".i2p")) {
|
||||||
|
return super.shouldInterceptRequest(view, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
int pPort = RouterService.getProxyPort();
|
||||||
|
if (pPort <= 0) {
|
||||||
|
RouterService.logEvent("PROXY", "HOLD " + uri + " (router proxyPort=" + pPort + ")");
|
||||||
|
return autoRefreshPage(
|
||||||
|
503,
|
||||||
|
"Service Unavailable",
|
||||||
|
"Starting bundled moon-i2p router and reseeding public I2P peers..."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
long t0 = System.currentTimeMillis();
|
||||||
|
try {
|
||||||
|
String currentUrl = uri.toString();
|
||||||
|
if (currentUrl.toLowerCase(Locale.ROOT).startsWith("https://")) {
|
||||||
|
currentUrl = "http://" + currentUrl.substring(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
Proxy proxy = new Proxy(
|
||||||
|
Proxy.Type.HTTP,
|
||||||
|
new InetSocketAddress(RouterService.ipv4Loopback(), pPort)
|
||||||
|
);
|
||||||
|
|
||||||
|
HttpURLConnection conn = null;
|
||||||
|
for (int hop = 0; hop < 5; hop++) {
|
||||||
|
URL u = new URL(currentUrl);
|
||||||
|
String h = u.getHost().toLowerCase(Locale.ROOT);
|
||||||
|
boolean isI2p = "i2p".equals(h) || h.endsWith(".i2p");
|
||||||
|
conn = (HttpURLConnection) (isI2p ? u.openConnection(proxy) : u.openConnection());
|
||||||
|
conn.setInstanceFollowRedirects(false);
|
||||||
|
conn.setConnectTimeout(15000);
|
||||||
|
conn.setReadTimeout(30000);
|
||||||
|
String method = request.getMethod();
|
||||||
|
conn.setRequestMethod(method != null ? method : "GET");
|
||||||
|
Map<String, String> reqHdrs = request.getRequestHeaders();
|
||||||
|
if (reqHdrs != null) {
|
||||||
|
for (Map.Entry<String, String> e : reqHdrs.entrySet()) {
|
||||||
|
String k = e.getKey();
|
||||||
|
if (k != null && !k.equalsIgnoreCase("Host") &&
|
||||||
|
!k.equalsIgnoreCase("Accept-Encoding") &&
|
||||||
|
!k.equalsIgnoreCase("User-Agent")) {
|
||||||
|
conn.setRequestProperty(k, e.getValue());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String cookies = CookieManager.getInstance().getCookie(currentUrl);
|
||||||
|
if (cookies != null && !cookies.isEmpty()) {
|
||||||
|
conn.setRequestProperty("Cookie", cookies);
|
||||||
|
}
|
||||||
|
int code = conn.getResponseCode();
|
||||||
|
if (code >= 300 && code < 400) {
|
||||||
|
String loc = conn.getHeaderField("Location");
|
||||||
|
conn.disconnect();
|
||||||
|
if (loc == null || loc.isEmpty()) {
|
||||||
|
return autoRefreshPage(502, "Bad Gateway", "Empty redirect from " + currentUrl);
|
||||||
|
}
|
||||||
|
currentUrl = new URL(u, loc).toString();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (conn == null) {
|
||||||
|
RouterService.logEvent("PROXY_ERR", uri + " -> null HttpURLConnection");
|
||||||
|
return autoRefreshPage(503, "Service Unavailable", "Proxy connection failed.");
|
||||||
|
}
|
||||||
|
int statusCode = conn.getResponseCode();
|
||||||
|
String reason = conn.getResponseMessage();
|
||||||
|
if (reason == null || reason.isEmpty()) reason = "OK";
|
||||||
|
|
||||||
|
Map<String, String> outHdrs = new HashMap<>();
|
||||||
|
for (Map.Entry<String, List<String>> e : conn.getHeaderFields().entrySet()) {
|
||||||
|
String k = e.getKey();
|
||||||
|
if (k == null || k.equalsIgnoreCase("Transfer-Encoding") || k.equalsIgnoreCase("Connection")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<String> vals = e.getValue();
|
||||||
|
if (vals != null && !vals.isEmpty()) {
|
||||||
|
if (k.equalsIgnoreCase("Set-Cookie")) {
|
||||||
|
for (String ck : vals) {
|
||||||
|
CookieManager.getInstance().setCookie(currentUrl, ck);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outHdrs.put(k, String.join(", ", vals));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String ctype = conn.getContentType();
|
||||||
|
String mime = "text/html";
|
||||||
|
String encoding = "utf-8";
|
||||||
|
if (ctype != null && !ctype.isEmpty()) {
|
||||||
|
String[] parts = ctype.split(";");
|
||||||
|
mime = parts[0].trim();
|
||||||
|
for (int i = 1; i < parts.length; i++) {
|
||||||
|
String p = parts[i].trim().toLowerCase(Locale.ROOT);
|
||||||
|
if (p.startsWith("charset=")) {
|
||||||
|
encoding = parts[i].trim().substring(8).replace("\"", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String dispHdr = conn.getHeaderField("Content-Disposition");
|
||||||
|
InputStream stream = statusCode >= 400 ? conn.getErrorStream() : conn.getInputStream();
|
||||||
|
byte[] payload = stream != null ? readAllBytes(stream, 8 * 1024 * 1024) : new byte[0];
|
||||||
|
conn.disconnect();
|
||||||
|
|
||||||
|
long elapsedMs = System.currentTimeMillis() - t0;
|
||||||
|
RouterService.logEvent("PROXY", (request.getMethod() != null ? request.getMethod() : "GET")
|
||||||
|
+ " " + currentUrl + " via 127.0.0.1:" + pPort
|
||||||
|
+ " -> HTTP " + statusCode + " (" + payload.length + "B, " + elapsedMs + "ms)");
|
||||||
|
|
||||||
|
String reqPath = uri.getPath() != null ? uri.getPath().toLowerCase(Locale.ROOT) : "";
|
||||||
|
boolean isTorrentResp = "application/x-bittorrent".equalsIgnoreCase(mime)
|
||||||
|
|| (dispHdr != null && dispHdr.toLowerCase(Locale.ROOT).contains(".torrent"))
|
||||||
|
|| reqPath.endsWith(".torrent")
|
||||||
|
|| currentUrl.toLowerCase(Locale.ROOT).endsWith(".torrent");
|
||||||
|
if (statusCode == 200 && payload.length > 0 && isTorrentResp) {
|
||||||
|
if (markRecentTorrentUrl(currentUrl) && markRecentTorrentUrl(uri.toString())) {
|
||||||
|
submitTorrentBytesAsync(payload, uri.getLastPathSegment() != null ? uri.getLastPathSegment() : ".torrent");
|
||||||
|
}
|
||||||
|
runOnUiThread(() -> switchTab(true));
|
||||||
|
return new WebResourceResponse(
|
||||||
|
"text/plain",
|
||||||
|
"utf-8",
|
||||||
|
204,
|
||||||
|
"No Content",
|
||||||
|
new HashMap<>(),
|
||||||
|
new ByteArrayInputStream(new byte[0])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new WebResourceResponse(
|
||||||
|
mime,
|
||||||
|
encoding,
|
||||||
|
statusCode,
|
||||||
|
reason,
|
||||||
|
outHdrs,
|
||||||
|
new ByteArrayInputStream(payload)
|
||||||
|
);
|
||||||
|
} catch (Exception e) {
|
||||||
|
long elapsedMs = System.currentTimeMillis() - t0;
|
||||||
|
RouterService.logEvent("PROXY_ERR", uri + " via 127.0.0.1:" + pPort + " (" + elapsedMs + "ms) -> "
|
||||||
|
+ e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||||
|
return autoRefreshPage(
|
||||||
|
503,
|
||||||
|
"Bootstrapping I2P",
|
||||||
|
"Connecting to " + lowerHost + " (" + e.getMessage() + ")."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,528 @@
|
|||||||
|
package org.mooni2p.browser;
|
||||||
|
|
||||||
|
import android.app.Notification;
|
||||||
|
import android.app.NotificationChannel;
|
||||||
|
import android.app.NotificationManager;
|
||||||
|
import android.app.PendingIntent;
|
||||||
|
import android.app.Service;
|
||||||
|
import android.content.Context;
|
||||||
|
import android.content.Intent;
|
||||||
|
import android.content.pm.PackageInfo;
|
||||||
|
import android.content.pm.ServiceInfo;
|
||||||
|
import android.os.Build;
|
||||||
|
import android.os.Environment;
|
||||||
|
import android.os.IBinder;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.FileOutputStream;
|
||||||
|
import java.io.FileWriter;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
|
import java.util.ArrayDeque;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Foreground Android service that fetches an I2P .su3 reseed file via Android
|
||||||
|
* HTTPS (without requiring curl) and runs the bundled native moon-i2p router.
|
||||||
|
*/
|
||||||
|
public class RouterService extends Service {
|
||||||
|
public static final String ACTION_STOP = "org.mooni2p.browser.ACTION_STOP";
|
||||||
|
private static final String CHANNEL_ID = "moon_i2p_router";
|
||||||
|
private static final int NOTIF_ID = 1001;
|
||||||
|
private static final int MAX_LOG_RING = 250;
|
||||||
|
|
||||||
|
private static final String[] RESEED_URLS = new String[] {
|
||||||
|
"https://reseed.i2pgit.org/i2pseeds.su3",
|
||||||
|
"https://reseed.diva.exchange/i2pseeds.su3",
|
||||||
|
"https://i2p.novg.net/i2pseeds.su3",
|
||||||
|
"https://reseed2.i2p.net/i2pseeds.su3",
|
||||||
|
"https://reseed.onion.im/i2pseeds.su3",
|
||||||
|
};
|
||||||
|
|
||||||
|
private static volatile int sProxyPort = 0;
|
||||||
|
private static volatile int sApiPort = 0;
|
||||||
|
private static volatile int sSamPort = 0;
|
||||||
|
private static volatile boolean sRunning = false;
|
||||||
|
private static volatile boolean sApiReady = false;
|
||||||
|
private static volatile String sStatusText = "Starting I2P router...";
|
||||||
|
private static volatile String sDownloadDir = "";
|
||||||
|
private static volatile String sLogFilePath = "";
|
||||||
|
private static volatile String sAndroidLogPath = "";
|
||||||
|
private static volatile String sSu3Path = "";
|
||||||
|
private static volatile long sStartedAtMs = 0L;
|
||||||
|
|
||||||
|
private static final ArrayDeque<String> sEventRing = new ArrayDeque<>();
|
||||||
|
private static final Object sLogLock = new Object();
|
||||||
|
|
||||||
|
private volatile boolean mShuttingDown = false;
|
||||||
|
private Process mRouterProc = null;
|
||||||
|
private Thread mWorker = null;
|
||||||
|
|
||||||
|
public static int getProxyPort() { return sProxyPort; }
|
||||||
|
public static int getApiPort() { return sApiPort; }
|
||||||
|
public static int getSamPort() { return sSamPort; }
|
||||||
|
public static boolean isRunning() { return sRunning; }
|
||||||
|
public static boolean isApiReady() { return sApiReady; }
|
||||||
|
public static String getStatusText() { return sStatusText; }
|
||||||
|
public static String getDownloadDir() { return sDownloadDir; }
|
||||||
|
public static String getLogFilePath() { return sLogFilePath; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Explicit IPv4 127.0.0.1 loopback address (InetAddress.getLoopbackAddress()
|
||||||
|
* can return IPv6 ::1 on Android, while moon-i2p binds IPv4 127.0.0.1).
|
||||||
|
*/
|
||||||
|
public static InetAddress ipv4Loopback() {
|
||||||
|
try {
|
||||||
|
return InetAddress.getByAddress("127.0.0.1", new byte[] { 127, 0, 0, 1 });
|
||||||
|
} catch (Exception e) {
|
||||||
|
return InetAddress.getLoopbackAddress();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void logEvent(String tag, String message) {
|
||||||
|
String ts;
|
||||||
|
synchronized (sLogLock) {
|
||||||
|
ts = new SimpleDateFormat("HH:mm:ss.SSS", Locale.US).format(new Date());
|
||||||
|
String line = "[" + ts + "] [" + tag + "] " + message;
|
||||||
|
if (sEventRing.size() >= MAX_LOG_RING) {
|
||||||
|
sEventRing.removeFirst();
|
||||||
|
}
|
||||||
|
sEventRing.addLast(line);
|
||||||
|
String path = sAndroidLogPath;
|
||||||
|
if (path != null && !path.isEmpty()) {
|
||||||
|
try (FileWriter fw = new FileWriter(path, true)) {
|
||||||
|
fw.write(line);
|
||||||
|
fw.write('\n');
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String getAndroidLogText() {
|
||||||
|
synchronized (sLogLock) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
for (String line : sEventRing) {
|
||||||
|
sb.append(line).append('\n');
|
||||||
|
}
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String readFileTail(String path, int maxBytes) {
|
||||||
|
if (path == null || path.isEmpty()) return "";
|
||||||
|
File f = new File(path);
|
||||||
|
if (!f.isFile()) return "";
|
||||||
|
try (FileInputStream fis = new FileInputStream(f)) {
|
||||||
|
long len = f.length();
|
||||||
|
long skip = Math.max(0L, len - (long) maxBytes);
|
||||||
|
if (skip > 0L) {
|
||||||
|
long skipped = 0L;
|
||||||
|
while (skipped < skip) {
|
||||||
|
long s = fis.skip(skip - skipped);
|
||||||
|
if (s <= 0L) break;
|
||||||
|
skipped += s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
byte[] buf = new byte[8192];
|
||||||
|
int total = 0;
|
||||||
|
int n;
|
||||||
|
while (total < maxBytes && (n = fis.read(buf, 0, Math.min(buf.length, maxBytes - total))) > 0) {
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
total += n;
|
||||||
|
}
|
||||||
|
String prefix = skip > 0L ? "...(truncated " + skip + " earlier bytes)...\n" : "";
|
||||||
|
return prefix + new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "Failed reading " + path + ": " + e.getMessage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String fetchLocalApiJson(int apiPort, String path) {
|
||||||
|
if (apiPort <= 0) return "(apiPort not bound yet)";
|
||||||
|
HttpURLConnection conn = null;
|
||||||
|
try {
|
||||||
|
URL u = new URL("http://127.0.0.1:" + apiPort + path);
|
||||||
|
conn = (HttpURLConnection) u.openConnection();
|
||||||
|
conn.setConnectTimeout(1000);
|
||||||
|
conn.setReadTimeout(1500);
|
||||||
|
int code = conn.getResponseCode();
|
||||||
|
InputStream in = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
|
||||||
|
if (in == null) return "HTTP " + code;
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
byte[] buf = new byte[4096];
|
||||||
|
int total = 0;
|
||||||
|
int n;
|
||||||
|
while (total < 64 * 1024 && (n = in.read(buf)) > 0) {
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
total += n;
|
||||||
|
}
|
||||||
|
return new String(out.toByteArray(), StandardCharsets.UTF_8);
|
||||||
|
} catch (Exception e) {
|
||||||
|
return "ERROR: " + e.getClass().getSimpleName() + ": " + e.getMessage();
|
||||||
|
} finally {
|
||||||
|
if (conn != null) conn.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collects device info, service state, router API snapshots, Android proxy events,
|
||||||
|
* and the verbose moon-i2p router log. Call from a background thread.
|
||||||
|
*/
|
||||||
|
public static String buildDiagnosticsReport(Context ctx) {
|
||||||
|
StringBuilder sb = new StringBuilder();
|
||||||
|
String verName = "?";
|
||||||
|
int verCode = 0;
|
||||||
|
try {
|
||||||
|
PackageInfo pi = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0);
|
||||||
|
verName = pi.versionName;
|
||||||
|
verCode = pi.versionCode;
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.append("=== Moon I2P Browser Diagnostics ===\n");
|
||||||
|
sb.append("App Version: ").append(verName).append(" (code=").append(verCode).append(")\n");
|
||||||
|
sb.append("Device: ").append(Build.MANUFACTURER).append(" ").append(Build.MODEL)
|
||||||
|
.append(" · Android ").append(Build.VERSION.RELEASE)
|
||||||
|
.append(" (API ").append(Build.VERSION.SDK_INT).append(")\n");
|
||||||
|
sb.append("ABIs: ").append(Arrays.toString(Build.SUPPORTED_ABIS)).append("\n");
|
||||||
|
sb.append("Running: ").append(sRunning)
|
||||||
|
.append(" · API Ready: ").append(sApiReady)
|
||||||
|
.append(" · Status: ").append(sStatusText).append("\n");
|
||||||
|
if (sStartedAtMs > 0L) {
|
||||||
|
long upSec = Math.max(0L, (System.currentTimeMillis() - sStartedAtMs) / 1000L);
|
||||||
|
sb.append("Uptime: ").append(upSec).append("s\n");
|
||||||
|
}
|
||||||
|
sb.append("Loopback IP: ").append(ipv4Loopback().getHostAddress())
|
||||||
|
.append(" · Proxy: ").append(sProxyPort)
|
||||||
|
.append(" · Torrent API: ").append(sApiPort)
|
||||||
|
.append(" · SAMv3: ").append(sSamPort).append("\n");
|
||||||
|
sb.append("Download Dir: ").append(sDownloadDir).append("\n");
|
||||||
|
|
||||||
|
if (sSu3Path != null && !sSu3Path.isEmpty()) {
|
||||||
|
File f = new File(sSu3Path);
|
||||||
|
if (f.isFile()) {
|
||||||
|
long ageSec = Math.max(0L, (System.currentTimeMillis() - f.lastModified()) / 1000L);
|
||||||
|
sb.append("Reseed SU3: ").append(f.getAbsolutePath())
|
||||||
|
.append(" (").append(f.length()).append(" bytes, age=").append(ageSec).append("s)\n");
|
||||||
|
} else {
|
||||||
|
sb.append("Reseed SU3: MISSING (").append(sSu3Path).append(")\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sb.append("\n=== Router API /api/status ===\n");
|
||||||
|
sb.append(fetchLocalApiJson(sApiPort, "/api/status")).append("\n");
|
||||||
|
sb.append("\n=== Router API /api/dht/nodes ===\n");
|
||||||
|
sb.append(fetchLocalApiJson(sApiPort, "/api/dht/nodes")).append("\n");
|
||||||
|
sb.append("\n=== Router API /api/torrents ===\n");
|
||||||
|
sb.append(fetchLocalApiJson(sApiPort, "/api/torrents")).append("\n");
|
||||||
|
|
||||||
|
sb.append("\n=== Android Service & Proxy Log ===\n");
|
||||||
|
String androidLog = getAndroidLogText();
|
||||||
|
if (androidLog.isEmpty()) {
|
||||||
|
androidLog = readFileTail(sAndroidLogPath, 16384);
|
||||||
|
}
|
||||||
|
sb.append(androidLog.isEmpty() ? "(empty)\n" : androidLog);
|
||||||
|
|
||||||
|
sb.append("\n=== Native moon-i2p Router Log (--debug, tail 32 KiB) ===\n");
|
||||||
|
String rLog = readFileTail(sLogFilePath, 32768);
|
||||||
|
sb.append(rLog.isEmpty() ? "(empty)\n" : rLog);
|
||||||
|
return sb.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onCreate() {
|
||||||
|
super.onCreate();
|
||||||
|
File alog = new File(getFilesDir(), "android_debug.log");
|
||||||
|
try {
|
||||||
|
if (alog.exists() && alog.length() > 512 * 1024) {
|
||||||
|
alog.delete();
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
sAndroidLogPath = alog.getAbsolutePath();
|
||||||
|
logEvent("SVC", "RouterService.onCreate device=" + Build.MANUFACTURER + " " + Build.MODEL
|
||||||
|
+ " API=" + Build.VERSION.SDK_INT + " ABIs=" + Arrays.toString(Build.SUPPORTED_ABIS));
|
||||||
|
createNotificationChannel();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||||
|
if (intent != null && ACTION_STOP.equals(intent.getAction())) {
|
||||||
|
logEvent("SVC", "ACTION_STOP received");
|
||||||
|
stopRouter();
|
||||||
|
stopSelf();
|
||||||
|
return START_NOT_STICKY;
|
||||||
|
}
|
||||||
|
startForegroundCompat("Bootstrapping I2P network...");
|
||||||
|
synchronized (this) {
|
||||||
|
if (mWorker == null || !mWorker.isAlive()) {
|
||||||
|
mShuttingDown = false;
|
||||||
|
mWorker = new Thread(this::runRouterLoop, "moon-i2p-router");
|
||||||
|
mWorker.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return START_STICKY;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void onDestroy() {
|
||||||
|
logEvent("SVC", "RouterService.onDestroy");
|
||||||
|
stopRouter();
|
||||||
|
super.onDestroy();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public IBinder onBind(Intent intent) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startForegroundCompat(String text) {
|
||||||
|
Notification notif = buildNotification(text);
|
||||||
|
if (Build.VERSION.SDK_INT >= 29) {
|
||||||
|
startForeground(NOTIF_ID, notif, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC);
|
||||||
|
} else {
|
||||||
|
startForeground(NOTIF_ID, notif);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createNotificationChannel() {
|
||||||
|
if (Build.VERSION.SDK_INT >= 26) {
|
||||||
|
NotificationChannel ch = new NotificationChannel(
|
||||||
|
CHANNEL_ID,
|
||||||
|
"Moon I2P Router",
|
||||||
|
NotificationManager.IMPORTANCE_LOW
|
||||||
|
);
|
||||||
|
ch.setDescription("Runs moon-i2p public router, proxy, and BitTorrent/DHT");
|
||||||
|
NotificationManager nm = getSystemService(NotificationManager.class);
|
||||||
|
if (nm != null) {
|
||||||
|
nm.createNotificationChannel(ch);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Notification buildNotification(String text) {
|
||||||
|
Intent openIntent = new Intent(this, MainActivity.class);
|
||||||
|
openIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
|
||||||
|
int piFlags = PendingIntent.FLAG_UPDATE_CURRENT;
|
||||||
|
if (Build.VERSION.SDK_INT >= 23) {
|
||||||
|
piFlags |= PendingIntent.FLAG_IMMUTABLE;
|
||||||
|
}
|
||||||
|
PendingIntent contentPi = PendingIntent.getActivity(this, 0, openIntent, piFlags);
|
||||||
|
|
||||||
|
Intent stopIntent = new Intent(this, RouterService.class);
|
||||||
|
stopIntent.setAction(ACTION_STOP);
|
||||||
|
PendingIntent stopPi = PendingIntent.getService(this, 1, stopIntent, piFlags);
|
||||||
|
|
||||||
|
Notification.Builder b = Build.VERSION.SDK_INT >= 26
|
||||||
|
? new Notification.Builder(this, CHANNEL_ID)
|
||||||
|
: new Notification.Builder(this);
|
||||||
|
|
||||||
|
return b
|
||||||
|
.setContentTitle("Moon I2P Browser")
|
||||||
|
.setContentText(text)
|
||||||
|
.setSmallIcon(android.R.drawable.stat_sys_download_done)
|
||||||
|
.setOngoing(true)
|
||||||
|
.setContentIntent(contentPi)
|
||||||
|
.addAction(android.R.drawable.ic_media_pause, "Stop", stopPi)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void updateNotification(String text) {
|
||||||
|
sStatusText = text;
|
||||||
|
logEvent("STATUS", text);
|
||||||
|
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
|
||||||
|
if (nm != null) {
|
||||||
|
nm.notify(NOTIF_ID, buildNotification(text));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int pickPort(int preferred) {
|
||||||
|
InetAddress lo = ipv4Loopback();
|
||||||
|
try (ServerSocket ss = new ServerSocket(preferred, 1, lo)) {
|
||||||
|
return ss.getLocalPort();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
try (ServerSocket ss = new ServerSocket(0, 1, lo)) {
|
||||||
|
return ss.getLocalPort();
|
||||||
|
} catch (Exception e) {
|
||||||
|
return preferred;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private File ensureReseedSu3() {
|
||||||
|
File su3 = new File(getFilesDir(), "i2pseeds.su3");
|
||||||
|
sSu3Path = su3.getAbsolutePath();
|
||||||
|
long maxAgeMs = 6L * 60L * 60L * 1000L;
|
||||||
|
if (su3.isFile() && su3.length() >= 4096 &&
|
||||||
|
System.currentTimeMillis() - su3.lastModified() < maxAgeMs) {
|
||||||
|
logEvent("RESEED", "Using cached " + su3.getAbsolutePath() + " (" + su3.length() + " bytes)");
|
||||||
|
return su3;
|
||||||
|
}
|
||||||
|
updateNotification("Fetching I2P network reseed...");
|
||||||
|
for (String urlStr : RESEED_URLS) {
|
||||||
|
if (mShuttingDown) return null;
|
||||||
|
HttpURLConnection conn = null;
|
||||||
|
File tmp = new File(getFilesDir(), "i2pseeds.su3.tmp");
|
||||||
|
try {
|
||||||
|
conn = (HttpURLConnection) new URL(urlStr).openConnection();
|
||||||
|
conn.setRequestProperty("User-Agent", "Wget/1.11.4");
|
||||||
|
conn.setConnectTimeout(10000);
|
||||||
|
conn.setReadTimeout(20000);
|
||||||
|
conn.setInstanceFollowRedirects(true);
|
||||||
|
int code = conn.getResponseCode();
|
||||||
|
if (code == 200) {
|
||||||
|
try (InputStream in = conn.getInputStream();
|
||||||
|
FileOutputStream out = new FileOutputStream(tmp)) {
|
||||||
|
byte[] buf = new byte[16384];
|
||||||
|
int total = 0;
|
||||||
|
int n;
|
||||||
|
while ((n = in.read(buf)) > 0) {
|
||||||
|
out.write(buf, 0, n);
|
||||||
|
total += n;
|
||||||
|
if (total > 2 * 1024 * 1024) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
logEvent("RESEED", urlStr + " -> HTTP 200 (" + tmp.length() + " bytes)");
|
||||||
|
if (tmp.length() >= 1024) {
|
||||||
|
if (su3.exists()) su3.delete();
|
||||||
|
if (tmp.renameTo(su3)) {
|
||||||
|
return su3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
logEvent("RESEED", urlStr + " -> HTTP " + code);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logEvent("RESEED_ERR", urlStr + " -> " + e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
if (conn != null) conn.disconnect();
|
||||||
|
if (tmp.exists()) tmp.delete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (su3.isFile() && su3.length() >= 1024) ? su3 : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void runRouterLoop() {
|
||||||
|
sRunning = true;
|
||||||
|
sApiReady = false;
|
||||||
|
sStartedAtMs = System.currentTimeMillis();
|
||||||
|
try {
|
||||||
|
File extDl = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
|
||||||
|
File dlDir = extDl != null ? new File(extDl, "moon-i2p") : new File(getFilesDir(), "downloads");
|
||||||
|
dlDir.mkdirs();
|
||||||
|
sDownloadDir = dlDir.getAbsolutePath();
|
||||||
|
|
||||||
|
File logFile = new File(getFilesDir(), "router.log");
|
||||||
|
sLogFilePath = logFile.getAbsolutePath();
|
||||||
|
|
||||||
|
File routerBin = new File(getApplicationInfo().nativeLibraryDir, "libmoon_i2p_router.so");
|
||||||
|
logEvent("ROUTER", "nativeLibraryDir=" + getApplicationInfo().nativeLibraryDir
|
||||||
|
+ " exists=" + routerBin.isFile() + " size=" + routerBin.length());
|
||||||
|
if (!routerBin.isFile()) {
|
||||||
|
updateNotification("Error: router binary missing in nativeLibraryDir");
|
||||||
|
sRunning = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
routerBin.setExecutable(true, false);
|
||||||
|
|
||||||
|
File su3 = ensureReseedSu3();
|
||||||
|
sProxyPort = pickPort(4444);
|
||||||
|
sApiPort = pickPort(4445);
|
||||||
|
sSamPort = pickPort(7656);
|
||||||
|
|
||||||
|
List<String> cmd = new ArrayList<>();
|
||||||
|
cmd.add(routerBin.getAbsolutePath());
|
||||||
|
cmd.add("--public");
|
||||||
|
cmd.add("--debug");
|
||||||
|
if (su3 != null) {
|
||||||
|
cmd.add("--su3");
|
||||||
|
cmd.add(su3.getAbsolutePath());
|
||||||
|
} else {
|
||||||
|
logEvent("RESEED_WARN", "No local .su3 fetched; router will try built-in reseed fallback");
|
||||||
|
}
|
||||||
|
cmd.add("--sam");
|
||||||
|
cmd.add("127.0.0.1:" + sSamPort);
|
||||||
|
cmd.add("--http-proxy");
|
||||||
|
cmd.add("127.0.0.1:" + sProxyPort);
|
||||||
|
cmd.add("--torrent-api");
|
||||||
|
cmd.add("127.0.0.1:" + sApiPort);
|
||||||
|
cmd.add("--download-dir");
|
||||||
|
cmd.add(sDownloadDir);
|
||||||
|
|
||||||
|
logEvent("ROUTER", "Launching: " + String.join(" ", cmd));
|
||||||
|
|
||||||
|
ProcessBuilder pb = new ProcessBuilder(cmd);
|
||||||
|
pb.directory(getFilesDir());
|
||||||
|
pb.environment().put("HOME", getFilesDir().getAbsolutePath());
|
||||||
|
pb.redirectErrorStream(true);
|
||||||
|
pb.redirectOutput(ProcessBuilder.Redirect.to(logFile));
|
||||||
|
|
||||||
|
updateNotification("Connecting to public I2P peers...");
|
||||||
|
mRouterProc = pb.start();
|
||||||
|
|
||||||
|
long deadline = System.currentTimeMillis() + 8000L;
|
||||||
|
while (!mShuttingDown && System.currentTimeMillis() < deadline) {
|
||||||
|
try {
|
||||||
|
HttpURLConnection c = (HttpURLConnection) new URL(
|
||||||
|
"http://127.0.0.1:" + sApiPort + "/api/status"
|
||||||
|
).openConnection();
|
||||||
|
c.setConnectTimeout(400);
|
||||||
|
c.setReadTimeout(400);
|
||||||
|
int code = c.getResponseCode();
|
||||||
|
c.disconnect();
|
||||||
|
if (code == 200) {
|
||||||
|
sApiReady = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
Thread.sleep(200);
|
||||||
|
}
|
||||||
|
updateNotification("Online · Proxy :" + sProxyPort + " · Torrent API :" + sApiPort);
|
||||||
|
|
||||||
|
Process proc = mRouterProc;
|
||||||
|
if (proc != null) {
|
||||||
|
int rc = proc.waitFor();
|
||||||
|
logEvent("ROUTER", "Router process exited with code=" + rc);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
logEvent("ROUTER_ERR", e.getClass().getSimpleName() + ": " + e.getMessage());
|
||||||
|
updateNotification("Router stopped: " + e.getMessage());
|
||||||
|
} finally {
|
||||||
|
sRunning = false;
|
||||||
|
sApiReady = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stopRouter() {
|
||||||
|
mShuttingDown = true;
|
||||||
|
sRunning = false;
|
||||||
|
sApiReady = false;
|
||||||
|
Process proc = mRouterProc;
|
||||||
|
mRouterProc = null;
|
||||||
|
if (proc != null) {
|
||||||
|
logEvent("ROUTER", "Stopping router child process");
|
||||||
|
proc.destroy();
|
||||||
|
try {
|
||||||
|
Thread.sleep(250);
|
||||||
|
} catch (InterruptedException ignored) {
|
||||||
|
}
|
||||||
|
if (Build.VERSION.SDK_INT >= 26 && proc.isAlive()) {
|
||||||
|
proc.destroyForcibly();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<network-security-config>
|
||||||
|
<base-config cleartextTrafficPermitted="true" />
|
||||||
|
</network-security-config>
|
||||||
@@ -119,6 +119,11 @@ test "Peer wire framing, BEP 10/9, i2p_pex, i2p_dht, and chunked I2P HTTP tracke
|
|||||||
Bitfield(b"\x80"),
|
Bitfield(b"\x80"),
|
||||||
Request(1, 0, 16384),
|
Request(1, 0, 16384),
|
||||||
Piece(1, 0, b"payload-bytes"),
|
Piece(1, 0, b"payload-bytes"),
|
||||||
|
SuggestPiece(3U),
|
||||||
|
HaveAll,
|
||||||
|
HaveNone,
|
||||||
|
RejectRequest(2, 16384, 16384),
|
||||||
|
AllowedFast(5U),
|
||||||
Extended(b'\x00', @bittorrent.encode_ext_handshake(metadata_size=Some(512))),
|
Extended(b'\x00', @bittorrent.encode_ext_handshake(metadata_size=Some(512))),
|
||||||
Extended(b'\x03', @bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
|
Extended(b'\x03', @bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
|
||||||
]
|
]
|
||||||
@@ -141,6 +146,7 @@ test "Peer wire framing, BEP 10/9, i2p_pex, i2p_dht, and chunked I2P HTTP tracke
|
|||||||
assert_eq(rext.ut_metadata_id, Some(b'\x02'))
|
assert_eq(rext.ut_metadata_id, Some(b'\x02'))
|
||||||
assert_eq(rext.i2p_dht_id, Some(b'\x03'))
|
assert_eq(rext.i2p_dht_id, Some(b'\x03'))
|
||||||
assert_eq(rext.metadata_size, Some(512))
|
assert_eq(rext.metadata_size, Some(512))
|
||||||
|
assert_eq(rext.client_name, "moon-i2p/0.1")
|
||||||
assert_eq(
|
assert_eq(
|
||||||
@bittorrent.decode_i2p_dht_ext(@bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
|
@bittorrent.decode_i2p_dht_ext(@bittorrent.encode_i2p_dht_ext(6881U, 6882U)),
|
||||||
Some((6881U, 6882U)),
|
Some((6881U, 6882U)),
|
||||||
|
|||||||
@@ -213,6 +213,11 @@ pub(all) enum PeerMessage {
|
|||||||
Request(Int32, Int32, Int32)
|
Request(Int32, Int32, Int32)
|
||||||
Piece(Int32, Int32, Bytes)
|
Piece(Int32, Int32, Bytes)
|
||||||
Cancel(Int32, Int32, Int32)
|
Cancel(Int32, Int32, Int32)
|
||||||
|
SuggestPiece(UInt32)
|
||||||
|
HaveAll
|
||||||
|
HaveNone
|
||||||
|
RejectRequest(Int32, Int32, Int32)
|
||||||
|
AllowedFast(UInt32)
|
||||||
Extended(Byte, Bytes)
|
Extended(Byte, Bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,6 +227,7 @@ pub(all) struct RemoteExtensions {
|
|||||||
mut i2p_pex_id : Byte?
|
mut i2p_pex_id : Byte?
|
||||||
mut i2p_dht_id : Byte?
|
mut i2p_dht_id : Byte?
|
||||||
mut metadata_size : Int32?
|
mut metadata_size : Int32?
|
||||||
|
mut client_name : String
|
||||||
}
|
}
|
||||||
|
|
||||||
#derive(Eq, @debug.Debug)
|
#derive(Eq, @debug.Debug)
|
||||||
|
|||||||
@@ -65,6 +65,11 @@ pub(all) enum PeerMessage {
|
|||||||
Request(Int32, Int32, Int32)
|
Request(Int32, Int32, Int32)
|
||||||
Piece(Int32, Int32, Bytes)
|
Piece(Int32, Int32, Bytes)
|
||||||
Cancel(Int32, Int32, Int32)
|
Cancel(Int32, Int32, Int32)
|
||||||
|
SuggestPiece(UInt32)
|
||||||
|
HaveAll
|
||||||
|
HaveNone
|
||||||
|
RejectRequest(Int32, Int32, Int32)
|
||||||
|
AllowedFast(UInt32)
|
||||||
Extended(Byte, Bytes)
|
Extended(Byte, Bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,6 +126,31 @@ pub fn encode_peer_message(msg : PeerMessage) -> Bytes {
|
|||||||
w.write_u32_be(begin.reinterpret_as_uint())
|
w.write_u32_be(begin.reinterpret_as_uint())
|
||||||
w.write_u32_be(len.reinterpret_as_uint())
|
w.write_u32_be(len.reinterpret_as_uint())
|
||||||
}
|
}
|
||||||
|
SuggestPiece(idx) => {
|
||||||
|
w.write_u32_be(5U)
|
||||||
|
w.write_u8(b'\x0d')
|
||||||
|
w.write_u32_be(idx)
|
||||||
|
}
|
||||||
|
HaveAll => {
|
||||||
|
w.write_u32_be(1U)
|
||||||
|
w.write_u8(b'\x0e')
|
||||||
|
}
|
||||||
|
HaveNone => {
|
||||||
|
w.write_u32_be(1U)
|
||||||
|
w.write_u8(b'\x0f')
|
||||||
|
}
|
||||||
|
RejectRequest(idx, begin, len) => {
|
||||||
|
w.write_u32_be(13U)
|
||||||
|
w.write_u8(b'\x10')
|
||||||
|
w.write_u32_be(idx.reinterpret_as_uint())
|
||||||
|
w.write_u32_be(begin.reinterpret_as_uint())
|
||||||
|
w.write_u32_be(len.reinterpret_as_uint())
|
||||||
|
}
|
||||||
|
AllowedFast(idx) => {
|
||||||
|
w.write_u32_be(5U)
|
||||||
|
w.write_u8(b'\x11')
|
||||||
|
w.write_u32_be(idx)
|
||||||
|
}
|
||||||
Extended(ext_id, payload) => {
|
Extended(ext_id, payload) => {
|
||||||
w.write_u32_be((2 + payload.length()).reinterpret_as_uint())
|
w.write_u32_be((2 + payload.length()).reinterpret_as_uint())
|
||||||
w.write_u8(b'\x14')
|
w.write_u8(b'\x14')
|
||||||
@@ -205,6 +235,22 @@ pub fn try_decode_peer_message(buf : Array[Byte]) -> PeerMessage? raise BtError
|
|||||||
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
||||||
Some(Cancel(idx, begin, len))
|
Some(Cancel(idx, begin, len))
|
||||||
}
|
}
|
||||||
|
b'\x0d' => {
|
||||||
|
let idx = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||||
|
Some(SuggestPiece(idx))
|
||||||
|
}
|
||||||
|
b'\x0e' => Some(HaveAll)
|
||||||
|
b'\x0f' => Some(HaveNone)
|
||||||
|
b'\x10' => {
|
||||||
|
let idx = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
||||||
|
let begin = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
||||||
|
let len = (r.read_u32_be() catch { e => raise Encoding(e) }).reinterpret_as_int()
|
||||||
|
Some(RejectRequest(idx, begin, len))
|
||||||
|
}
|
||||||
|
b'\x11' => {
|
||||||
|
let idx = r.read_u32_be() catch { e => raise Encoding(e) }
|
||||||
|
Some(AllowedFast(idx))
|
||||||
|
}
|
||||||
b'\x14' => {
|
b'\x14' => {
|
||||||
let ext_id = r.read_u8() catch { e => raise Encoding(e) }
|
let ext_id = r.read_u8() catch { e => raise Encoding(e) }
|
||||||
Some(Extended(ext_id, r.read_remaining()))
|
Some(Extended(ext_id, r.read_remaining()))
|
||||||
@@ -220,6 +266,7 @@ pub(all) struct RemoteExtensions {
|
|||||||
mut i2p_pex_id : Byte?
|
mut i2p_pex_id : Byte?
|
||||||
mut i2p_dht_id : Byte?
|
mut i2p_dht_id : Byte?
|
||||||
mut metadata_size : Int32?
|
mut metadata_size : Int32?
|
||||||
|
mut client_name : String
|
||||||
}
|
}
|
||||||
|
|
||||||
///|
|
///|
|
||||||
@@ -252,6 +299,7 @@ pub fn decode_ext_handshake(payload : Bytes) -> RemoteExtensions raise BtError {
|
|||||||
i2p_pex_id: None,
|
i2p_pex_id: None,
|
||||||
i2p_dht_id: None,
|
i2p_dht_id: None,
|
||||||
metadata_size: None,
|
metadata_size: None,
|
||||||
|
client_name: "",
|
||||||
}
|
}
|
||||||
match bdict_get(d, "m") {
|
match bdict_get(d, "m") {
|
||||||
Some(m) => {
|
Some(m) => {
|
||||||
@@ -275,6 +323,10 @@ pub fn decode_ext_handshake(payload : Bytes) -> RemoteExtensions raise BtError {
|
|||||||
res.metadata_size = Some(sz.to_int())
|
res.metadata_size = Some(sz.to_int())
|
||||||
_ => ()
|
_ => ()
|
||||||
}
|
}
|
||||||
|
match bdict_get_string(d, "v") {
|
||||||
|
Some(v) => res.client_name = v
|
||||||
|
None => ()
|
||||||
|
}
|
||||||
res
|
res
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -24,6 +24,10 @@ extension:
|
|||||||
appimage:
|
appimage:
|
||||||
python3 scripts/build_appimage.py
|
python3 scripts/build_appimage.py
|
||||||
|
|
||||||
|
# Build self-contained Android APK (arm64-v8a + x86_64) with embedded .i2p browser + router
|
||||||
|
apk:
|
||||||
|
python3 scripts/build_apk.py
|
||||||
|
|
||||||
# Run all MoonBit tests across wasm, js, and native targets
|
# Run all MoonBit tests across wasm, js, and native targets
|
||||||
test:
|
test:
|
||||||
moon test --target wasm
|
moon test --target wasm
|
||||||
|
|||||||
+10
-3
@@ -623,16 +623,23 @@ int32_t moon_i2p_net_mkdir_p(moonbit_bytes_t path_bytes, int32_t path_len) {
|
|||||||
char path[1024];
|
char path[1024];
|
||||||
memcpy(path, path_bytes, (size_t)path_len);
|
memcpy(path, path_bytes, (size_t)path_len);
|
||||||
path[path_len] = '\0';
|
path[path_len] = '\0';
|
||||||
|
struct stat st;
|
||||||
for (int32_t i = 1; i < path_len; i++) {
|
for (int32_t i = 1; i < path_len; i++) {
|
||||||
if (path[i] == '/') {
|
if (path[i] == '/') {
|
||||||
path[i] = '\0';
|
path[i] = '\0';
|
||||||
if (mkdir(path, 0755) < 0 && errno != EEXIST) {
|
if (!(stat(path, &st) == 0 && S_ISDIR(st.st_mode))) {
|
||||||
net_set_error(strerror(errno));
|
if (mkdir(path, 0755) < 0 &&
|
||||||
return -1;
|
errno != EEXIST && errno != EISDIR && errno != EACCES && errno != EROFS) {
|
||||||
|
net_set_error(strerror(errno));
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
path[i] = '/';
|
path[i] = '/';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
if (mkdir(path, 0755) < 0 && errno != EEXIST) {
|
if (mkdir(path, 0755) < 0 && errno != EEXIST) {
|
||||||
net_set_error(strerror(errno));
|
net_set_error(strerror(errno));
|
||||||
return -1;
|
return -1;
|
||||||
|
|||||||
+52
-2
@@ -345,11 +345,53 @@ fn Router::build_api_torrents_json(self : Router) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut active_peers = 0
|
let mut active_peers = 0
|
||||||
for p in t.peers {
|
let mut unchoked_peers = 0
|
||||||
|
let mut seeder_peers = 0
|
||||||
|
let peers_sb = StringBuilder()
|
||||||
|
peers_sb.write_char('[')
|
||||||
|
for pi = 0; pi < t.peers.length(); pi = pi + 1 {
|
||||||
|
let p = t.peers[pi]
|
||||||
|
if pi > 0 {
|
||||||
|
peers_sb.write_char(',')
|
||||||
|
}
|
||||||
|
let mut p_pieces = 0
|
||||||
|
for hp in p.peer_bitfield {
|
||||||
|
if hp {
|
||||||
|
p_pieces += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
if p.state == 3 {
|
if p.state == 3 {
|
||||||
active_peers += 1
|
active_peers += 1
|
||||||
|
if !p.peer_choking {
|
||||||
|
unchoked_peers += 1
|
||||||
|
}
|
||||||
|
if p_pieces > 0 || p.peer_have_all {
|
||||||
|
seeder_peers += 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let pb32 = bt_short_b32(p.peer_hash)
|
||||||
|
peers_sb.write_char('{')
|
||||||
|
peers_sb.write_string("\"b32\":\"\{api_json_escape(pb32)}\",")
|
||||||
|
peers_sb.write_string("\"state\":\{p.state},")
|
||||||
|
peers_sb.write_string("\"choking\":\{p.peer_choking},")
|
||||||
|
peers_sb.write_string("\"pieces\":\{p_pieces},")
|
||||||
|
peers_sb.write_string("\"in_flight\":\{p.in_flight.length()},")
|
||||||
|
peers_sb.write_string("\"blocks_recv\":\{p.blocks_recv},")
|
||||||
|
peers_sb.write_string(
|
||||||
|
"\"client\":\"\{api_json_escape(p.remote_client)}\"",
|
||||||
|
)
|
||||||
|
peers_sb.write_char('}')
|
||||||
|
}
|
||||||
|
peers_sb.write_char(']')
|
||||||
|
let mut inflight_blocks = 0
|
||||||
|
for pbuf in t.inflight_pieces {
|
||||||
|
for g in pbuf.got_blocks {
|
||||||
|
if g {
|
||||||
|
inflight_blocks += 1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let inflight_bytes = inflight_blocks.to_int64() * 16384L
|
||||||
let state_str = if t.error.length() > 0 {
|
let state_str = if t.error.length() > 0 {
|
||||||
"error"
|
"error"
|
||||||
} else if t.paused {
|
} else if t.paused {
|
||||||
@@ -380,12 +422,20 @@ fn Router::build_api_torrents_json(self : Router) -> String {
|
|||||||
sb.write_string("\"uploaded_bytes\":\{t.uploaded_bytes},")
|
sb.write_string("\"uploaded_bytes\":\{t.uploaded_bytes},")
|
||||||
sb.write_string("\"have_pieces\":\{have_cnt},")
|
sb.write_string("\"have_pieces\":\{have_cnt},")
|
||||||
sb.write_string("\"num_pieces\":\{num_pieces},")
|
sb.write_string("\"num_pieces\":\{num_pieces},")
|
||||||
|
sb.write_string("\"inflight_blocks\":\{inflight_blocks},")
|
||||||
|
sb.write_string("\"inflight_bytes\":\{inflight_bytes},")
|
||||||
sb.write_string("\"progress_pct\":\{progress_pct},")
|
sb.write_string("\"progress_pct\":\{progress_pct},")
|
||||||
sb.write_string("\"known_peers\":\{t.known_peers.length()},")
|
sb.write_string("\"known_peers\":\{t.known_peers.length()},")
|
||||||
sb.write_string("\"connected_peers\":\{active_peers},")
|
sb.write_string("\"connected_peers\":\{active_peers},")
|
||||||
|
sb.write_string("\"unchoked_peers\":\{unchoked_peers},")
|
||||||
|
sb.write_string("\"seeder_peers\":\{seeder_peers},")
|
||||||
sb.write_string("\"trackers\":\{t.trackers.length()},")
|
sb.write_string("\"trackers\":\{t.trackers.length()},")
|
||||||
|
sb.write_string(
|
||||||
|
"\"last_tracker_status\":\"\{api_json_escape(t.last_tracker_status)}\",",
|
||||||
|
)
|
||||||
sb.write_string("\"download_dir\":\"\{api_json_escape(t.download_dir)}\",")
|
sb.write_string("\"download_dir\":\"\{api_json_escape(t.download_dir)}\",")
|
||||||
sb.write_string("\"error\":\"\{api_json_escape(t.error)}\"")
|
sb.write_string("\"error\":\"\{api_json_escape(t.error)}\",")
|
||||||
|
sb.write_string("\"peers\":\{peers_sb.to_string()}")
|
||||||
sb.write_char('}')
|
sb.write_char('}')
|
||||||
}
|
}
|
||||||
sb.write_string("]}")
|
sb.write_string("]}")
|
||||||
|
|||||||
+533
-44
File diff suppressed because it is too large.
Load diff
Executable
+334
@@ -0,0 +1,334 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build a self-contained MoonI2P-Browser Android APK (arm64-v8a + x86_64).
|
||||||
|
|
||||||
|
Compiles MoonBit cmd/router (C backend) + MoonBit runtime + ntcp2_net POSIX
|
||||||
|
stubs directly with Android NDK clang into native PIE executables packaged under
|
||||||
|
lib/<abi>/libmoon_i2p_router.so, compiles the Java WebView + ForegroundService
|
||||||
|
shell using Android SDK build-tools (no Gradle required), aligns, and signs.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||||
|
ANDROID_SRC = REPO_ROOT / "android" / "app" / "src" / "main"
|
||||||
|
CACHE_DIR = REPO_ROOT / ".cache" / "android"
|
||||||
|
BUILD_DIR = CACHE_DIR / "build"
|
||||||
|
DIST_DIR = REPO_ROOT / "dist"
|
||||||
|
OUTPUT_APK = DIST_DIR / "MoonI2P-Browser-android.apk"
|
||||||
|
|
||||||
|
ICON_SVG = REPO_ROOT / "extensions" / "firefox-i2p-torrent" / "icon.svg"
|
||||||
|
|
||||||
|
|
||||||
|
def run(cmd, cwd=None):
|
||||||
|
print(f"[build_apk] $ {' '.join(map(str, cmd))}")
|
||||||
|
return subprocess.run(cmd, cwd=str(cwd or REPO_ROOT), check=True)
|
||||||
|
|
||||||
|
|
||||||
|
def find_sdk_paths():
|
||||||
|
sdk_root = Path(
|
||||||
|
os.environ.get("ANDROID_HOME")
|
||||||
|
or os.environ.get("ANDROID_SDK_ROOT")
|
||||||
|
or (Path.home() / "Android" / "Sdk")
|
||||||
|
)
|
||||||
|
if not (sdk_root / "platforms").is_dir():
|
||||||
|
fallback = Path.home() / "Android" / "Sdk"
|
||||||
|
if (fallback / "platforms").is_dir():
|
||||||
|
sdk_root = fallback
|
||||||
|
|
||||||
|
build_tools_root = sdk_root / "build-tools"
|
||||||
|
if not build_tools_root.is_dir():
|
||||||
|
raise FileNotFoundError(f"Android SDK build-tools not found under {sdk_root}")
|
||||||
|
bt_versions = sorted(build_tools_root.iterdir(), key=lambda p: p.name)
|
||||||
|
build_tools = bt_versions[-1]
|
||||||
|
|
||||||
|
platforms_root = sdk_root / "platforms"
|
||||||
|
plat_versions = sorted(platforms_root.iterdir(), key=lambda p: p.name)
|
||||||
|
android_jar = plat_versions[-1] / "android.jar"
|
||||||
|
if not android_jar.is_file():
|
||||||
|
raise FileNotFoundError(f"android.jar not found under {platforms_root}")
|
||||||
|
|
||||||
|
ndk_root = sdk_root / "ndk"
|
||||||
|
ndk_versions = sorted(ndk_root.iterdir(), key=lambda p: p.name)
|
||||||
|
ndk_bin = ndk_versions[-1] / "toolchains" / "llvm" / "prebuilt" / "linux-x86_64" / "bin"
|
||||||
|
if not ndk_bin.is_dir():
|
||||||
|
raise FileNotFoundError(f"Android NDK llvm toolchain not found under {ndk_root}")
|
||||||
|
|
||||||
|
java_home = Path("/usr/lib/jvm/java-17-openjdk")
|
||||||
|
if (java_home / "bin" / "javac").is_file():
|
||||||
|
javac_bin = str(java_home / "bin" / "javac")
|
||||||
|
keytool_bin = str(java_home / "bin" / "keytool")
|
||||||
|
java_bin = str(java_home / "bin" / "java")
|
||||||
|
else:
|
||||||
|
javac_bin = shutil.which("javac") or "javac"
|
||||||
|
keytool_bin = shutil.which("keytool") or "keytool"
|
||||||
|
java_bin = shutil.which("java") or "java"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"sdk": sdk_root,
|
||||||
|
"build_tools": build_tools,
|
||||||
|
"android_jar": android_jar,
|
||||||
|
"ndk_bin": ndk_bin,
|
||||||
|
"javac": javac_bin,
|
||||||
|
"keytool": keytool_bin,
|
||||||
|
"java": java_bin,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def render_icons(res_dir: Path):
|
||||||
|
sizes = [
|
||||||
|
("mipmap-mdpi", 48),
|
||||||
|
("mipmap-hdpi", 72),
|
||||||
|
("mipmap-xhdpi", 96),
|
||||||
|
("mipmap-xxhdpi", 144),
|
||||||
|
("mipmap-xxxhdpi", 192),
|
||||||
|
]
|
||||||
|
for folder, px in sizes:
|
||||||
|
out_dir = res_dir / folder
|
||||||
|
out_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
out_png = out_dir / "ic_launcher.png"
|
||||||
|
if shutil.which("rsvg-convert"):
|
||||||
|
run(["rsvg-convert", "-w", str(px), "-h", str(px), str(ICON_SVG), "-o", str(out_png)])
|
||||||
|
elif shutil.which("magick"):
|
||||||
|
run(["magick", "-background", "none", str(ICON_SVG), "-resize", f"{px}x{px}", str(out_png)])
|
||||||
|
else:
|
||||||
|
raise RuntimeError("Need rsvg-convert or magick to render launcher icons")
|
||||||
|
|
||||||
|
|
||||||
|
def build_native_router_abi(ndk_bin: Path, compiler_name: str, abi: str, out_dir: Path) -> Path:
|
||||||
|
clang = ndk_bin / compiler_name
|
||||||
|
strip = ndk_bin / "llvm-strip"
|
||||||
|
if not clang.is_file():
|
||||||
|
raise FileNotFoundError(f"Missing NDK clang: {clang}")
|
||||||
|
|
||||||
|
moon_home = Path.home() / ".moon"
|
||||||
|
moon_inc = moon_home / "include"
|
||||||
|
moon_rt = moon_home / "lib" / "runtime"
|
||||||
|
|
||||||
|
router_c = REPO_ROOT / "_build" / "native" / "release" / "build" / "cmd" / "router" / "router.c"
|
||||||
|
net_stub_c = REPO_ROOT / "ntcp2_net" / "net_stub.c"
|
||||||
|
c_sources = [
|
||||||
|
router_c,
|
||||||
|
moon_rt / "runtime.c",
|
||||||
|
moon_rt / "backtrace.c",
|
||||||
|
moon_rt / "utf.c",
|
||||||
|
moon_rt / "env.c",
|
||||||
|
net_stub_c,
|
||||||
|
]
|
||||||
|
|
||||||
|
abi_dir = out_dir / "lib" / abi
|
||||||
|
abi_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
out_so = abi_dir / "libmoon_i2p_router.so"
|
||||||
|
|
||||||
|
compat_hdr = out_dir / "android_compat.h"
|
||||||
|
compat_hdr.write_text(
|
||||||
|
"#pragma once\n"
|
||||||
|
"#include <stdlib.h>\n"
|
||||||
|
"#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 28)\n"
|
||||||
|
"static inline int moon_i2p_android_getentropy(void *buf, size_t buflen) {\n"
|
||||||
|
" arc4random_buf(buf, buflen);\n"
|
||||||
|
" return 0;\n"
|
||||||
|
"}\n"
|
||||||
|
"#define getentropy(buf, len) moon_i2p_android_getentropy((buf), (len))\n"
|
||||||
|
"#endif\n",
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
str(clang),
|
||||||
|
"-O2",
|
||||||
|
"-fPIE",
|
||||||
|
"-pie",
|
||||||
|
"-DMOONBIT_ALLOCATOR=MOONBIT_ALLOCATOR_SYSTEM",
|
||||||
|
"-DMOONBIT_NATIVE_EXIT_ON_PANIC",
|
||||||
|
"-Wno-unused-value",
|
||||||
|
"-Wno-parentheses",
|
||||||
|
"-Wno-deprecated-declarations",
|
||||||
|
f"-I{moon_inc}",
|
||||||
|
"-include",
|
||||||
|
str(compat_hdr),
|
||||||
|
*[str(c) for c in c_sources],
|
||||||
|
"-lm",
|
||||||
|
"-o",
|
||||||
|
str(out_so),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
if strip.is_file():
|
||||||
|
run([str(strip), "--strip-unneeded", str(out_so)])
|
||||||
|
os.chmod(out_so, os.stat(out_so).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
||||||
|
return out_so
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_debug_keystore(keytool_bin: str) -> Path:
|
||||||
|
ks = CACHE_DIR / "debug.keystore"
|
||||||
|
if ks.is_file():
|
||||||
|
return ks
|
||||||
|
ks.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
keytool_bin,
|
||||||
|
"-genkeypair",
|
||||||
|
"-v",
|
||||||
|
"-keystore",
|
||||||
|
str(ks),
|
||||||
|
"-storepass",
|
||||||
|
"android",
|
||||||
|
"-alias",
|
||||||
|
"androiddebugkey",
|
||||||
|
"-keypass",
|
||||||
|
"android",
|
||||||
|
"-keyalg",
|
||||||
|
"RSA",
|
||||||
|
"-keysize",
|
||||||
|
"2048",
|
||||||
|
"-validity",
|
||||||
|
"10000",
|
||||||
|
"-dname",
|
||||||
|
"CN=MoonI2P Debug,O=MoonI2P,C=US",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
return ks
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tools = find_sdk_paths()
|
||||||
|
DIST_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
if BUILD_DIR.exists():
|
||||||
|
shutil.rmtree(BUILD_DIR)
|
||||||
|
BUILD_DIR.mkdir(parents=True)
|
||||||
|
|
||||||
|
# 1. Generate release C sources for cmd/router via MoonBit compiler
|
||||||
|
run(["moon", "build", "--target", "native", "--release", "cmd/router"])
|
||||||
|
|
||||||
|
# 2. Cross-compile MoonBit router ELF PIE binaries for Android arm64-v8a & x86_64
|
||||||
|
native_stage = BUILD_DIR / "native"
|
||||||
|
so_arm64 = build_native_router_abi(tools["ndk_bin"], "aarch64-linux-android24-clang", "arm64-v8a", native_stage)
|
||||||
|
so_x86_64 = build_native_router_abi(tools["ndk_bin"], "x86_64-linux-android24-clang", "x86_64", native_stage)
|
||||||
|
|
||||||
|
# 3. Prepare Android resources & compile via aapt2
|
||||||
|
res_stage = BUILD_DIR / "res"
|
||||||
|
shutil.copytree(ANDROID_SRC / "res", res_stage)
|
||||||
|
render_icons(res_stage)
|
||||||
|
|
||||||
|
flat_zip = BUILD_DIR / "resources.zip"
|
||||||
|
run([str(tools["build_tools"] / "aapt2"), "compile", "--dir", str(res_stage), "-o", str(flat_zip)])
|
||||||
|
|
||||||
|
java_gen = BUILD_DIR / "gen"
|
||||||
|
java_gen.mkdir(parents=True)
|
||||||
|
base_apk = BUILD_DIR / "base.apk"
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
str(tools["build_tools"] / "aapt2"),
|
||||||
|
"link",
|
||||||
|
"-o",
|
||||||
|
str(base_apk),
|
||||||
|
"-I",
|
||||||
|
str(tools["android_jar"]),
|
||||||
|
"--manifest",
|
||||||
|
str(ANDROID_SRC / "AndroidManifest.xml"),
|
||||||
|
"--min-sdk-version",
|
||||||
|
"24",
|
||||||
|
"--target-sdk-version",
|
||||||
|
"34",
|
||||||
|
"--java",
|
||||||
|
str(java_gen),
|
||||||
|
"--auto-add-overlay",
|
||||||
|
str(flat_zip),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
# 4. Compile Java sources -> class files -> classes.dex via d8
|
||||||
|
classes_dir = BUILD_DIR / "classes"
|
||||||
|
classes_dir.mkdir(parents=True)
|
||||||
|
java_files = list(java_gen.rglob("*.java")) + list((ANDROID_SRC / "java").rglob("*.java"))
|
||||||
|
run(
|
||||||
|
[
|
||||||
|
tools["javac"],
|
||||||
|
"--release",
|
||||||
|
"11",
|
||||||
|
"-encoding",
|
||||||
|
"UTF-8",
|
||||||
|
"-classpath",
|
||||||
|
str(tools["android_jar"]),
|
||||||
|
"-d",
|
||||||
|
str(classes_dir),
|
||||||
|
*[str(f) for f in sorted(java_files)],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
dex_dir = BUILD_DIR / "dex"
|
||||||
|
dex_dir.mkdir(parents=True)
|
||||||
|
class_files = sorted(classes_dir.rglob("*.class"))
|
||||||
|
d8_env = os.environ.copy()
|
||||||
|
java_bin_dir = str(Path(tools["javac"]).parent)
|
||||||
|
d8_env["PATH"] = f"{java_bin_dir}:{d8_env.get('PATH', '')}"
|
||||||
|
print(f"[build_apk] $ d8 --min-api 24 ... ({len(class_files)} class files)")
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
str(tools["build_tools"] / "d8"),
|
||||||
|
"--min-api",
|
||||||
|
"24",
|
||||||
|
"--lib",
|
||||||
|
str(tools["android_jar"]),
|
||||||
|
"--output",
|
||||||
|
str(dex_dir),
|
||||||
|
*[str(c) for c in class_files],
|
||||||
|
],
|
||||||
|
env=d8_env,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 5. Merge resources, classes.dex, assets, and uncompressed native libs into unaligned APK
|
||||||
|
unaligned_apk = BUILD_DIR / "unaligned.apk"
|
||||||
|
with zipfile.ZipFile(base_apk, "r") as zin, zipfile.ZipFile(unaligned_apk, "w") as zout:
|
||||||
|
for item in zin.infolist():
|
||||||
|
compress = zipfile.ZIP_STORED if item.filename == "resources.arsc" else zipfile.ZIP_DEFLATED
|
||||||
|
zout.writestr(item.filename, zin.read(item.filename), compress_type=compress)
|
||||||
|
zout.write(dex_dir / "classes.dex", "classes.dex", compress_type=zipfile.ZIP_DEFLATED)
|
||||||
|
for asset in sorted((ANDROID_SRC / "assets").rglob("*")):
|
||||||
|
if asset.is_file():
|
||||||
|
rel = asset.relative_to(ANDROID_SRC).as_posix()
|
||||||
|
zout.write(asset, rel, compress_type=zipfile.ZIP_DEFLATED)
|
||||||
|
# Keep native executables uncompressed for Android package manager alignment
|
||||||
|
zout.write(so_arm64, "lib/arm64-v8a/libmoon_i2p_router.so", compress_type=zipfile.ZIP_STORED)
|
||||||
|
zout.write(so_x86_64, "lib/x86_64/libmoon_i2p_router.so", compress_type=zipfile.ZIP_STORED)
|
||||||
|
|
||||||
|
# 6. Zipalign and sign with apksigner
|
||||||
|
aligned_apk = BUILD_DIR / "aligned.apk"
|
||||||
|
run([str(tools["build_tools"] / "zipalign"), "-f", "-p", "4", str(unaligned_apk), str(aligned_apk)])
|
||||||
|
|
||||||
|
keystore = ensure_debug_keystore(tools["keytool"])
|
||||||
|
tmp_signed = OUTPUT_APK.with_suffix(".apk.part")
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
str(tools["build_tools"] / "apksigner"),
|
||||||
|
"sign",
|
||||||
|
"--ks",
|
||||||
|
str(keystore),
|
||||||
|
"--ks-pass",
|
||||||
|
"pass:android",
|
||||||
|
"--ks-key-alias",
|
||||||
|
"androiddebugkey",
|
||||||
|
"--key-pass",
|
||||||
|
"pass:android",
|
||||||
|
"--out",
|
||||||
|
str(tmp_signed),
|
||||||
|
str(aligned_apk),
|
||||||
|
],
|
||||||
|
env=d8_env,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
tmp_signed.replace(OUTPUT_APK)
|
||||||
|
size_mb = OUTPUT_APK.stat().st_size / (1024 * 1024)
|
||||||
|
print(f"[build_apk] Built {OUTPUT_APK} ({size_mb:.1f} MiB)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
+65
-29
@@ -101,32 +101,62 @@ fn StreamConnection::queue_packet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
///|
|
///|
|
||||||
fn StreamConnection::current_nacks(self : StreamConnection) -> Array[UInt32] {
|
fn StreamConnection::wire_ack_and_nacks(
|
||||||
|
self : StreamConnection,
|
||||||
|
) -> (UInt32, Array[UInt32]) {
|
||||||
if self.ooo_recv.length() == 0 {
|
if self.ooo_recv.length() == 0 {
|
||||||
return []
|
return (self.ack_through, [])
|
||||||
}
|
}
|
||||||
let mut max_seen = self.next_recv_seq
|
let seqs : Array[UInt32] = []
|
||||||
for entry in self.ooo_recv {
|
for entry in self.ooo_recv {
|
||||||
if entry.0 > max_seen {
|
let s = entry.0
|
||||||
max_seen = entry.0
|
if s < self.next_recv_seq {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
}
|
let mut dup = false
|
||||||
let nacks : Array[UInt32] = []
|
for existing in seqs {
|
||||||
let mut s = self.next_recv_seq
|
if existing == s {
|
||||||
while s < max_seen && nacks.length() < 32 {
|
dup = true
|
||||||
let mut found = false
|
|
||||||
for entry in self.ooo_recv {
|
|
||||||
if entry.0 == s {
|
|
||||||
found = true
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !found {
|
if !dup {
|
||||||
nacks.push(s)
|
seqs.push(s)
|
||||||
}
|
}
|
||||||
s = s + 1U
|
|
||||||
}
|
}
|
||||||
nacks
|
if seqs.length() == 0 {
|
||||||
|
return (self.ack_through, [])
|
||||||
|
}
|
||||||
|
for i = 1; i < seqs.length(); i = i + 1 {
|
||||||
|
let key = seqs[i]
|
||||||
|
let mut j = i
|
||||||
|
while j > 0 && seqs[j - 1] > key {
|
||||||
|
seqs[j] = seqs[j - 1]
|
||||||
|
j -= 1
|
||||||
|
}
|
||||||
|
seqs[j] = key
|
||||||
|
}
|
||||||
|
let mut best_ack = self.ack_through
|
||||||
|
let nacks : Array[UInt32] = []
|
||||||
|
let mut cursor = self.next_recv_seq
|
||||||
|
for s in seqs {
|
||||||
|
if s < cursor {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
let gap = s - cursor
|
||||||
|
if gap <= 32U && nacks.length() + gap.reinterpret_as_int() <= 32 {
|
||||||
|
let mut m = cursor
|
||||||
|
while m < s {
|
||||||
|
nacks.push(m)
|
||||||
|
m = m + 1U
|
||||||
|
}
|
||||||
|
best_ack = s
|
||||||
|
cursor = s + 1U
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(best_ack, nacks)
|
||||||
}
|
}
|
||||||
|
|
||||||
///|
|
///|
|
||||||
@@ -354,12 +384,13 @@ fn StreamConnection::send_ack(
|
|||||||
self : StreamConnection,
|
self : StreamConnection,
|
||||||
now_ms : UInt64,
|
now_ms : UInt64,
|
||||||
) -> Unit raise StreamingError {
|
) -> Unit raise StreamingError {
|
||||||
|
let (wire_ack, wire_nacks) = self.wire_ack_and_nacks()
|
||||||
let ack_pkt : StreamingPacket = {
|
let ack_pkt : StreamingPacket = {
|
||||||
send_stream_id: self.remote_stream_id,
|
send_stream_id: self.remote_stream_id,
|
||||||
recv_stream_id: self.local_stream_id,
|
recv_stream_id: self.local_stream_id,
|
||||||
sequence_num: 0U,
|
sequence_num: 0U,
|
||||||
ack_through: self.ack_through,
|
ack_through: wire_ack,
|
||||||
nacks: self.current_nacks(),
|
nacks: wire_nacks,
|
||||||
resend_delay: b'\x00',
|
resend_delay: b'\x00',
|
||||||
flags: 0U,
|
flags: 0U,
|
||||||
delay_requested: None,
|
delay_requested: None,
|
||||||
@@ -479,8 +510,7 @@ pub fn StreamConnection::on_packet(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let seq = pkt.sequence_num
|
let seq = pkt.sequence_num
|
||||||
let has_data = pkt.payload.length() > 0 || (pkt.flags & flag_close) != 0U
|
if seq > 0U && (pkt.flags & flag_synchronize) == 0U {
|
||||||
if seq > 0U && has_data {
|
|
||||||
if seq == self.next_recv_seq {
|
if seq == self.next_recv_seq {
|
||||||
for i = 0; i < pkt.payload.length(); i = i + 1 {
|
for i = 0; i < pkt.payload.length(); i = i + 1 {
|
||||||
self.recv_buf.push(pkt.payload[i])
|
self.recv_buf.push(pkt.payload[i])
|
||||||
@@ -513,10 +543,14 @@ pub fn StreamConnection::on_packet(
|
|||||||
self.send_ack(now_ms)
|
self.send_ack(now_ms)
|
||||||
acked = true
|
acked = true
|
||||||
}
|
}
|
||||||
if !acked && (pkt.flags & flag_delay_requested) != 0U {
|
if !acked {
|
||||||
match pkt.delay_requested {
|
if (pkt.flags & flag_echo) != 0U {
|
||||||
Some(d) if d == 0U => self.send_ack(now_ms)
|
self.send_ack(now_ms)
|
||||||
_ => ()
|
} else if (pkt.flags & flag_delay_requested) != 0U {
|
||||||
|
match pkt.delay_requested {
|
||||||
|
Some(d) if d == 0U => self.send_ack(now_ms)
|
||||||
|
_ => ()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -543,12 +577,13 @@ pub fn StreamConnection::write(
|
|||||||
let seq = self.next_send_seq
|
let seq = self.next_send_seq
|
||||||
self.next_send_seq = seq + 1U
|
self.next_send_seq = seq + 1U
|
||||||
let flags = if self.has_recv_syn { 0U } else { flag_no_ack }
|
let flags = if self.has_recv_syn { 0U } else { flag_no_ack }
|
||||||
|
let (wire_ack, wire_nacks) = self.wire_ack_and_nacks()
|
||||||
let pkt : StreamingPacket = {
|
let pkt : StreamingPacket = {
|
||||||
send_stream_id: self.remote_stream_id,
|
send_stream_id: self.remote_stream_id,
|
||||||
recv_stream_id: self.local_stream_id,
|
recv_stream_id: self.local_stream_id,
|
||||||
sequence_num: seq,
|
sequence_num: seq,
|
||||||
ack_through: self.ack_through,
|
ack_through: wire_ack,
|
||||||
nacks: self.current_nacks(),
|
nacks: wire_nacks,
|
||||||
resend_delay: b'\x00',
|
resend_delay: b'\x00',
|
||||||
flags,
|
flags,
|
||||||
delay_requested: None,
|
delay_requested: None,
|
||||||
@@ -592,12 +627,13 @@ pub fn StreamConnection::close(
|
|||||||
}
|
}
|
||||||
let seq = self.next_send_seq
|
let seq = self.next_send_seq
|
||||||
self.next_send_seq = seq + 1U
|
self.next_send_seq = seq + 1U
|
||||||
|
let (wire_ack, wire_nacks) = self.wire_ack_and_nacks()
|
||||||
let pkt : StreamingPacket = {
|
let pkt : StreamingPacket = {
|
||||||
send_stream_id: self.remote_stream_id,
|
send_stream_id: self.remote_stream_id,
|
||||||
recv_stream_id: self.local_stream_id,
|
recv_stream_id: self.local_stream_id,
|
||||||
sequence_num: seq,
|
sequence_num: seq,
|
||||||
ack_through: self.ack_through,
|
ack_through: wire_ack,
|
||||||
nacks: self.current_nacks(),
|
nacks: wire_nacks,
|
||||||
resend_delay: b'\x00',
|
resend_delay: b'\x00',
|
||||||
flags: flag_close |
|
flags: flag_close |
|
||||||
flag_signature_included |
|
flag_signature_included |
|
||||||
|
|||||||
@@ -353,3 +353,80 @@ test "StreamManager dispatches protocol 17 repliable and protocol 18 raw datagra
|
|||||||
assert_eq(bob_mgr.incoming_raw_dgrams[0].0.from_port, 6882U)
|
assert_eq(bob_mgr.incoming_raw_dgrams[0].0.from_port, 6882U)
|
||||||
assert_eq(bob_mgr.incoming_raw_dgrams[0].1, b"dht-reply")
|
assert_eq(bob_mgr.incoming_raw_dgrams[0].1, b"dht-reply")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
///|
|
||||||
|
test "Streaming SACK wire_ack_and_nacks invariant on out-of-order and large gaps" {
|
||||||
|
let (alice_dest, alice_seed) = make_test_identity(b'\x71')
|
||||||
|
let (bob_dest, bob_seed) = make_test_identity(b'\x72')
|
||||||
|
let alice_mgr = @streaming.StreamManager::new(
|
||||||
|
alice_dest,
|
||||||
|
alice_seed,
|
||||||
|
initial_stream_id=500U,
|
||||||
|
)
|
||||||
|
let bob_mgr = @streaming.StreamManager::new(
|
||||||
|
bob_dest,
|
||||||
|
bob_seed,
|
||||||
|
initial_stream_id=600U,
|
||||||
|
)
|
||||||
|
let a_stream = alice_mgr.connect(bob_dest.hash(), 1000UL)
|
||||||
|
for msg in a_stream.drain_outbound() {
|
||||||
|
let _ = bob_mgr.handle_incoming_i2cp(msg, 1005UL)
|
||||||
|
}
|
||||||
|
let b_stream = match bob_mgr.accept_next() {
|
||||||
|
Some(s) => s
|
||||||
|
None => fail("expected accept_next")
|
||||||
|
}
|
||||||
|
for msg in b_stream.drain_outbound() {
|
||||||
|
let _ = alice_mgr.handle_incoming_i2cp(msg, 1010UL)
|
||||||
|
}
|
||||||
|
let _ = alice_mgr.streams[0].drain_outbound()
|
||||||
|
|
||||||
|
fn make_data_pkt(seq : UInt32, payload : Bytes) -> Bytes {
|
||||||
|
let p : @streaming.StreamingPacket = {
|
||||||
|
send_stream_id: 600U,
|
||||||
|
recv_stream_id: 500U,
|
||||||
|
sequence_num: seq,
|
||||||
|
ack_through: 0U,
|
||||||
|
nacks: [],
|
||||||
|
resend_delay: b'\x00',
|
||||||
|
flags: 0U,
|
||||||
|
delay_requested: None,
|
||||||
|
from_dest: None,
|
||||||
|
max_packet_size: None,
|
||||||
|
offline_sig: None,
|
||||||
|
signature: None,
|
||||||
|
payload,
|
||||||
|
}
|
||||||
|
try! @streaming.encode_i2cp_streaming(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliver seq 1, skip 2, deliver 3 and 4 -> ack_through must be 4, nacks == [2]
|
||||||
|
let _ = bob_mgr.handle_incoming_i2cp(make_data_pkt(1U, b"a"), 1020UL)
|
||||||
|
let _ = b_stream.drain_outbound()
|
||||||
|
let _ = bob_mgr.handle_incoming_i2cp(make_data_pkt(3U, b"c"), 1021UL)
|
||||||
|
let acks1 = b_stream.drain_outbound()
|
||||||
|
let (_, ack_dec1) = @streaming.decode_i2cp_streaming(acks1[0])
|
||||||
|
assert_eq(ack_dec1.ack_through, 3U)
|
||||||
|
assert_eq(ack_dec1.nacks, [2U])
|
||||||
|
|
||||||
|
let _ = bob_mgr.handle_incoming_i2cp(make_data_pkt(4U, b"d"), 1022UL)
|
||||||
|
let acks2 = b_stream.drain_outbound()
|
||||||
|
let (_, ack_dec2) = @streaming.decode_i2cp_streaming(acks2[0])
|
||||||
|
assert_eq(ack_dec2.ack_through, 4U)
|
||||||
|
assert_eq(ack_dec2.nacks, [2U])
|
||||||
|
|
||||||
|
// Deliver seq 50 (gap from cursor=5 to 50 is 45 > 32): ack_through must stay 4 and nacks stay [2]
|
||||||
|
let _ = bob_mgr.handle_incoming_i2cp(make_data_pkt(50U, b"z"), 1023UL)
|
||||||
|
let acks3 = b_stream.drain_outbound()
|
||||||
|
let (_, ack_dec3) = @streaming.decode_i2cp_streaming(acks3[0])
|
||||||
|
assert_eq(ack_dec3.ack_through, 4U)
|
||||||
|
assert_eq(ack_dec3.nacks, [2U])
|
||||||
|
|
||||||
|
// Empty seq=2 fills the gap -> drains 2,3,4 cleanly
|
||||||
|
let _ = bob_mgr.handle_incoming_i2cp(make_data_pkt(2U, b"b"), 1024UL)
|
||||||
|
let acks4 = b_stream.drain_outbound()
|
||||||
|
let (_, ack_dec4) = @streaming.decode_i2cp_streaming(acks4[0])
|
||||||
|
assert_eq(ack_dec4.ack_through, 4U)
|
||||||
|
assert_eq(ack_dec4.nacks, [])
|
||||||
|
assert_eq(b_stream.read_available(), b"abcd")
|
||||||
|
}
|
||||||
Reference in new issue
Block a user