feat: add Android APK with embedded I2P browser and torrent manager
check / check (ubuntu-latest) (push) Failing after 26s
check / check (macos-latest) (push) Failing after 29s
check / check (windows-latest) (push) Failing after 26s

- 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:
nandi committed 2026-11-28 17:55:42 -08:00
1 parent fbe6818c4e
commit 7a1b4325f9
16 files changed
+3041 -78

No files matched your search

+50
View File
@@ -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>
+420
View File
@@ -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 &amp; 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 &amp; 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) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;",
})[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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
}
@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>