diff --git a/README.md b/README.md index c586cda..5083e51 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,10 @@ just proxy just 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: # Installs native messaging host (~/.mozilla & ~/.config/mozilla) and packs .xpi: just extension diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..cb1cebd --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/assets/manager.html b/android/app/src/main/assets/manager.html new file mode 100644 index 0000000..b6b6637 --- /dev/null +++ b/android/app/src/main/assets/manager.html @@ -0,0 +1,420 @@ + + + + + + Moon I2P Torrents & DHT + + + +
+

+ moon-i2p Router Status + Starting... +

+
+
+
NetDB / Tunnels
+
--
+
+
+
Download Folder
+
--
+
+
+
+
Torrent Session .b32.i2p
+
+
--
+ +
+
+
+ +
+

+ I2P Kademlia DHT (Proto 17 / 18) + 0 nodes +

+
+
+
DHT Node ID (20B)
+
--
+
+
+
Sent / Recv / Peers
+
0 / 0 / 0
+
+
+
+ + + +
+
No DHT nodes yet.
+
+ +
+

Add I2P Torrent

+
+ + +
+
+ + +
+
+
+ +
+

+ Active Torrents + 0 +

+
No torrents added yet.
+
+ +
+

+ Diagnostics & Verbose Logs + + + + +

+
Loading diagnostics...
+
+ + + + diff --git a/android/app/src/main/java/org/mooni2p/browser/MainActivity.java b/android/app/src/main/java/org/mooni2p/browser/MainActivity.java new file mode 100644 index 0000000..c688fea --- /dev/null +++ b/android/app/src/main/java/org/mooni2p/browser/MainActivity.java @@ -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 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 = "" + + "" + + "" + + "" + code + " " + reason + "" + + "

" + code + " " + reason + "

" + + "

" + escapeSimple(detail) + "

Refreshing automatically every 3s... " + + escapeSimple(RouterService.getStatusText()) + " · Tap DIAG above to inspect/copy logs.

"; + Map 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 reqHdrs = request.getRequestHeaders(); + if (reqHdrs != null) { + for (Map.Entry 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 outHdrs = new HashMap<>(); + for (Map.Entry> e : conn.getHeaderFields().entrySet()) { + String k = e.getKey(); + if (k == null || k.equalsIgnoreCase("Transfer-Encoding") || k.equalsIgnoreCase("Connection")) { + continue; + } + List 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() + ")." + ); + } + } + } +} diff --git a/android/app/src/main/java/org/mooni2p/browser/RouterService.java b/android/app/src/main/java/org/mooni2p/browser/RouterService.java new file mode 100644 index 0000000..734b8dc --- /dev/null +++ b/android/app/src/main/java/org/mooni2p/browser/RouterService.java @@ -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 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 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(); + } + } + } +} diff --git a/android/app/src/main/res/xml/network_security_config.xml b/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..2439f15 --- /dev/null +++ b/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,4 @@ + + + + diff --git a/bittorrent/bittorrent_test.mbt b/bittorrent/bittorrent_test.mbt index b7ac496..37554f7 100644 --- a/bittorrent/bittorrent_test.mbt +++ b/bittorrent/bittorrent_test.mbt @@ -119,6 +119,11 @@ test "Peer wire framing, BEP 10/9, i2p_pex, i2p_dht, and chunked I2P HTTP tracke Bitfield(b"\x80"), Request(1, 0, 16384), 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'\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.i2p_dht_id, Some(b'\x03')) assert_eq(rext.metadata_size, Some(512)) + assert_eq(rext.client_name, "moon-i2p/0.1") assert_eq( @bittorrent.decode_i2p_dht_ext(@bittorrent.encode_i2p_dht_ext(6881U, 6882U)), Some((6881U, 6882U)), diff --git a/bittorrent/pkg.generated.mbti b/bittorrent/pkg.generated.mbti index 2b2d20f..582fdb3 100644 --- a/bittorrent/pkg.generated.mbti +++ b/bittorrent/pkg.generated.mbti @@ -213,6 +213,11 @@ pub(all) enum PeerMessage { Request(Int32, Int32, Int32) Piece(Int32, Int32, Bytes) Cancel(Int32, Int32, Int32) + SuggestPiece(UInt32) + HaveAll + HaveNone + RejectRequest(Int32, Int32, Int32) + AllowedFast(UInt32) Extended(Byte, Bytes) } @@ -222,6 +227,7 @@ pub(all) struct RemoteExtensions { mut i2p_pex_id : Byte? mut i2p_dht_id : Byte? mut metadata_size : Int32? + mut client_name : String } #derive(Eq, @debug.Debug) diff --git a/bittorrent/wire.mbt b/bittorrent/wire.mbt index b1f2d46..7aab99e 100644 --- a/bittorrent/wire.mbt +++ b/bittorrent/wire.mbt @@ -65,6 +65,11 @@ pub(all) enum PeerMessage { Request(Int32, Int32, Int32) Piece(Int32, Int32, Bytes) Cancel(Int32, Int32, Int32) + SuggestPiece(UInt32) + HaveAll + HaveNone + RejectRequest(Int32, Int32, Int32) + AllowedFast(UInt32) 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(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) => { w.write_u32_be((2 + payload.length()).reinterpret_as_uint()) 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() 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' => { let ext_id = r.read_u8() catch { e => raise Encoding(e) } Some(Extended(ext_id, r.read_remaining())) @@ -220,6 +266,7 @@ pub(all) struct RemoteExtensions { mut i2p_pex_id : Byte? mut i2p_dht_id : Byte? 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_dht_id: None, metadata_size: None, + client_name: "", } match bdict_get(d, "m") { Some(m) => { @@ -275,6 +323,10 @@ pub fn decode_ext_handshake(payload : Bytes) -> RemoteExtensions raise BtError { res.metadata_size = Some(sz.to_int()) _ => () } + match bdict_get_string(d, "v") { + Some(v) => res.client_name = v + None => () + } res } diff --git a/justfile b/justfile index 72d5d2e..8c80c25 100644 --- a/justfile +++ b/justfile @@ -24,6 +24,10 @@ extension: appimage: 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 test: moon test --target wasm diff --git a/ntcp2_net/net_stub.c b/ntcp2_net/net_stub.c index 2e67328..2a8412c 100644 --- a/ntcp2_net/net_stub.c +++ b/ntcp2_net/net_stub.c @@ -623,16 +623,23 @@ int32_t moon_i2p_net_mkdir_p(moonbit_bytes_t path_bytes, int32_t path_len) { char path[1024]; memcpy(path, path_bytes, (size_t)path_len); path[path_len] = '\0'; + struct stat st; for (int32_t i = 1; i < path_len; i++) { if (path[i] == '/') { path[i] = '\0'; - if (mkdir(path, 0755) < 0 && errno != EEXIST) { - net_set_error(strerror(errno)); - return -1; + if (!(stat(path, &st) == 0 && S_ISDIR(st.st_mode))) { + if (mkdir(path, 0755) < 0 && + errno != EEXIST && errno != EISDIR && errno != EACCES && errno != EROFS) { + net_set_error(strerror(errno)); + return -1; + } } path[i] = '/'; } } + if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) { + return 0; + } if (mkdir(path, 0755) < 0 && errno != EEXIST) { net_set_error(strerror(errno)); return -1; diff --git a/router/torrent_api.mbt b/router/torrent_api.mbt index b6997e1..de69eb6 100644 --- a/router/torrent_api.mbt +++ b/router/torrent_api.mbt @@ -345,11 +345,53 @@ fn Router::build_api_torrents_json(self : Router) -> String { } } 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 { 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 { "error" } 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("\"have_pieces\":\{have_cnt},") 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("\"known_peers\":\{t.known_peers.length()},") 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( + "\"last_tracker_status\":\"\{api_json_escape(t.last_tracker_status)}\",", + ) 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_string("]}") diff --git a/router/torrent_engine.mbt b/router/torrent_engine.mbt index bbb4386..f98362a 100644 --- a/router/torrent_engine.mbt +++ b/router/torrent_engine.mbt @@ -29,6 +29,10 @@ priv struct TorrentPeerConn { mut state : Int32 // 0=lookup_ls2, 1=streaming_connect, 2=await_bt_hs, 3=active, 4=closed mut started_ms : UInt64 mut last_activity_ms : UInt64 + mut last_send_ms : UInt64 + mut last_ls2_sent_ms : UInt64 + mut last_ls2_lookup_ms : UInt64 + mut sent_ls2_gen : Int32 mut stream_id : UInt32 mut peer_static : Bytes mut lease_gw : @common.Hash? @@ -40,10 +44,15 @@ priv struct TorrentPeerConn { mut peer_choking : Bool mut am_choking : Bool mut am_interested : Bool + mut has_bitfield_info : Bool + mut peer_have_all : Bool mut remote_ext : @bittorrent.RemoteExtensions? + mut remote_client : String mut peer_bitfield : Array[Bool] in_flight : Array[(Int32, Int32, Int32, UInt64)] // (piece_idx, begin, len, req_ms) + mut blocks_recv : UInt64 mut dht_pinged : Bool + mut close_reason : String } ///| @@ -76,6 +85,7 @@ priv struct ActiveTorrent { mut paused : Bool mut completed : Bool mut error : String + mut last_tracker_status : String mut downloaded_bytes : UInt64 mut uploaded_bytes : UInt64 mut have_pieces : Array[Bool] @@ -84,6 +94,7 @@ priv struct ActiveTorrent { meta_pieces : Array[(Int32, Bytes)] mut meta_req_ms : UInt64 known_peers : Array[@common.Hash] + peer_backoff : Array[(@common.Hash, UInt64)] peers : Array[TorrentPeerConn] trackers : Array[TorrentTrackerConn] mut last_dht_lookup_ms : UInt64 @@ -102,6 +113,7 @@ priv struct TorrentEngine { mut last_dht_maint_ms : UInt64 mut last_ls2_pub_ms : UInt64 mut last_ls2_pub_tunnels : Int32 + mut ls2_gen : Int32 } ///| @@ -123,13 +135,93 @@ fn bt_normalize_dir(dir : String) -> String { } } +///| +fn bt_short_b32(h : @common.Hash) -> String { + let b = h.to_b32_address() + if b.length() >= 16 { + b[:16].to_owned() + } else { + b + } +} + +///| +fn bt_set_peer_backoff( + t : ActiveTorrent, + h : @common.Hash, + retry_after_ms : UInt64, +) -> Unit { + for i = 0; i < t.peer_backoff.length(); i = i + 1 { + if t.peer_backoff[i].0 == h { + t.peer_backoff[i] = (h, retry_after_ms) + return + } + } + t.peer_backoff.push((h, retry_after_ms)) +} + +///| +fn bt_is_peer_backed_off( + t : ActiveTorrent, + h : @common.Hash, + now_ms : UInt64, +) -> Bool { + for entry in t.peer_backoff { + if entry.0 == h && now_ms < entry.1 { + return true + } + } + false +} + +///| +fn bt_net_err_msg(e : @ntcp2_net.Ntcp2NetError) -> String { + match e { + IoError(m) => m + Timeout => "timeout" + Closed => "closed" + InvalidPeer(m) => m + Protocol(_) => "protocol error" + Common(_) => "common error" + Noise(_) => "noise error" + } +} + +///| +/// Sanitizes a path segment for Android FUSE / VFAT filesystems while staying identical across reads and writes. +fn bt_sanitize_fs_segment(seg : String) -> String { + let sb = StringBuilder() + for ch in seg { + if ch == ':' || + ch == '*' || + ch == '?' || + ch == '"' || + ch == '<' || + ch == '>' || + ch == '|' { + sb.write_char('_') + } else { + sb.write_char(ch) + } + } + let mut s = sb.to_string() + while s.length() > 0 && (s.has_suffix(".") || s.has_suffix(" ")) { + s = s[:s.length() - 1].to_owned() + } + if s.length() == 0 || s == "." || s == ".." { + "_" + } else { + s + } +} + ///| fn bt_join_rel_path(base_dir : String, segs : Array[String]) -> String { let out = StringBuilder() out.write_string(bt_normalize_dir(base_dir)) for seg in segs { out.write_char('/') - out.write_string(seg) + out.write_string(bt_sanitize_fs_segment(seg)) } out.to_string() } @@ -143,7 +235,7 @@ fn bt_parent_dir(base_dir : String, segs : Array[String]) -> String { out.write_string(bt_normalize_dir(base_dir)) for i = 0; i < segs.length() - 1; i = i + 1 { out.write_char('/') - out.write_string(segs[i]) + out.write_string(bt_sanitize_fs_segment(segs[i])) } out.to_string() } @@ -188,10 +280,10 @@ fn bt_write_piece_to_files( t : ActiveTorrent, piece_idx : Int32, piece_bytes : Bytes, -) -> Bool { +) -> (Bool, String) { let meta = match t.metainfo { Some(m) => m - None => return false + None => return (false, "missing metainfo") } let global_start = piece_idx.to_int64() * meta.piece_length let mut cursor = 0 @@ -210,17 +302,27 @@ fn bt_write_piece_to_files( let slice_off = (overlap_start - global_start).to_int() let file_off = overlap_start - file_start let pdir = bt_parent_dir(t.download_dir, f.path) - let _ = @ntcp2_net.mkdir_p(pdir) catch { _ => return false } + let _ = @ntcp2_net.mkdir_p(pdir) catch { + e => return (false, "mkdir_p(\{pdir}): \{bt_net_err_msg(e)}") + } let full_path = bt_join_rel_path(t.download_dir, f.path) let chunk = piece_bytes[slice_off:slice_off + chunk_len].to_owned() let _ = @ntcp2_net.write_file_at(full_path, file_off, chunk) catch { - _ => return false + e => + return ( + false, + "write_file_at(\{full_path} @ \{file_off}): \{bt_net_err_msg(e)}", + ) } cursor += chunk_len } file_start = file_end } - cursor == piece_bytes.length() + if cursor == piece_bytes.length() { + (true, "") + } else { + (false, "short piece write (\{cursor}/\{piece_bytes.length()}B)") + } } ///| @@ -573,6 +675,7 @@ pub fn Router::enable_torrent_engine( last_dht_maint_ms: 0UL, last_ls2_pub_ms: @ntcp2_net.unix_time_ms(), last_ls2_pub_tunnels: self.tunnels.inbound.length(), + ls2_gen: 1, }) } @@ -676,6 +779,7 @@ pub fn Router::add_torrent_bytes( paused: false, completed: false, error: "", + last_tracker_status: "", downloaded_bytes: 0UL, uploaded_bytes: 0UL, have_pieces: Array::make(meta.piece_hashes.length(), false), @@ -684,6 +788,7 @@ pub fn Router::add_torrent_bytes( meta_pieces: [], meta_req_ms: 0UL, known_peers: [], + peer_backoff: [], peers: [], trackers: [], last_dht_lookup_ms: 0UL, @@ -695,6 +800,11 @@ pub fn Router::add_torrent_bytes( Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms) None => () } + if self.debug { + println( + "[debug] bt added torrent \{hex[:12]} '\{meta.name}' (\{meta.piece_hashes.length()} pcs, \{meta.total_length}B, \{t.trackers.length()} trackers)", + ) + } hex } @@ -763,6 +873,7 @@ pub fn Router::add_torrent_magnet( paused: false, completed: false, error: "", + last_tracker_status: "", downloaded_bytes: 0UL, uploaded_bytes: 0UL, have_pieces: [], @@ -771,6 +882,7 @@ pub fn Router::add_torrent_magnet( meta_pieces: [], meta_req_ms: 0UL, known_peers: [], + peer_backoff: [], peers: [], trackers: [], last_dht_lookup_ms: 0UL, @@ -792,6 +904,11 @@ pub fn Router::add_torrent_magnet( Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms) None => () } + if self.debug { + println( + "[debug] bt added magnet \{hex[:12]} '\{t.name}' (\{t.trackers.length()} trackers)", + ) + } hex } @@ -1028,6 +1145,11 @@ fn Router::send_dht_query( now_ms, info_hash~, ) + if self.debug { + println( + "[debug] bt dht TX \{kind_str} -> \{bt_short_b32(target_hash)}:\{port}", + ) + } true } @@ -1085,6 +1207,11 @@ fn Router::poll_dht_datagrams( match msg { Some(Query(tx_id~, sender_id~, kind~)) => { eng.dht.record_query_recv() + if self.debug { + println( + "[debug] bt dht RX query from \{bt_short_b32(sender_hash)}:\{sender_port}", + ) + } let _ = eng.dht.upsert_node(sender_id, sender_hash, sender_port, now_ms) match kind { Ping => { @@ -1192,6 +1319,11 @@ fn Router::poll_dht_datagrams( Some(Response(tx_id~, sender_id~, nodes~, values~, token~)) => match eng.dht.take_pending_tx(tx_id) { Some(tx) => { + if self.debug { + println( + "[debug] bt dht RX \{tx.kind} reply from \{bt_short_b32(tx.dest_hash)} nodes=\{nodes.length() / 54} values=\{values.length()}", + ) + } let _ = eng.dht.upsert_node( sender_id, tx.dest_hash, @@ -1282,6 +1414,12 @@ fn Router::poll_dht_datagrams( } None => () } + Some(ErrorMsg(tx_id~, code~, msg~)) => { + let _ = eng.dht.take_pending_tx(tx_id) + if self.debug { + println("[debug] bt dht RX error code=\{code} msg=\{msg}") + } + } _ => () } } @@ -1436,6 +1574,10 @@ fn Router::step_trackers( } _ => if now_ms > tr.started_ms + 25000UL { + t.last_tracker_status = "ls2 timeout: \{tr.host}" + if self.debug { + println("[debug] bt tracker ls2 timeout \{tr.host}") + } tr.state = 0 tr.next_announce_ms = now_ms + 30000UL } @@ -1481,6 +1623,14 @@ fn Router::step_trackers( _ => 0 } tr.sent_req = true + if t.last_tracker_status.length() == 0 { + t.last_tracker_status = "announcing \{tr.host}" + } + if self.debug { + println( + "[debug] bt tracker GET http://\{tr.host}:\{tr.port}\{tr.path} (ih=\{t.info_hash_hex[:12]}, left=\{left})", + ) + } match self.netdb.get_lease_set2(thash, now_sec) { Some(ls2) if ls2.leases.length() > 0 => match extract_x25519_key(ls2) { @@ -1519,8 +1669,12 @@ fn Router::step_trackers( if tr.recv_buf.length() > 0 { let raw = Bytes::from_array(tr.recv_buf) tr.recv_buf.clear() + let mut parse_err = "" let resp_opt = Some(@bittorrent.parse_http_tracker_response(raw)) catch { - _ => None + e => { + parse_err = bt_err_msg(e) + None + } } match resp_opt { Some(resp) => { @@ -1532,8 +1686,38 @@ fn Router::step_trackers( if resp.interval >= 15 { next_wait = resp.interval.to_uint64() * 1000UL } + match resp.failure_reason { + Some(fr) if fr.length() > 0 => { + t.last_tracker_status = "err: \{fr}" + if self.debug { + println("[debug] bt tracker \{tr.host} failure: \{fr}") + } + } + _ => { + t.last_tracker_status = "ok: \{resp.peers.length()}p (\{resp.complete}s/\{resp.incomplete}l) int=\{resp.interval}s" + if self.debug { + println( + "[debug] bt tracker \{tr.host} -> \{resp.peers.length()} peers (\{resp.complete}s/\{resp.incomplete}l), interval=\{resp.interval}s", + ) + } + } + } } - None => () + None => { + t.last_tracker_status = "parse err (\{raw.length()}B): \{parse_err}" + if self.debug { + println( + "[debug] bt tracker \{tr.host} parse error (\{raw.length()}B): \{parse_err}", + ) + } + } + } + } else { + t.last_tracker_status = "empty/timeout (\{tr.host})" + if self.debug { + println( + "[debug] bt tracker \{tr.host} empty/timeout (sent_req=\{tr.sent_req})", + ) } } tr.state = 0 @@ -1551,11 +1735,33 @@ fn Router::step_trackers( ///| fn Router::bt_flush_peer_send_buf( self : Router, + eng : TorrentEngine, sess : SamSession, conn : @streaming.StreamConnection, peer : TorrentPeerConn, now_ms : UInt64, ) -> Bool { + let now_sec = (now_ms / 1000UL).to_uint() + match self.netdb.get_lease_set2(peer.peer_hash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => { + if ls2.published_sec + ls2.expires_offset <= now_sec + 60U && + now_ms >= peer.last_ls2_lookup_ms + 20000UL { + peer.last_ls2_lookup_ms = now_ms + let _ = self.start_proxy_netdb_lookup(peer.peer_hash) + } + peer.lease_gw = Some(ls2.leases[0].tunnel_gw) + peer.lease_tid = ls2.leases[0].tunnel_id + match extract_x25519_key(ls2) { + Some(k) => peer.peer_static = k + None => () + } + } + _ => + if now_ms >= peer.last_ls2_lookup_ms + 20000UL { + peer.last_ls2_lookup_ms = now_ms + let _ = self.start_proxy_netdb_lookup(peer.peer_hash) + } + } if peer.send_buf.length() == 0 { return false } @@ -1566,8 +1772,11 @@ fn Router::bt_flush_peer_send_buf( return false } bt_pop_front_bytes(peer.send_buf, wrote) + peer.last_send_ms = now_ms + let need_ls2 = peer.sent_ls2_gen != eng.ls2_gen || + now_ms >= peer.last_ls2_sent_ms + 180000UL match (peer.lease_gw, peer.peer_static.length() == 32) { - (Some(gw), true) => + (Some(gw), true) => { self.flush_stream_outbound( sess, conn, @@ -1575,8 +1784,13 @@ fn Router::bt_flush_peer_send_buf( peer.peer_static, gw, peer.lease_tid, - send_ls2=false, + send_ls2=need_ls2, ) + if need_ls2 { + peer.sent_ls2_gen = eng.ls2_gen + peer.last_ls2_sent_ms = now_ms + } + } _ => () } true @@ -1585,6 +1799,7 @@ fn Router::bt_flush_peer_send_buf( ///| fn Router::bt_send_peer_wire( self : Router, + eng : TorrentEngine, sess : SamSession, conn : @streaming.StreamConnection, peer : TorrentPeerConn, @@ -1594,12 +1809,13 @@ fn Router::bt_send_peer_wire( for i = 0; i < data.length(); i = i + 1 { peer.send_buf.push(data[i]) } - let _ = self.bt_flush_peer_send_buf(sess, conn, peer, now_ms) + let _ = self.bt_flush_peer_send_buf(eng, sess, conn, peer, now_ms) } ///| fn Router::bt_send_post_handshake( self : Router, + eng : TorrentEngine, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, @@ -1611,15 +1827,24 @@ fn Router::bt_send_post_handshake( let msize : Int32? = if t.meta_size > 0 { Some(t.meta_size) } else { None } let ext_hs = @bittorrent.encode_ext_handshake(metadata_size=msize) self.bt_send_peer_wire( + eng, sess, conn, peer, @bittorrent.encode_peer_message(Extended(b'\x00', ext_hs)), now_ms, ) - if t.have_pieces.length() > 0 { + let mut any_have = false + for h in t.have_pieces { + if h { + any_have = true + break + } + } + if any_have { let bf = bt_build_bitfield_bytes(t.have_pieces) self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1630,6 +1855,7 @@ fn Router::bt_send_post_handshake( if peer.am_choking { peer.am_choking = false self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1640,6 +1866,7 @@ fn Router::bt_send_post_handshake( if !t.completed && !peer.am_interested { peer.am_interested = true self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1665,6 +1892,18 @@ fn Router::bt_handle_ext_message( if ext_id == b'\x00' { let re = @bittorrent.decode_ext_handshake(payload) catch { _ => return } peer.remote_ext = Some(re) + if re.client_name.length() > 0 { + peer.remote_client = re.client_name + } + if self.debug { + let ms_str = match re.metadata_size { + Some(ms) => "\{ms}" + None => "none" + } + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} ext_hs client=\"\{re.client_name}\" meta_size=\{ms_str}", + ) + } match re.metadata_size { Some(ms) if ms > 0 && t.meta_size == 0 => t.meta_size = ms _ => () @@ -1676,6 +1915,7 @@ fn Router::bt_handle_ext_message( eng.dht.reply_port, ) self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1697,6 +1937,7 @@ fn Router::bt_handle_ext_message( match re.ut_metadata_id { Some(rid) => self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1726,6 +1967,7 @@ fn Router::bt_handle_ext_message( match re.ut_metadata_id { Some(rid) => self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1836,6 +2078,7 @@ fn Router::bt_handle_ext_message( ///| fn Router::bt_request_metadata_if_needed( self : Router, + eng : TorrentEngine, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, @@ -1868,6 +2111,7 @@ fn Router::bt_request_metadata_if_needed( if !have { t.meta_req_ms = now_ms self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -1884,6 +2128,7 @@ fn Router::bt_request_metadata_if_needed( ///| fn Router::bt_schedule_piece_requests( self : Router, + eng : TorrentEngine, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, @@ -1894,26 +2139,33 @@ fn Router::bt_schedule_piece_requests( Some(m) => m None => return } - if t.completed || peer.peer_choking { + if peer.peer_have_all && + peer.peer_bitfield.length() < meta.piece_hashes.length() { + peer.peer_bitfield = Array::make(meta.piece_hashes.length(), true) + peer.has_bitfield_info = true + } + if t.completed || peer.peer_choking || !peer.has_bitfield_info { return } - // Drop timed-out in-flight requests (> 12s) + let req_timeout_ms = if self.public_mode { 30000UL } else { 12000UL } let mut i = 0 while i < peer.in_flight.length() { - if now_ms > peer.in_flight[i].3 + 12000UL { + if now_ms > peer.in_flight[i].3 + req_timeout_ms { let _ = peer.in_flight.remove(i) } else { i += 1 } } - let max_pipeline = 4 + let max_pipeline = 8 let num_pieces = meta.piece_hashes.length() while peer.in_flight.length() < max_pipeline { let mut picked : (Int32, Int32, Int32)? = None // First fill blocks inside already-active piece buffers for pbuf in t.inflight_pieces { let pidx = pbuf.piece_idx - if pidx < peer.peer_bitfield.length() && !peer.peer_bitfield[pidx] { + if pidx < 0 || + pidx >= peer.peer_bitfield.length() || + !peer.peer_bitfield[pidx] { continue } let plen = bt_piece_length(meta, pidx) @@ -1955,7 +2207,9 @@ fn Router::bt_schedule_piece_requests( if t.have_pieces[pidx] { continue } - if pidx < peer.peer_bitfield.length() && !peer.peer_bitfield[pidx] { + if pidx < 0 || + pidx >= peer.peer_bitfield.length() || + !peer.peer_bitfield[pidx] { continue } let mut active = false @@ -1991,8 +2245,14 @@ fn Router::bt_schedule_piece_requests( } match picked { Some((pidx, begin, blen)) => { + if self.debug && (begin == 0 || peer.blocks_recv == 0UL) { + println( + "[debug] bt req \{bt_short_b32(peer.peer_hash)} piece=\{pidx} begin=\{begin} len=\{blen}", + ) + } peer.in_flight.push((pidx, begin, blen, now_ms)) self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -2008,6 +2268,7 @@ fn Router::bt_schedule_piece_requests( ///| fn Router::bt_on_piece_block( self : Router, + eng : TorrentEngine, sess : SamSession, mgr : @streaming.StreamManager, t : ActiveTorrent, @@ -2021,6 +2282,12 @@ fn Router::bt_on_piece_block( Some(m) => m None => return } + peer.blocks_recv += 1UL + if self.debug && (peer.blocks_recv == 1UL || peer.blocks_recv % 8UL == 0UL) { + println( + "[debug] bt recv \{bt_short_b32(peer.peer_hash)} piece=\{piece_idx} begin=\{begin} len=\{block.length()} (blocks=\{peer.blocks_recv})", + ) + } // Remove from peer.in_flight let mut k = 0 while k < peer.in_flight.length() { @@ -2059,9 +2326,18 @@ fn Router::bt_on_piece_block( @crypto.sha1(piece_bytes), meta.piece_hashes[piece_idx], ) { - if bt_write_piece_to_files(t, piece_idx, piece_bytes) { + let (wrote_ok, err_msg) = bt_write_piece_to_files( + t, piece_idx, piece_bytes, + ) + if wrote_ok { + t.error = "" t.have_pieces[piece_idx] = true t.downloaded_bytes += piece_bytes.length().to_uint64() + if self.debug { + println( + "[debug] bt piece #\{piece_idx} verified & written (\{piece_bytes.length()}B, total=\{t.downloaded_bytes})", + ) + } let have_msg = @bittorrent.encode_peer_message( Have(piece_idx.reinterpret_as_uint()), ) @@ -2069,7 +2345,7 @@ fn Router::bt_on_piece_block( if op.state == 3 { match find_stream_by_id(mgr, op.stream_id) { Some(oc) => - self.bt_send_peer_wire(sess, oc, op, have_msg, now_ms) + self.bt_send_peer_wire(eng, sess, oc, op, have_msg, now_ms) None => () } } @@ -2083,8 +2359,18 @@ fn Router::bt_on_piece_block( } if all_done { t.completed = true + if self.debug { + println("[debug] bt COMPLETED '\{t.name}'!") + } + } + } else { + t.error = "disk write failed: \{err_msg}" + if self.debug { + println("[debug] bt write error: \{t.error}") } } + } else if self.debug { + println("[debug] bt piece #\{piece_idx} SHA-1 mismatch!") } } break @@ -2105,7 +2391,8 @@ fn Router::bt_process_peer_messages( ) -> Unit { for _iter = 0; _iter < 64; _iter = _iter + 1 { let msg_opt = @bittorrent.try_decode_peer_message(peer.recv_buf) catch { - _ => { + e => { + peer.close_reason = "wire decode error: \{bt_err_msg(e)}" peer.state = 4 return } @@ -2119,19 +2406,43 @@ fn Router::bt_process_peer_messages( Choke => { peer.peer_choking = true peer.in_flight.clear() + if self.debug { + println("[debug] bt peer \{bt_short_b32(peer.peer_hash)} CHOKE") + } + } + Unchoke => { + peer.peer_choking = false + if self.debug { + println("[debug] bt peer \{bt_short_b32(peer.peer_hash)} UNCHOKE") + } } - Unchoke => peer.peer_choking = false Interested | NotInterested => () Have(idx) => { let pidx = idx.reinterpret_as_int() if pidx >= 0 { - while peer.peer_bitfield.length() <= pidx { + let was_bf = peer.has_bitfield_info + let min_len = match t.metainfo { + Some(m) => + if m.piece_hashes.length() > pidx + 1 { + m.piece_hashes.length() + } else { + pidx + 1 + } + None => pidx + 1 + } + while peer.peer_bitfield.length() < min_len { peer.peer_bitfield.push(false) } peer.peer_bitfield[pidx] = true + peer.has_bitfield_info = true + if self.debug && (!was_bf || idx % 100U == 0U) { + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} Have(\{idx})", + ) + } } } - Bitfield(bf) => + Bitfield(bf) => { match t.metainfo { Some(m) => peer.peer_bitfield = bt_decode_bitfield( @@ -2142,6 +2453,76 @@ fn Router::bt_process_peer_messages( // Guess piece count from bitfield bytes until metadata arrives peer.peer_bitfield = bt_decode_bitfield(bf, bf.length() * 8) } + peer.has_bitfield_info = true + peer.peer_have_all = false + if self.debug { + let mut have_cnt = 0 + for hp in peer.peer_bitfield { + if hp { + have_cnt += 1 + } + } + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} Bitfield \{have_cnt}/\{peer.peer_bitfield.length()}", + ) + } + } + HaveAll => { + peer.peer_have_all = true + peer.has_bitfield_info = true + match t.metainfo { + Some(m) => + peer.peer_bitfield = Array::make(m.piece_hashes.length(), true) + None => () + } + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} HaveAll (\{peer.peer_bitfield.length()} pcs)", + ) + } + } + HaveNone => { + peer.peer_have_all = false + peer.has_bitfield_info = true + match t.metainfo { + Some(m) => + peer.peer_bitfield = Array::make(m.piece_hashes.length(), false) + None => peer.peer_bitfield = [] + } + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} HaveNone", + ) + } + } + RejectRequest(piece_idx, begin, _len) => { + let mut k = 0 + while k < peer.in_flight.length() { + if peer.in_flight[k].0 == piece_idx && + peer.in_flight[k].1 == begin { + let _ = peer.in_flight.remove(k) + break + } + k += 1 + } + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} REJECT piece=\{piece_idx} begin=\{begin}", + ) + } + } + SuggestPiece(idx) => + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} SuggestPiece(\{idx})", + ) + } + AllowedFast(idx) => + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(peer.peer_hash)} AllowedFast(\{idx})", + ) + } Request(piece_idx, begin, req_len) => if req_len > 0 && req_len <= 32768 && @@ -2152,6 +2533,7 @@ fn Router::bt_process_peer_messages( Some(block) => { t.uploaded_bytes += block.length().to_uint64() self.bt_send_peer_wire( + eng, sess, conn, peer, @@ -2166,7 +2548,7 @@ fn Router::bt_process_peer_messages( } Piece(piece_idx, begin, block) => self.bt_on_piece_block( - sess, mgr, t, peer, piece_idx, begin, block, now_ms, + eng, sess, mgr, t, peer, piece_idx, begin, block, now_ms, ) Cancel(_, _, _) => () Extended(eid, epayload) => @@ -2203,6 +2585,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool { now_ms >= eng.last_ls2_pub_ms + 120000UL { eng.last_ls2_pub_ms = now_ms eng.last_ls2_pub_tunnels = cur_in + eng.ls2_gen += 1 self.publish_session_leaseset2(sess) } @@ -2299,6 +2682,10 @@ fn Router::step_torrent_engine(self : Router) -> Bool { state: 3, started_ms: now_ms, last_activity_ms: now_ms, + last_send_ms: now_ms, + last_ls2_sent_ms: now_ms, + last_ls2_lookup_ms: 0UL, + sent_ls2_gen: eng.ls2_gen, stream_id: conn.local_stream_id, peer_static: ib.peer_static, lease_gw: Some(ib.lease_gw), @@ -2310,10 +2697,20 @@ fn Router::step_torrent_engine(self : Router) -> Bool { peer_choking: true, am_choking: true, am_interested: false, + has_bitfield_info: false, + peer_have_all: false, remote_ext: None, + remote_client: "", peer_bitfield: [], in_flight: [], + blocks_recv: 0UL, dht_pinged: false, + close_reason: "", + } + if self.debug { + println( + "[debug] bt inbound peer \{bt_short_b32(ib.peer_hash)} handshake OK", + ) } let hs_out = @bittorrent.encode_handshake( t.info_hash, @@ -2321,8 +2718,8 @@ fn Router::step_torrent_engine(self : Router) -> Bool { ) catch { _ => b"" } - self.bt_send_peer_wire(sess, conn, peer, hs_out, now_ms) - self.bt_send_post_handshake(sess, conn, t, peer, now_ms) + self.bt_send_peer_wire(eng, sess, conn, peer, hs_out, now_ms) + self.bt_send_post_handshake(eng, sess, conn, t, peer, now_ms) self.bt_process_peer_messages( eng, sess, mgr, conn, t, peer, now_ms, ) @@ -2366,6 +2763,9 @@ fn Router::step_torrent_engine(self : Router) -> Bool { if t.peers.length() >= 12 { break } + if bt_is_peer_backed_off(t, kh, now_ms) { + continue + } let mut already = kh == sess.hash if !already { for p in t.peers { @@ -2377,11 +2777,18 @@ fn Router::step_torrent_engine(self : Router) -> Bool { } if !already { let _ = self.start_proxy_netdb_lookup(kh) + if self.debug { + println("[debug] bt peer \{bt_short_b32(kh)} queuing LS2 lookup") + } t.peers.push({ peer_hash: kh, state: 0, started_ms: now_ms, last_activity_ms: now_ms, + last_send_ms: now_ms, + last_ls2_sent_ms: 0UL, + last_ls2_lookup_ms: now_ms, + sent_ls2_gen: 0, stream_id: 0U, peer_static: b"", lease_gw: None, @@ -2393,10 +2800,15 @@ fn Router::step_torrent_engine(self : Router) -> Bool { peer_choking: true, am_choking: true, am_interested: false, + has_bitfield_info: false, + peer_have_all: false, remote_ext: None, + remote_client: "", peer_bitfield: [], in_flight: [], + blocks_recv: 0UL, dht_pinged: false, + close_reason: "", }) did_work = true } @@ -2419,6 +2831,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool { to_port=0U, ) catch { _ => { + p.close_reason = "stream connect error" p.state = 4 continue } @@ -2429,6 +2842,13 @@ fn Router::step_torrent_engine(self : Router) -> Bool { p.lease_tid = ls2.leases[0].tunnel_id p.state = 1 p.started_ms = now_ms + p.sent_ls2_gen = eng.ls2_gen + p.last_ls2_sent_ms = now_ms + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(p.peer_hash)} connecting I2P stream sid=\{conn.local_stream_id}", + ) + } self.flush_stream_outbound( sess, conn, @@ -2445,6 +2865,8 @@ fn Router::step_torrent_engine(self : Router) -> Bool { _ => () } if p.state == 0 && now_ms > p.started_ms + 30000UL { + p.close_reason = "ls2 lookup timeout (30s)" + bt_set_peer_backoff(t, p.peer_hash, now_ms + 10000UL) p.state = 4 } } @@ -2452,6 +2874,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool { let conn = match find_stream_by_id(mgr, p.stream_id) { Some(c) => c None => { + p.close_reason = "missing stream" p.state = 4 continue } @@ -2459,15 +2882,26 @@ fn Router::step_torrent_engine(self : Router) -> Bool { if conn.state == Established { p.state = 2 p.last_activity_ms = now_ms + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(p.peer_hash)} stream connected, sending BT handshake", + ) + } if !p.sent_bt_hs { p.sent_bt_hs = true let hs = @bittorrent.encode_handshake(t.info_hash, eng.peer_id) catch { _ => b"" } - self.bt_send_peer_wire(sess, conn, p, hs, now_ms) + self.bt_send_peer_wire(eng, sess, conn, p, hs, now_ms) } did_work = true } else if conn.state == Reset || now_ms > p.started_ms + 30000UL { + p.close_reason = if conn.state == Reset { + "stream connect reset" + } else { + "stream connect timeout (30s)" + } + bt_set_peer_backoff(t, p.peer_hash, now_ms + 10000UL) p.state = 4 } } @@ -2475,11 +2909,12 @@ fn Router::step_torrent_engine(self : Router) -> Bool { let conn = match find_stream_by_id(mgr, p.stream_id) { Some(c) => c None => { + p.close_reason = "missing stream" p.state = 4 continue } } - if self.bt_flush_peer_send_buf(sess, conn, p, now_ms) { + if self.bt_flush_peer_send_buf(eng, sess, conn, p, now_ms) { did_work = true } let avail = conn.read_available() @@ -2499,16 +2934,33 @@ fn Router::step_torrent_engine(self : Router) -> Bool { bt_pop_front_bytes(p.recv_buf, 68) p.state = 3 p.last_activity_ms = now_ms - self.bt_send_post_handshake(sess, conn, t, p, now_ms) + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(p.peer_hash)} handshake OK", + ) + } + self.bt_send_post_handshake(eng, sess, conn, t, p, now_ms) self.bt_process_peer_messages( eng, sess, mgr, conn, t, p, now_ms, ) } - _ => p.state = 4 + _ => { + p.close_reason = "bt handshake mismatch" + bt_set_peer_backoff(t, p.peer_hash, now_ms + 15000UL) + p.state = 4 + } } } else if conn.is_eof() || conn.state == Reset || now_ms > p.last_activity_ms + 20000UL { + p.close_reason = if conn.state == Reset { + "stream reset before bt handshake" + } else if conn.is_eof() { + "stream eof before bt handshake" + } else { + "bt handshake timeout (20s)" + } + bt_set_peer_backoff(t, p.peer_hash, now_ms + 10000UL) p.state = 4 } } @@ -2516,11 +2968,12 @@ fn Router::step_torrent_engine(self : Router) -> Bool { let conn = match find_stream_by_id(mgr, p.stream_id) { Some(c) => c None => { + p.close_reason = "missing stream" p.state = 4 continue } } - if self.bt_flush_peer_send_buf(sess, conn, p, now_ms) { + if self.bt_flush_peer_send_buf(eng, sess, conn, p, now_ms) { did_work = true } let avail = conn.read_available() @@ -2533,9 +2986,30 @@ fn Router::step_torrent_engine(self : Router) -> Bool { } self.bt_process_peer_messages(eng, sess, mgr, conn, t, p, now_ms) if p.state == 3 { - self.bt_request_metadata_if_needed(sess, conn, t, p, now_ms) - self.bt_schedule_piece_requests(sess, conn, t, p, now_ms) + self.bt_request_metadata_if_needed(eng, sess, conn, t, p, now_ms) + self.bt_schedule_piece_requests(eng, sess, conn, t, p, now_ms) + if p.send_buf.length() == 0 && now_ms >= p.last_send_ms + 45000UL { + self.bt_send_peer_wire( + eng, + sess, + conn, + p, + @bittorrent.encode_peer_message(KeepAlive), + now_ms, + ) + } if conn.is_eof() || conn.state == Reset { + p.close_reason = if conn.state == Reset { + "stream reset" + } else { + "stream eof" + } + bt_set_peer_backoff(t, p.peer_hash, now_ms + 10000UL) + p.state = 4 + } else if !t.completed && now_ms > p.last_activity_ms + 90000UL { + p.close_reason = "idle 90s timeout" + bt_set_peer_backoff(t, p.peer_hash, now_ms + 15000UL) + let _ = self.netdb.remove_lease_set2(p.peer_hash) p.state = 4 } } @@ -2543,6 +3017,11 @@ fn Router::step_torrent_engine(self : Router) -> Bool { _ => () } if p.state == 4 { + if self.debug { + println( + "[debug] bt peer \{bt_short_b32(p.peer_hash)} closed (\{p.close_reason})", + ) + } if p.stream_id != 0U { match find_stream_by_id(mgr, p.stream_id) { Some(c) => { @@ -2564,20 +3043,30 @@ fn Router::step_torrent_engine(self : Router) -> Bool { t.known_peers.length() > 0 && now_ms >= t.last_pex_ms + 30000UL { t.last_pex_ms = now_ms - let pex_bytes = @bittorrent.encode_i2p_pex(t.known_peers) for p in t.peers { if p.state == 3 { match (p.remote_ext, find_stream_by_id(mgr, p.stream_id)) { (Some(re), Some(conn)) => match re.i2p_pex_id { - Some(pid) => - self.bt_send_peer_wire( - sess, - conn, - p, - @bittorrent.encode_peer_message(Extended(pid, pex_bytes)), - now_ms, - ) + Some(pid) => { + let filtered : Array[@common.Hash] = [] + for kh in t.known_peers { + if kh != p.peer_hash { + filtered.push(kh) + } + } + if filtered.length() > 0 { + let pex_bytes = @bittorrent.encode_i2p_pex(filtered) + self.bt_send_peer_wire( + eng, + sess, + conn, + p, + @bittorrent.encode_peer_message(Extended(pid, pex_bytes)), + now_ms, + ) + } + } None => () } _ => () diff --git a/scripts/build_apk.py b/scripts/build_apk.py new file mode 100755 index 0000000..e5524e6 --- /dev/null +++ b/scripts/build_apk.py @@ -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//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 \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() diff --git a/streaming/stream.mbt b/streaming/stream.mbt index e5a8dbf..642a450 100644 --- a/streaming/stream.mbt +++ b/streaming/stream.mbt @@ -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 { - return [] + return (self.ack_through, []) } - let mut max_seen = self.next_recv_seq + let seqs : Array[UInt32] = [] for entry in self.ooo_recv { - if entry.0 > max_seen { - max_seen = entry.0 + let s = entry.0 + if s < self.next_recv_seq { + continue } - } - let nacks : Array[UInt32] = [] - let mut s = self.next_recv_seq - while s < max_seen && nacks.length() < 32 { - let mut found = false - for entry in self.ooo_recv { - if entry.0 == s { - found = true + let mut dup = false + for existing in seqs { + if existing == s { + dup = true break } } - if !found { - nacks.push(s) + if !dup { + 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, now_ms : UInt64, ) -> Unit raise StreamingError { + let (wire_ack, wire_nacks) = self.wire_ack_and_nacks() let ack_pkt : StreamingPacket = { send_stream_id: self.remote_stream_id, recv_stream_id: self.local_stream_id, sequence_num: 0U, - ack_through: self.ack_through, - nacks: self.current_nacks(), + ack_through: wire_ack, + nacks: wire_nacks, resend_delay: b'\x00', flags: 0U, delay_requested: None, @@ -479,8 +510,7 @@ pub fn StreamConnection::on_packet( } let seq = pkt.sequence_num - let has_data = pkt.payload.length() > 0 || (pkt.flags & flag_close) != 0U - if seq > 0U && has_data { + if seq > 0U && (pkt.flags & flag_synchronize) == 0U { if seq == self.next_recv_seq { for i = 0; i < pkt.payload.length(); i = i + 1 { self.recv_buf.push(pkt.payload[i]) @@ -513,10 +543,14 @@ pub fn StreamConnection::on_packet( self.send_ack(now_ms) acked = true } - if !acked && (pkt.flags & flag_delay_requested) != 0U { - match pkt.delay_requested { - Some(d) if d == 0U => self.send_ack(now_ms) - _ => () + if !acked { + if (pkt.flags & flag_echo) != 0U { + 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 self.next_send_seq = seq + 1U 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 = { send_stream_id: self.remote_stream_id, recv_stream_id: self.local_stream_id, sequence_num: seq, - ack_through: self.ack_through, - nacks: self.current_nacks(), + ack_through: wire_ack, + nacks: wire_nacks, resend_delay: b'\x00', flags, delay_requested: None, @@ -592,12 +627,13 @@ pub fn StreamConnection::close( } let seq = self.next_send_seq self.next_send_seq = seq + 1U + let (wire_ack, wire_nacks) = self.wire_ack_and_nacks() let pkt : StreamingPacket = { send_stream_id: self.remote_stream_id, recv_stream_id: self.local_stream_id, sequence_num: seq, - ack_through: self.ack_through, - nacks: self.current_nacks(), + ack_through: wire_ack, + nacks: wire_nacks, resend_delay: b'\x00', flags: flag_close | flag_signature_included | diff --git a/streaming/streaming_test.mbt b/streaming/streaming_test.mbt index 8a6056d..808664c 100644 --- a/streaming/streaming_test.mbt +++ b/streaming/streaming_test.mbt @@ -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].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") +}