From ef67e1c0aee83becd776c4a970573eb5d513ce5c Mon Sep 17 00:00:00 2001 From: Aleksandr Bogomiakov Date: Tue, 24 Nov 2026 17:28:23 +0200 Subject: [PATCH] Add a Rust Android mesh client with shared tray views Run one agent for all joined networks behind Android's VPN service. Share transport registration and reporting with the CLI, and move the tray's egui forms into a Rust UI crate. Phones use compact device rows and a full-width exit picker with RTT and data path. All four transports retain their per-network selection and priority. The phone consumes remote IPv4 exits and keeps the existing desktop identity and wire protocols. Send discovery and transport traffic over the physical network and bind VIP TCP health checks to the mesh. Build local DNS zones from the same signed membership and VIP records on desktop and Android. Answer UDP and TCP queries on the VPN, keep unknown mesh names local, and resolve public names through Android's underlying resolver, including with an exit. Show an ongoing notification for the selected exit. Guard its disconnect action against a stale selection and keep mesh routing and DNS alive when it removes the default route. Remove the app notification in mesh-only mode. Document Android 14's unlocked-device swipe behavior. Checked formatting and ran locked all-target workspace Clippy with warnings denied and tests on macOS (547 passed, 2 ignored). Built the arm64 debug APK. A physical Pixel resolved a mesh member and a Kubernetes VIP, answered UDP and TCP DNS, and reached the API over TLS (HTTP 401 without credentials). On a separate Android emulator the notification action removed the default route and notice while mesh DNS still worked. --- Cargo.lock | 50 +- README.md | 1 + android/.gitattributes | 2 + android/.gitignore | 5 + android/README.md | 23 + android/app/build.gradle | 59 ++ android/app/src/main/AndroidManifest.xml | 25 + .../java/cy/hexor/tsunagi/MainActivity.kt | 53 ++ .../main/java/cy/hexor/tsunagi/MeshSurface.kt | 147 ++++ .../src/main/java/cy/hexor/tsunagi/MeshVpn.kt | 197 ++++++ .../src/main/java/cy/hexor/tsunagi/Native.kt | 21 + android/app/src/main/res/drawable/tsunagi.xml | 6 + android/gradle.properties | 2 + android/gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 48966 bytes .../gradle/wrapper/gradle-wrapper.properties | 7 + android/gradlew | 248 +++++++ android/gradlew.bat | 93 +++ android/settings.gradle | 3 + crates/tsunagi-android/Cargo.toml | 42 ++ crates/tsunagi-android/src/android/display.rs | 263 +++++++ crates/tsunagi-android/src/android/dns.rs | 90 +++ crates/tsunagi-android/src/android/mod.rs | 366 ++++++++++ crates/tsunagi-android/src/dns.rs | 122 ++++ crates/tsunagi-android/src/dns/stack.rs | 311 +++++++++ crates/tsunagi-android/src/dns/stack/tests.rs | 105 +++ crates/tsunagi-android/src/lib.rs | 13 + crates/tsunagi-android/src/plan.rs | 85 +++ crates/tsunagi-android/src/service.rs | 263 +++++++ crates/tsunagi-android/src/tests.rs | 651 ++++++++++++++++++ crates/tsunagi-android/src/tun.rs | 287 ++++++++ crates/tsunagi-android/src/view.rs | 361 ++++++++++ crates/tsunagi-core/src/agent/mod.rs | 13 + crates/tsunagi-core/src/dns/mod.rs | 50 ++ crates/tsunagi-core/src/dns/server.rs | 69 +- crates/tsunagi-core/src/dns/zone.rs | 18 + crates/tsunagi-core/src/net.rs | 4 + .../src/overlay/hostrules/exit.rs | 2 + .../src/overlay/hostrules/windows_exit.rs | 1 + crates/tsunagi-core/src/overlay/interface.rs | 9 +- crates/tsunagi-core/src/overlay/router.rs | 9 + crates/tsunagi-core/src/overlay/tun.rs | 55 +- crates/tsunagi-core/src/vip/router.rs | 60 +- crates/tsunagi-runtime/Cargo.toml | 20 + crates/tsunagi-runtime/src/lib.rs | 190 +++++ crates/tsunagi-runtime/src/report.rs | 201 ++++++ crates/tsunagi-tcp-tls/src/plugin.rs | 32 +- crates/tsunagi-tray/Cargo.toml | 1 + crates/tsunagi-tray/src/agent.rs | 89 +-- crates/tsunagi-tray/src/app.rs | 8 +- crates/tsunagi-tray/src/main.rs | 12 +- crates/tsunagi-tray/src/ui.rs | 402 +---------- crates/tsunagi-ui/Cargo.toml | 18 + .../{tsunagi-tray => tsunagi-ui}/src/about.rs | 32 +- crates/tsunagi-ui/src/client.rs | 121 ++++ .../src/devices.rs | 211 +++++- crates/tsunagi-ui/src/devices/compact.rs | 193 ++++++ crates/tsunagi-ui/src/devices/exit_picker.rs | 340 +++++++++ .../{tsunagi-tray => tsunagi-ui}/src/exit.rs | 4 +- .../src/format.rs | 14 +- crates/tsunagi-ui/src/home.rs | 412 +++++++++++ crates/tsunagi-ui/src/lib.rs | 19 + crates/tsunagi-ui/src/listeners.rs | 94 +++ .../{tsunagi-tray => tsunagi-ui}/src/stats.rs | 73 +- .../{tsunagi-tray => tsunagi-ui}/src/table.rs | 1 - .../{tsunagi-tray => tsunagi-ui}/src/vip.rs | 89 +-- .../src/vip_status.rs | 96 ++- crates/tsunagi-wg-quic/tests/exit_node.rs | 52 +- crates/tsunagi-wireguard/src/transport.rs | 17 +- crates/tsunagi/Cargo.toml | 2 +- crates/tsunagi/src/main.rs | 446 +----------- 70 files changed, 6199 insertions(+), 1181 deletions(-) create mode 100644 android/.gitattributes create mode 100644 android/.gitignore create mode 100644 android/README.md create mode 100644 android/app/build.gradle create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt create mode 100644 android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt create mode 100644 android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt create mode 100644 android/app/src/main/java/cy/hexor/tsunagi/Native.kt create mode 100644 android/app/src/main/res/drawable/tsunagi.xml create mode 100644 android/gradle.properties create mode 100644 android/gradle/wrapper/gradle-wrapper.jar create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100755 android/gradlew create mode 100644 android/gradlew.bat create mode 100644 android/settings.gradle create mode 100644 crates/tsunagi-android/Cargo.toml create mode 100644 crates/tsunagi-android/src/android/display.rs create mode 100644 crates/tsunagi-android/src/android/dns.rs create mode 100644 crates/tsunagi-android/src/android/mod.rs create mode 100644 crates/tsunagi-android/src/dns.rs create mode 100644 crates/tsunagi-android/src/dns/stack.rs create mode 100644 crates/tsunagi-android/src/dns/stack/tests.rs create mode 100644 crates/tsunagi-android/src/lib.rs create mode 100644 crates/tsunagi-android/src/plan.rs create mode 100644 crates/tsunagi-android/src/service.rs create mode 100644 crates/tsunagi-android/src/tests.rs create mode 100644 crates/tsunagi-android/src/tun.rs create mode 100644 crates/tsunagi-android/src/view.rs create mode 100644 crates/tsunagi-runtime/Cargo.toml create mode 100644 crates/tsunagi-runtime/src/lib.rs create mode 100644 crates/tsunagi-runtime/src/report.rs create mode 100644 crates/tsunagi-ui/Cargo.toml rename crates/{tsunagi-tray => tsunagi-ui}/src/about.rs (83%) create mode 100644 crates/tsunagi-ui/src/client.rs rename crates/{tsunagi-tray => tsunagi-ui}/src/devices.rs (87%) create mode 100644 crates/tsunagi-ui/src/devices/compact.rs create mode 100644 crates/tsunagi-ui/src/devices/exit_picker.rs rename crates/{tsunagi-tray => tsunagi-ui}/src/exit.rs (98%) rename crates/{tsunagi-tray => tsunagi-ui}/src/format.rs (92%) create mode 100644 crates/tsunagi-ui/src/home.rs create mode 100644 crates/tsunagi-ui/src/lib.rs create mode 100644 crates/tsunagi-ui/src/listeners.rs rename crates/{tsunagi-tray => tsunagi-ui}/src/stats.rs (83%) rename crates/{tsunagi-tray => tsunagi-ui}/src/table.rs (99%) rename crates/{tsunagi-tray => tsunagi-ui}/src/vip.rs (81%) rename crates/{tsunagi-tray => tsunagi-ui}/src/vip_status.rs (92%) diff --git a/Cargo.lock b/Cargo.lock index ffaaacd..898d85f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6310,14 +6310,38 @@ dependencies = [ "tokio", "tracing", "tracing-subscriber", - "tsunagi-awg", "tsunagi-core", + "tsunagi-runtime", "tsunagi-tcp-tls", "tsunagi-wg-quic", "tsunagi-wireguard", "windows-service", ] +[[package]] +name = "tsunagi-android" +version = "1.0.0" +dependencies = [ + "bytes", + "egui", + "egui-phosphor", + "egui_glow", + "iroh", + "jni 0.21.1", + "jni 0.22.4", + "rand 0.10.3", + "rustls-platform-verifier", + "simple-dns", + "smoltcp", + "tempfile", + "tokio", + "tsunagi-core", + "tsunagi-runtime", + "tsunagi-ui", + "tsunagi-wg-quic", + "zeroize", +] + [[package]] name = "tsunagi-awg" version = "1.0.0" @@ -6375,6 +6399,19 @@ dependencies = [ "zeroize", ] +[[package]] +name = "tsunagi-runtime" +version = "1.0.0" +dependencies = [ + "tokio", + "tracing", + "tsunagi-awg", + "tsunagi-core", + "tsunagi-tcp-tls", + "tsunagi-wg-quic", + "tsunagi-wireguard", +] + [[package]] name = "tsunagi-tcp-tls" version = "1.0.0" @@ -6407,9 +6444,20 @@ dependencies = [ "tracing-subscriber", "tray-icon", "tsunagi-core", + "tsunagi-ui", "winit", ] +[[package]] +name = "tsunagi-ui" +version = "1.0.0" +dependencies = [ + "egui", + "egui-phosphor", + "tsunagi-core", + "zeroize", +] + [[package]] name = "tsunagi-wg-quic" version = "1.0.0" diff --git a/README.md b/README.md index 9fa6962..478e92c 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ with relay fallback), and keep the network state among themselves. - **LAN games:** UDP broadcasts are relayed, so "LAN" lobbies show up across the mesh. - **Several networks at once** on one device. - **Tray app** for Windows, macOS and Linux; a command line for everything. +- **Android prototype** for ARM64 phones, with the same egui forms and a foreground VPN service. [Build and run the Android client](android/README.md). ## Install diff --git a/android/.gitattributes b/android/.gitattributes new file mode 100644 index 0000000..43a6f0c --- /dev/null +++ b/android/.gitattributes @@ -0,0 +1,2 @@ +gradlew text eol=lf +gradlew.bat text eol=crlf diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..e4db14d --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,5 @@ +.gradle/ +.kotlin/ +.idea/ +local.properties +**/build/ diff --git a/android/README.md b/android/README.md new file mode 100644 index 0000000..70c6478 --- /dev/null +++ b/android/README.md @@ -0,0 +1,23 @@ +# Android client + +Open this directory in Android Studio. The debug prototype targets ARM64 devices running Android 8 or later with OpenGL ES 3. Install SDK Platform 35 and the NDK with the SDK Manager. Point `ANDROID_HOME` at your SDK and `ANDROID_NDK_HOME` at the installed NDK directory. The Gradle launcher needs a JDK, such as the one bundled with Android Studio. + +From the repository root, with Cargo and cargo-ndk on your PATH: + +```sh +rustup target add aarch64-linux-android +cargo install cargo-ndk --version 4.1.2 --locked +cd android +./gradlew :app:assembleDebug +adb install -r app/build/outputs/apk/debug/app-debug.apk +``` + +Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks. + +The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic. + +Applications using Android’s system resolver can connect to `.` and `.`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records. + +The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard. + +Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications) diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..9542c98 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,59 @@ +import groovy.json.JsonSlurper + +plugins { id 'com.android.application' version '9.2.1' } + +def workspace = rootProject.projectDir.parentFile +def abi = 'arm64-v8a' +android { + namespace 'cy.hexor.tsunagi' + compileSdk 35 + + // Cargo also builds standalone cdylibs for these dependencies. Their code + // is linked into tsunagi_android; the JVM loads only the application library. + packaging.jniLibs.excludes += ['**/libboringtun.so', '**/libiroh.so', '**/libiroh_relay.so'] + defaultConfig { + applicationId 'cy.hexor.tsunagi' + minSdk 26 + targetSdk 35 + versionCode 1 + versionName '1.0.0' + ndk { abiFilters abi } + } +} + +// rustls ships its Android trust manager as an AAR in the locked Cargo package. +def metadata = providers.exec { + workingDir workspace + commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android' +}.standardOutput.asText.get() +def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' } +repositories { + maven { + url new File(new File(verifier.manifest_path).parent, 'maven') + metadataSources { mavenPom() } + content { includeModule 'rustls', 'rustls-platform-verifier' } + } + google() + mavenCentral() +} +dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" } + +abstract class BuildRust extends Exec { + @OutputDirectory abstract DirectoryProperty getJniLibs() +} + +androidComponents.onVariants(androidComponents.selector().all()) { variant -> + def mode = variant.buildType + def libs = layout.buildDirectory.dir("generated/rust/${mode}") + def nativeBuild = tasks.register("cargo${mode.capitalize()}", BuildRust) { + workingDir workspace + inputs.files(fileTree(workspace) { + include 'Cargo.toml', 'Cargo.lock', '.cargo/**', 'crates/**/Cargo.toml', 'crates/**/src/**', 'vendor/**' + }) + jniLibs.set(libs) + commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26', '-o', libs.get().asFile, + 'build', '--locked', '--lib', '-p', 'tsunagi-android' + if (mode == 'release') args '--release' + } + variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2d26971 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt b/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt new file mode 100644 index 0000000..2b57030 --- /dev/null +++ b/android/app/src/main/java/cy/hexor/tsunagi/MainActivity.kt @@ -0,0 +1,53 @@ +package cy.hexor.tsunagi + +import android.app.Activity +import android.content.Intent +import android.net.VpnService +import android.os.Build +import android.os.Bundle +import android.view.WindowInsets +import android.widget.FrameLayout + +class MainActivity : Activity() { + private var askedForNotifications = false + internal fun requestExitNotifications() { + if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications && + checkSelfPermission(android.Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) { + askedForNotifications = true + requestPermissions(arrayOf(android.Manifest.permission.POST_NOTIFICATIONS), 2) + } + } + private lateinit var surface: MeshSurface + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + surface = MeshSurface(this) + val root = FrameLayout(this) + if (Build.VERSION.SDK_INT >= 30) { + window.setDecorFitsSystemWindows(false) + root.setOnApplyWindowInsetsListener { view, insets -> + val area = insets.getInsets(WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout() or WindowInsets.Type.ime()) + view.setPadding(area.left, area.top, area.right, area.bottom) + insets + } + } else root.fitsSystemWindows = true + root.addView(surface) + setContentView(root) + } + internal fun requestVpn() { + val consent = VpnService.prepare(this) + if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java)) + else startActivityForResult(consent, 1) + } + @Deprecated("Platform consent result") + override fun onActivityResult(request: Int, result: Int, data: Intent?) { + super.onActivityResult(request, result, data) + if (request == 1) { + if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java)) + else surface.input(5, "VPN permission was declined") + } + } + @Deprecated("Forward system Back to the current Rust view") + override fun onBackPressed() { surface.dispatchBack() } + override fun onResume() { super.onResume(); surface.onResume() } + override fun onPause() { surface.onPause(); super.onPause() } +} diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt b/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt new file mode 100644 index 0000000..5cd630d --- /dev/null +++ b/android/app/src/main/java/cy/hexor/tsunagi/MeshSurface.kt @@ -0,0 +1,147 @@ +package cy.hexor.tsunagi + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.opengl.GLSurfaceView +import android.text.InputType +import android.view.KeyEvent +import android.view.MotionEvent +import android.view.inputmethod.BaseInputConnection +import android.view.inputmethod.EditorInfo +import android.view.inputmethod.InputConnection +import android.view.inputmethod.InputMethodManager +import javax.microedition.khronos.egl.EGLConfig +import javax.microedition.khronos.opengles.GL10 + +/** Surface, input connection and clipboard bridge for egui. */ +class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer { + private val density get() = resources.displayMetrics.density + private val imm = activity.getSystemService(InputMethodManager::class.java) + private var imeMode = 0 + private var widthPx = 0 + private var heightPx = 0 + private val repaint = Runnable { requestRender() } + init { + setEGLContextClientVersion(3) + preserveEGLContextOnPause = true + setRenderer(this) + renderMode = RENDERMODE_WHEN_DIRTY + isFocusableInTouchMode = true + requestFocus() + } + override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface() + override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h } + override fun onDrawFrame(gl: GL10?) { + val delay = Native.draw(this, widthPx, heightPx, density) + removeCallbacks(repaint) + postDelayed(repaint, delay.coerceAtLeast(16)) + } + override fun onPause() { super.onPause(); removeCallbacks(repaint) } + override fun onTouchEvent(e: MotionEvent): Boolean { + val phase = when (e.actionMasked) { + MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0 + MotionEvent.ACTION_MOVE -> 1 + MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> 2 + MotionEvent.ACTION_CANCEL -> 3 + else -> return false + } + for (i in 0 until e.pointerCount) { + if ((phase == 0 || phase == 2) && i != e.actionIndex) continue + val id = e.getPointerId(i) + val x = e.getX(i) / density + val y = e.getY(i) / density + queueEvent { Native.touch(phase, id, x, y) } + } + requestRender() + return true + } + + fun startVpn() { post { activity.requestVpn() } } + fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } } + fun requestExitNotifications() { post { activity.requestExitNotifications() } } + fun closeScreen() { post { activity.finish() } } + fun openUrl(url: String) { post { + val uri = android.net.Uri.parse(url) + if (uri.scheme == "https") { + try { activity.startActivity(Intent(Intent.ACTION_VIEW, uri)) } + catch (_: android.content.ActivityNotFoundException) { } + } + } } + fun dispatchBack() { queueEvent { Native.back(this) }; requestRender() } + fun copyText(value: String) { post { + activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("tsunagi", value)) + } } + fun copySecret(value: String) { post { + val clip = ClipData.newPlainText("tsunagi", value) + clip.description.extras = android.os.PersistableBundle().apply { putBoolean("android.content.extra.IS_SENSITIVE", true) } + activity.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip) + } } + fun pasteSecret() { post { + val clip = activity.getSystemService(ClipboardManager::class.java).primaryClip + val text = clip?.takeIf { it.itemCount > 0 }?.getItemAt(0)?.text + if (text != null && text.length <= 2048) input(4, text.toString()) + } } + fun keyboard(mode: Int) { post { + imeMode = mode + if (mode == 0) { + imm.hideSoftInputFromWindow(windowToken, 0) + imm.restartInput(this) + } + else { + requestFocus() + imm.restartInput(this) + imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) + } + } } + fun input(kind: Int, value: String) { + queueEvent { Native.input(kind, value) } + requestRender() + } + private fun key(code: Int) { queueEvent { Native.key(code) }; requestRender() } + override fun onCheckIsTextEditor(): Boolean = imeMode != 0 + override fun onCreateInputConnection(info: EditorInfo): InputConnection? { + if (imeMode == 0) return null + info.inputType = InputType.TYPE_CLASS_TEXT or (if (imeMode == 2) InputType.TYPE_TEXT_VARIATION_PASSWORD else InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS) + info.imeOptions = EditorInfo.IME_ACTION_DONE or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING + return object : BaseInputConnection(this, false) { + private var composing: String? = null + override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean { + if (composing == null) input(1, "") + composing = text?.toString().orEmpty() + input(2, composing.orEmpty()) + return true + } + override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean { + input(if (composing == null) 0 else 3, text?.toString().orEmpty()) + composing = null + return true + } + override fun finishComposingText(): Boolean { + composing?.let { input(3, it) } + composing = null + return true + } + override fun deleteSurroundingText(before: Int, after: Int): Boolean { + repeat(before.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_DEL) } + repeat(after.coerceIn(0, 2048)) { key(KeyEvent.KEYCODE_FORWARD_DEL) } + return true + } + override fun sendKeyEvent(event: KeyEvent): Boolean = dispatchKeyEvent(event) + override fun performEditorAction(action: Int): Boolean { key(KeyEvent.KEYCODE_ENTER); return true } + } + } + override fun onKeyDown(code: Int, event: KeyEvent): Boolean { + when (code) { + KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_TAB, KeyEvent.KEYCODE_DEL, + KeyEvent.KEYCODE_FORWARD_DEL, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> key(code) + else -> { + val point = event.unicodeChar + if (point <= 0) return super.onKeyDown(code, event) + input(0, String(Character.toChars(point))) + } + } + return true + } +} diff --git a/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt b/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt new file mode 100644 index 0000000..4b50e67 --- /dev/null +++ b/android/app/src/main/java/cy/hexor/tsunagi/MeshVpn.kt @@ -0,0 +1,197 @@ +package cy.hexor.tsunagi + +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Intent +import android.net.ConnectivityManager +import android.net.DnsResolver +import android.net.Network +import android.net.LinkProperties +import android.net.NetworkCapabilities +import android.net.NetworkRequest +import android.net.VpnService +import android.os.Handler +import android.os.Build +import android.os.CancellationSignal +import android.os.Looper +import android.os.ParcelFileDescriptor +import android.system.OsConstants +import java.util.concurrent.CompletableFuture +import java.util.concurrent.TimeUnit + +class MeshVpn : VpnService() { + companion object { + const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN" + private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT" + private const val NOTIFICATION_ID = 1 + private const val EXIT_CHANNEL = "exit-node" + } + private val main = Handler(Looper.getMainLooper()) + private val notifications by lazy { getSystemService(NotificationManager::class.java) } + @Volatile private var instance = 0L + private var closed = false + private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) } + @Volatile private var upstream: Network? = null + private var watching = false + private val changes = object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) = useUnderlay(network) + override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { + if (network == upstream && !closed) updateAddresses(properties) + } + override fun onLost(network: Network) { + if (network != upstream || closed) return + upstream = null + // Keep the binding to the lost network until its replacement is ready. + // Falling back to the default network here could send iroh into its own TUN. + setUnderlyingNetworks(emptyArray()) + physicalAddresses = "" + Native.networkChanged(instance, "") + } + } + + private var physicalAddresses = "" + private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty() + .mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",") + private fun updateAddresses(properties: LinkProperties) { + val next = addresses(properties) + if (next == physicalAddresses) return + physicalAddresses = next + Native.networkChanged(instance, next) + } + + @Synchronized private fun useUnderlay(network: Network) { + if (closed || !connectivity.bindProcessToNetwork(network)) return + upstream = network + setUnderlyingNetworks(arrayOf(network)) + physicalAddresses = addresses(connectivity.getLinkProperties(network)) + if (instance == 0L) { + Native.trust(applicationContext) + instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses) + } else Native.networkChanged(instance, physicalAddresses) + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY } + DISCONNECT_EXIT -> { + val ids = intent.data?.pathSegments.orEmpty() + if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) { + if (!Native.disconnectExit(instance, ids[0], ids[1])) { + android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show() + } + } else if (!watching) stopSelf(startId) + return START_NOT_STICKY + } + } + if (watching) { + if (Native.failed(instance)) { + Native.stop(instance) + instance = 0 + upstream?.let(::useUnderlay) + } + return START_NOT_STICKY + } + notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW)) + notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW)) + val startup = notification("vpn").setContentTitle("Starting mesh VPN") + if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED) + startForeground(NOTIFICATION_ID, startup.build()) + watching = true + connectivity.requestNetwork(NetworkRequest.Builder() + .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper())) + return START_NOT_STICKY + } + + private fun notification(channel: String): Notification.Builder { + val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + return Notification.Builder(this, channel).setSmallIcon(R.drawable.tsunagi) + .setContentIntent(open).setOngoing(true).setOnlyAlertOnce(true).setShowWhen(false) + .setCategory(Notification.CATEGORY_SERVICE) + } + + // Rust publishes a change even when the activity is closed. Android holds its + // own service binding for an established TUN, so mesh-only mode can leave + // foreground promotion and remove the app's notification. + fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String) { + main.post { + if (closed || session != instance) return@post + if (peer.isEmpty()) { + stopForeground(STOP_FOREGROUND_REMOVE) + return@post + } + val target = android.net.Uri.Builder().scheme("tsunagi").authority("exit") + .appendPath(network).appendPath(peer).build() + val disconnect = PendingIntent.getService(this, 1, + Intent(this, MeshVpn::class.java).setAction(DISCONNECT_EXIT).setData(target).putExtra("instance", session), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val notice = notification(EXIT_CHANNEL).setContentTitle(title).setContentText(text) + .addAction(Notification.Action.Builder(null, "Disconnect exit node", disconnect).build()) + if (Build.VERSION.SDK_INT >= 31) notice.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_IMMEDIATE) + startForeground(NOTIFICATION_ID, notice.build()) + } + } + + // Called from Rust with the exhaustive local plan; detachFd transfers ownership. + @Synchronized fun establishTun(addresses: String, routes: String, dns: String, mtu: Int, fullTunnel: Boolean): Int { + if (closed) return -1 + val builder = Builder().setSession("tsunagi").setMtu(mtu).setBlocking(false) + builder.setUnderlyingNetworks(upstream?.let { arrayOf(it) } ?: emptyArray()) + addresses.split(',').forEach { builder.addAddress(it.substringBefore('/'), it.substringAfter('/').toInt()) } + routes.split(',').forEach { builder.addRoute(it.substringBefore('/'), it.substringAfter('/').toInt()) } + if (dns.isNotEmpty()) builder.addDnsServer(dns) + // Mesh exits currently carry IPv4. Android blocks an unconfigured family + // unless explicitly allowed. In split mode ordinary IPv6 should pass. + if (!fullTunnel) builder.allowFamily(OsConstants.AF_INET6) + return builder.establish()?.detachFd() ?: -1 + } + + // Called on a bounded Rust blocking worker, never on the UI or TUN reader. + @android.annotation.TargetApi(29) + fun resolveDns(query: ByteArray): ByteArray? { + val network = upstream ?: return null + val result = CompletableFuture() + val cancel = CancellationSignal() + return try { + DnsResolver.getInstance().rawQuery(network, query, DnsResolver.FLAG_EMPTY, { it.run() }, cancel, + object : DnsResolver.Callback { + override fun onAnswer(answer: ByteArray, rcode: Int) { result.complete(answer) } + override fun onError(error: DnsResolver.DnsException) { result.completeExceptionally(error) } + }) + result.get(4, TimeUnit.SECONDS) + } catch (_: Exception) { null } finally { cancel.cancel() } + } + + // Android 8 and 9 expose only address lookups through their system resolver. + fun resolveAddresses(host: String): String? = try { + upstream?.getAllByName(host)?.mapNotNull { it.hostAddress }?.joinToString(",") + } catch (_: java.net.UnknownHostException) { null } + + // The endpoint uses the physical network. This one explicitly selected TCP + // socket must instead follow the same VPN as applications using the VIP. + @Suppress("DEPRECATION") + fun bindOverlaySocket(fd: Int, source: String): Boolean { + val vpn = connectivity.allNetworks.firstOrNull { network -> + connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true && + connectivity.getLinkProperties(network)?.linkAddresses?.any { it.address.hostAddress == source } == true + } ?: return false + return try { + ParcelFileDescriptor.fromFd(fd).use { vpn.bindSocket(it.fileDescriptor) } + true + } catch (_: java.io.IOException) { false } + } + + override fun onRevoke() { shutdown(); stopSelf() } + override fun onDestroy() { shutdown(); super.onDestroy() } + @Synchronized private fun shutdown() { + if (closed) return + closed = true + if (watching) connectivity.unregisterNetworkCallback(changes) + if (instance != 0L) Native.stop(instance) + connectivity.bindProcessToNetwork(null) + stopForeground(STOP_FOREGROUND_REMOVE) + } +} diff --git a/android/app/src/main/java/cy/hexor/tsunagi/Native.kt b/android/app/src/main/java/cy/hexor/tsunagi/Native.kt new file mode 100644 index 0000000..3c5e994 --- /dev/null +++ b/android/app/src/main/java/cy/hexor/tsunagi/Native.kt @@ -0,0 +1,21 @@ +package cy.hexor.tsunagi + +import android.content.Context + +/** OS entry points. Network commands and all views live in the Rust library. */ +internal object Native { + init { System.loadLibrary("tsunagi_android") } + external fun trust(context: Context) + external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long + external fun failed(instance: Long): Boolean + external fun stop(instance: Long) + external fun disconnectExit(instance: Long, network: String, peer: String): Boolean + external fun networkChanged(instance: Long, addresses: String) + + external fun surface() + external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long + external fun touch(action: Int, id: Int, x: Float, y: Float) + external fun input(kind: Int, value: String) + external fun key(key: Int) + external fun back(host: MeshSurface) +} diff --git a/android/app/src/main/res/drawable/tsunagi.xml b/android/app/src/main/res/drawable/tsunagi.xml new file mode 100644 index 0000000..c7af5e8 --- /dev/null +++ b/android/app/src/main/res/drawable/tsunagi.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..d60c541 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,2 @@ +android.useAndroidX=true +org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8 diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..d997cfc60f4cff0e7451d19d49a82fa986695d07 GIT binary patch literal 48966 zcma&NW0WmQwk%w>ZQHhO+qUi6W!pA(xoVef+k2O7+pkXd9rt^$@9p#T8Y9=Q^(R-x zjL3*NQ$ZRS1O)&B0s;U4fbe_$e;)(@NB~(;6+v1_IWc+}NnuerWl>cXPyoQcezKvZ z?Yzc@<~LK@Yhh-7jwvSDadFw~t7KfJ%AUfU*p0wc+3m9#p=Zo4`H`aA_wBL6 z9Q`7!;Ok~8YhZ^Vt#N97bt5aZ#mQc8r~hs3;R?H6V4(!oxSADTK|DR2PL6SQ3v6jM<>eLMh9 zAsd(APyxHNFK|G4hA_zi+YV?J+3K_*DIrdla>calRjaE)4(?YnX+AMqEM!Y|ED{^2 zI5gZ%nG-1qAVtl==8o0&F1N+aPj`Oo99RfDNP#ZHw}}UKV)zw6yy%~8Se#sKr;3?g zJGOkV2luy~HgMlEJB+L<_$@9sUXM7@bI)>-K!}JQUCUwuMdq@68q*dV+{L#Vc?r<( z?Wf1Hb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@q1b$GG0VQ_)`{MeylBlVfy%UHR=;Z98>T3M&;{0i?+0T-Bck?I)AUQrz zeF**_iGu$JlCpLnFv`D9?q6R51jKPM{Rd6!0FF#KP=O|b3iQX*TqXSjO?gXaXAmLr zU#g&%@+XpjVArlGkfaPKk^PUSnMLsjlK<9nH*zxl^V2-jGC$4+HGE%?F3%4|y9>HN z|FJgz*HW$VwU8$RNtuBf(2vdZhW3x;R6%eoJM(|2zvKebxCh$s5J-*fhZ75B_yeUs zFTrToFiB^SNH?gV2>l?G&h!UD>UP%uKh1L;Er59!q&NoZRe$VEf?5Ar^&iUad&2gQ z&WE`E%lTg=_3XQT@gJOjkAi-Hbbqrl{(pA<>_GH4O8+xI^=IAhS#v+$vmgOK=>C!~_xFg-pLM>6kUfy=zL|u~KkNJ< z$L?p*?;%(Ze6w%%M(zjE|4dH&5$)_}mG3z{KUQ6s!Y@_+kInPH;kAC&{T^5HKmqz@ z@+!aA{YNIy&r;uKTz=r6e6v>d-%9<%_4R!+-iN^8H#0N(rQbiu-u&}-|2`q@k1agM zdHkW_1&%VDD_|I;NpK*OZfAjAb z`Ttl8km0{|{F`kWKWltH$^Ech;G2y`{7&N^%H;d0$cGv7Z^oJNOSiwAFaP<=em}wX z<8AA6<}bbeZc_7S=ii6PALi)3nOXL)o&Uj%-OnQ52M&L%(%ZaWiu^(R{b!Bu2WJl< h$Zw`p^gE5e2}ml*LW4$nU|{5+pXG<~Ugg7I{||-5t(pJ; literal 0 HcmV?d00001 diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c61a118 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..739907d --- /dev/null +++ b/android/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..c4bdd3a --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..56c6e87 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,3 @@ +pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } } +rootProject.name = 'tsunagi-android' +include ':app' diff --git a/crates/tsunagi-android/Cargo.toml b/crates/tsunagi-android/Cargo.toml new file mode 100644 index 0000000..86d8525 --- /dev/null +++ b/crates/tsunagi-android/Cargo.toml @@ -0,0 +1,42 @@ +[package] +name = "tsunagi-android" +version = "1.0.0" +description = "Android VPN client and egui views for tsunagi." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.0" } +tsunagi-ui = { path = "../tsunagi-ui" } +tsunagi-core = { path = "../tsunagi-core" } +tsunagi-wg-quic = { path = "../tsunagi-wg-quic" } +egui = "0.31" +egui-phosphor = "0.9" +tokio.workspace = true +bytes.workspace = true +zeroize = "1.9" +simple-dns = "0.12" + +[target.'cfg(unix)'.dependencies] +rand = "0.10" +smoltcp = { version = "0.12", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "socket-tcp", "socket-udp"] } + +[target.'cfg(target_os = "android")'.dependencies] +egui_glow = { version = "0.31", default-features = false } +jni = "0.21" +iroh.workspace = true +jni-verifier = { package = "jni", version = "0.22" } +rustls-platform-verifier = "0.7" + +[dev-dependencies] +tempfile.workspace = true +tsunagi-core = { path = "../tsunagi-core", features = ["testing"] } + +[lints] +workspace = true diff --git a/crates/tsunagi-android/src/android/display.rs b/crates/tsunagi-android/src/android/display.rs new file mode 100644 index 0000000..fcd3e2f --- /dev/null +++ b/crates/tsunagi-android/src/android/display.rs @@ -0,0 +1,263 @@ +//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets. +use crate::view::{Phone, SystemAction}; +use egui::{ + Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase, +}; +use egui_glow::{Painter, glow}; +use jni::{ + JNIEnv, + objects::{JObject, JString, JValue}, + sys::{jfloat, jint, jlong}, +}; +use std::{ + cell::RefCell, + ffi::{c_char, c_void}, + sync::Arc, + time::Instant, +}; + +#[link(name = "EGL")] +unsafe extern "C" { + fn eglGetProcAddress(name: *const c_char) -> *const c_void; +} + +struct Display { + painter: Painter, + ctx: egui::Context, + ui: Phone, + events: Vec, + primary: Option, + start: Instant, + ime: i32, + exit_active: bool, +} +thread_local! { static DISPLAY: RefCell> = const {RefCell::new(None)}; } + +fn with_display(f: impl FnOnce(&mut Display) -> T) -> T { + DISPLAY.with_borrow_mut(|d| d.as_mut().map(f).unwrap_or_default()) +} + +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) { + // SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current. + let gl = unsafe { + glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr())) + }; + let Ok(painter) = Painter::new(Arc::new(gl), "", None, false) else { + let _ = env.throw_new( + "java/lang/IllegalStateException", + "Could not initialise OpenGL ES", + ); + return; + }; + let ctx = egui::Context::default(); + crate::view::configure(&ctx); + DISPLAY.with_borrow_mut(|d| { + // If Android discarded the old EGL context, its GPU resources are already gone. + let ui = d.take().map(|old| old.ui).unwrap_or_default(); + *d = Some(Display { + painter, + ctx, + ui, + events: Vec::new(), + primary: None, + start: Instant::now(), + ime: -1, + exit_active: false, + }); + }); +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_draw( + mut env: JNIEnv, + _: JObject, + host: JObject, + w: jint, + h: jint, + scale: jfloat, +) -> jlong { + with_display(|d| { + let size = egui::vec2(w as f32, h as f32) / scale; + let mut input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)), + events: std::mem::take(&mut d.events), + time: Some(d.start.elapsed().as_secs_f64()), + ..Default::default() + }; + if let Some(info) = input.viewports.get_mut(&egui::ViewportId::ROOT) { + info.native_pixels_per_point = Some(scale); + } + let mut action = None; + let state = super::status(); + let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some())); + if exit_active && !d.exit_active { + let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]); + } + d.exit_active = exit_active; + let output = d.ctx.run(input, |ctx| { + action = d.ui.draw(ctx, &state, super::send); + }); + if let Some(action) = action { + let method = match action { + SystemAction::Start => "startVpn", + SystemAction::Stop => "stopVpn", + SystemAction::PasteSecret => "pasteSecret", + SystemAction::Finish => "closeScreen", + }; + let _ = env.call_method(&host, method, "()V", &[]); + } + if let Some(secret) = d.ui.take_copied_secret() + && let Ok(text) = env.new_string(secret.as_str()) + { + let _ = env.call_method( + &host, + "copySecret", + "(Ljava/lang/String;)V", + &[JValue::Object(&text)], + ); + } + for command in output.platform_output.commands { + let (method, value) = match command { + egui::OutputCommand::CopyText(text) => ("copyText", text), + egui::OutputCommand::OpenUrl(url) => ("openUrl", url.url), + _ => continue, + }; + if let Ok(text) = env.new_string(value) { + let _ = env.call_method( + &host, + method, + "(Ljava/lang/String;)V", + &[JValue::Object(&text)], + ); + } + } + let ime = if output.platform_output.ime.is_none() { + 0 + } else if d.ui.secret_focused(&d.ctx) { + 2 + } else { + 1 + }; + if ime != d.ime { + d.ime = ime; + let _ = env.call_method(&host, "keyboard", "(I)V", &[JValue::Int(ime)]); + } + let ppp = output.pixels_per_point; + let primitives = d.ctx.tessellate(output.shapes, ppp); + let pixels = [w as u32, h as u32]; + d.painter.clear(pixels, [0.1, 0.1, 0.1, 1.0]); + d.painter + .paint_and_update_textures(pixels, ppp, &primitives, &output.textures_delta); + output + .viewport_output + .get(&egui::ViewportId::ROOT) + .map_or(1000, |v| { + v.repaint_delay.as_millis().clamp(16, 1000) as jlong + }) + }) +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_touch( + _: JNIEnv, + _: JObject, + action: jint, + id: jint, + x: jfloat, + y: jfloat, +) { + with_display(|d| { + let pos = egui::pos2(x, y); + let phase = match action { + 0 => TouchPhase::Start, + 1 => TouchPhase::Move, + 2 => TouchPhase::End, + _ => TouchPhase::Cancel, + }; + d.events.push(Event::Touch { + device_id: TouchDeviceId(0), + id: TouchId(id as u64), + phase, + pos, + force: None, + }); + if phase == TouchPhase::Start && d.primary.is_none() { + d.primary = Some(id); + } + if d.primary != Some(id) { + return; + } + if phase != TouchPhase::Cancel { + d.events.push(Event::PointerMoved(pos)); + } + if phase != TouchPhase::Move { + if phase == TouchPhase::Cancel { + d.events.push(Event::PointerGone); + } + d.events.push(Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed: phase == TouchPhase::Start, + modifiers: Modifiers::NONE, + }); + } + if matches!(phase, TouchPhase::Cancel | TouchPhase::End) { + d.events.push(Event::PointerGone); + d.primary = None; + } + }); +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_input( + mut env: JNIEnv, + _: JObject, + kind: jint, + value: JString, +) { + let Ok(text) = env.get_string(&value) else { + return; + }; + let text = String::from(text); + with_display(|d| match kind { + 0 => d.events.push(Event::Text(text)), + 1 => d.events.push(Event::Ime(ImeEvent::Enabled)), + 2 => d.events.push(Event::Ime(ImeEvent::Preedit(text))), + 3 => { + d.events.push(Event::Ime(ImeEvent::Commit(text))); + d.events.push(Event::Ime(ImeEvent::Disabled)); + } + 4 => d.ui.paste_secret(text), + 5 => d.ui.error(text), + _ => {} + }); +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_key(_: JNIEnv, _: JObject, key: jint) { + let key = match key { + 67 => Key::Backspace, + 112 => Key::Delete, + 66 => Key::Enter, + 21 => Key::ArrowLeft, + 22 => Key::ArrowRight, + 61 => Key::Tab, + _ => return, + }; + with_display(|d| { + for pressed in [true, false] { + d.events.push(Event::Key { + key, + physical_key: None, + pressed, + repeat: false, + modifiers: Modifiers::NONE, + }); + } + }); +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_back(mut env: JNIEnv, _: JObject, host: JObject) { + with_display(|d| { + if d.ui.back() == Some(SystemAction::Finish) { + let _ = env.call_method(&host, "closeScreen", "()V", &[]); + } + }); +} diff --git a/crates/tsunagi-android/src/android/dns.rs b/crates/tsunagi-android/src/android/dns.rs new file mode 100644 index 0000000..a538178 --- /dev/null +++ b/crates/tsunagi-android/src/android/dns.rs @@ -0,0 +1,90 @@ +//! Android's physical-network resolver, including its Private DNS policy. +use crate::dns::Resolver; +use jni::{ + JNIEnv, JavaVM, + objects::{GlobalRef, JByteArray, JString, JValue}, +}; +use simple_dns::{CLASS, Packet, PacketFlag, QTYPE, RCODE, ResourceRecord, TYPE, rdata::RData}; +use std::{net::IpAddr, sync::Arc}; + +pub(super) fn resolver(vm: Arc, service: GlobalRef, sdk: i32) -> Resolver { + Resolver::new(move |query| { + let mut env = vm.attach_current_thread().ok()?; + let response = env.with_local_frame(6, |env| { + if sdk < 29 { + return legacy(env, &service, query); + } + let bytes = env.byte_array_from_slice(query)?; + let reply = env + .call_method(&service, "resolveDns", "([B)[B", &[JValue::Object(&bytes)])? + .l()?; + if reply.is_null() { + return Ok(None); + } + let reply = JByteArray::from(reply); + if env.get_array_length(&reply)? > i32::from(u16::MAX) { + return Ok(None); + } + env.convert_byte_array(reply).map(Some) + }); + if env.exception_check().unwrap_or(false) { + let _ = env.exception_clear(); + return None; + } + response.ok().flatten() + }) +} + +fn legacy( + env: &mut JNIEnv<'_>, + service: &GlobalRef, + query: &[u8], +) -> jni::errors::Result>> { + let Some(packet) = Packet::parse(query).ok() else { + return Ok(None); + }; + let [question] = packet.questions.as_slice() else { + return Ok(None); + }; + let mut reply = Packet::new_reply(packet.id()); + reply.questions.push(question.clone()); + reply.set_flags(PacketFlag::RECURSION_AVAILABLE); + if packet.has_flags(PacketFlag::RECURSION_DESIRED) { + reply.set_flags(PacketFlag::RECURSION_DESIRED); + } + if matches!(question.qtype, QTYPE::TYPE(TYPE::A | TYPE::AAAA)) { + let name = env.new_string(format!("{}.", question.qname))?; + let addresses = env + .call_method( + service, + "resolveAddresses", + "(Ljava/lang/String;)Ljava/lang/String;", + &[JValue::Object(&name)], + )? + .l()?; + if addresses.is_null() { + return Ok(None); + } + let addresses: String = env.get_string(&JString::from(addresses))?.into(); + for address in addresses + .split(',') + .take(128) + .filter_map(|s| s.parse::().ok()) + { + let data = match (question.qtype, address) { + (QTYPE::TYPE(TYPE::A), IpAddr::V4(v4)) => RData::A(v4.into()), + (QTYPE::TYPE(TYPE::AAAA), IpAddr::V6(v6)) => RData::AAAA(v6.into()), + _ => continue, + }; + reply.answers.push(ResourceRecord::new( + question.qname.clone(), + CLASS::IN, + 0, + data, + )); + } + } else { + *reply.rcode_mut() = RCODE::NotImplemented; + } + Ok(reply.build_bytes_vec_compressed().ok()) +} diff --git a/crates/tsunagi-android/src/android/mod.rs b/crates/tsunagi-android/src/android/mod.rs new file mode 100644 index 0000000..6fd8c3f --- /dev/null +++ b/crates/tsunagi-android/src/android/mod.rs @@ -0,0 +1,366 @@ +//! Android process entry points. JNI owns references here, never in the core. +#![allow(unsafe_code)] +mod display; +mod dns; +use crate::{ + plan::VpnPlan, + service::{Reply, Request, Response, State}, + tun::AndroidTun, +}; +use jni::{ + JNIEnv, JavaVM, + objects::{GlobalRef, JObject, JString, JValue}, + sys::jlong, +}; +use std::{ + fs::File, + io, + os::fd::{AsRawFd, FromRawFd, OwnedFd}, + path::PathBuf, + sync::{Arc, Mutex, OnceLock}, +}; +use tokio::sync::{mpsc, oneshot, watch}; +use tsunagi::{Agent, AgentConfig, StoragePaths, TransportPolicy, discovery::MainlineDiscovery}; +use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin}; + +struct Session { + id: i64, + commands: mpsc::Sender<(Request, Reply)>, + state: watch::Receiver, + underlay: watch::Sender>, + stop: watch::Sender, +} +static SESSION: Mutex> = Mutex::new(None); +// Stop/start can cross on the Android main thread. The previous agent closes +// its fd, endpoint and directory lock before its successor opens that identity. +static LIFETIME: Mutex<()> = Mutex::new(()); + +fn current() -> std::sync::MutexGuard<'static, Option> { + SESSION.lock().unwrap_or_else(|e| e.into_inner()) +} +fn status() -> State { + current() + .as_ref() + .map(|s| s.state.borrow().clone()) + .unwrap_or_default() +} +fn send(cmd: tsunagi_ui::client::Command) -> Result { + let (reply, result) = oneshot::channel(); + current() + .as_ref() + .ok_or("VPN service stopped")? + .commands + .try_send((Request::Action(cmd), reply)) + .map_err(|_| "VPN service is busy or stopped".to_owned())?; + Ok(result) +} + +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_trust( + mut env: jni_verifier::EnvUnowned, + _: jni_verifier::objects::JObject, + app: jni_verifier::objects::JObject, +) { + env.with_env(|env| rustls_platform_verifier::android::init_with_env(env, app)) + .resolve::(); +} + +fn establish(vm: &JavaVM, service: &GlobalRef, plan: &VpnPlan) -> io::Result { + let mut env = vm.attach_current_thread().map_err(io::Error::other)?; + let addresses = plan + .addresses_in_order() + .iter() + .map(ToString::to_string) + .collect::>() + .join(","); + let routes = plan.routes().join(","); + let result = env.with_local_frame(6, |env| -> jni::errors::Result { + let addresses = env.new_string(addresses)?; + let routes = env.new_string(routes)?; + let dns = env.new_string( + plan.dns_address() + .map(|a| a.to_string()) + .unwrap_or_default(), + )?; + env.call_method( + service, + "establishTun", + "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)I", + &[ + JValue::Object(&addresses), + JValue::Object(&routes), + JValue::Object(&dns), + JValue::Int(plan.mtu as i32), + JValue::Bool(plan.full_tunnel.into()), + ], + )? + .i() + }); + if env.exception_check().unwrap_or(false) { + let _ = env.exception_clear(); + return Err(io::Error::other( + "Android could not establish the VPN. Check the VPN permission.", + )); + } + let fd = result.map_err(io::Error::other)?; + if fd < 0 { + return Err(io::Error::other("Android revoked the VPN permission")); + } + // SAFETY: establishTun transferred exclusive ownership with detachFd(). + Ok(File::from(unsafe { OwnedFd::from_raw_fd(fd) })) +} + +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_start( + mut env: JNIEnv, + _: JObject, + service: JObject, + app: JObject, + state_dir: JString, + cache_dir: JString, + addresses: JString, +) -> jlong { + let result = (|| -> Result> { + // Keep the application (never an activity) alive for DNS throughout the process. + static APPLICATION: OnceLock = OnceLock::new(); + let vm = Arc::new(env.get_java_vm()?); + let application = env.new_global_ref(app)?; + if APPLICATION.set(application.clone()).is_ok() { + // SAFETY: the VM and this stored global reference live until process exit. + unsafe { + iroh::dns::install_android_jni_context( + vm.get_java_vm_pointer().cast(), + application.as_obj().as_raw().cast(), + ); + } + } + let service = env.new_global_ref(service)?; + let state_dir: String = env.get_string(&state_dir)?.into(); + let cache_dir: String = env.get_string(&cache_dir)?.into(); + let paths = StoragePaths::new(PathBuf::from(state_dir), PathBuf::from(cache_dir)); + let tun_vm = vm.clone(); + let tun_service = service.clone(); + let notice_vm = vm.clone(); + let notice_service = service.clone(); + let sdk = env + .get_static_field("android/os/Build$VERSION", "SDK_INT", "I")? + .i()?; + let dns = dns::resolver(vm.clone(), service.clone(), sdk); + let factory = AndroidTun::new( + dns.clone(), + move |plan| establish(&tun_vm, &tun_service, plan), + move |socket, source| { + let mut env = vm.attach_current_thread().map_err(io::Error::other)?; + let result = env.with_local_frame(3, |env| -> jni::errors::Result { + let source = env.new_string(source.to_string())?; + env.call_method( + &service, + "bindOverlaySocket", + "(ILjava/lang/String;)Z", + &[JValue::Int(socket.as_raw_fd()), JValue::Object(&source)], + )? + .z() + }); + if env.exception_check().unwrap_or(false) { + let _ = env.exception_clear(); + return Err(io::Error::other("VPN socket binding failed")); + } + if result.map_err(io::Error::other)? { + Ok(()) + } else { + Err(io::Error::other("VPN network is unavailable")) + } + }, + ); + let addresses: String = env.get_string(&addresses)?.into(); + let (underlay, physical) = watch::channel(underlay_ips(&addresses)); + let (commands, rx) = mpsc::channel(16); + let (state, state_rx) = watch::channel(State::Starting); + let (stop, stopped) = watch::channel(false); + static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut slot = current(); + if let Some(old) = slot.as_ref() { + old.stop.send_replace(true); + } + std::thread::Builder::new() + .name("tsunagi-agent".into()) + .spawn(move || { + let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner()); + if *stopped.borrow() { + return; + } + let run = || -> Result<(), Box> { + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build()?; + runtime.block_on(async { + let wg = WireguardPlugin::open(WireguardConfig::new( + paths.state_dir.join("wg-quic"), + )) + .await?; + let config = AgentConfig::new(paths) + .with_transport(TransportPolicy::N0Defaults) + .with_dht(MainlineDiscovery::default()) + .with_interface(Arc::new(factory), "tsunagi-vpn", DEFAULT_MTU) + .with_tunnel(wg.clone()); + let (config, carriers) = tsunagi_runtime::Carriers::configure( + config, + &[], + Some(physical), + |_| Vec::new(), + ) + .await?; + let agent = Agent::spawn(config).await?; + let _listeners = carriers.listen(&agent); + crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| { + update_exit_notification(¬ice_vm, ¬ice_service, id, notice); + }) + .await; + Ok(()) + }) + }; + if let Err(e) = run() { + state.send_replace(State::Error(e.to_string())); + } + })?; + *slot = Some(Session { + id, + commands, + state: state_rx, + underlay, + stop, + }); + Ok(id) + })(); + match result { + Ok(id) => id, + Err(e) => { + let _ = env.throw_new("java/lang/IllegalStateException", e.to_string()); + 0 + } + } +} + +fn update_exit_notification( + vm: &JavaVM, + service: &GlobalRef, + id: i64, + notice: Option<&crate::service::ExitNotice>, +) { + let Ok(mut env) = vm.attach_current_thread() else { + return; + }; + let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> { + let network = env.new_string(notice.map_or("", |n| &n.network))?; + let peer = env.new_string(notice.map_or("", |n| &n.peer))?; + let title = env.new_string( + notice + .map(|n| format!("Exit node · {}", n.name)) + .unwrap_or_default(), + )?; + let text = env.new_string( + notice + .map(|n| { + if n.online { + format!("IPv4 internet via {}", n.network_name) + } else { + format!( + "{} · Exit offline. IPv4 internet is blocked.", + n.network_name + ) + } + }) + .unwrap_or_default(), + )?; + env.call_method( + service, + "updateExitNotification", + "(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V", + &[ + JValue::Long(id), + JValue::Object(&network), + JValue::Object(&peer), + JValue::Object(&title), + JValue::Object(&text), + ], + )?; + Ok(()) + }); + if env.exception_check().unwrap_or(false) { + let _ = env.exception_clear(); + } +} + +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit( + mut env: JNIEnv, + _: JObject, + id: jlong, + network: JString, + peer: JString, +) -> jni::sys::jboolean { + let (Ok(network), Ok(peer)) = (env.get_string(&network), env.get_string(&peer)) else { + return false.into(); + }; + current() + .as_ref() + .filter(|s| s.id == id) + .is_some_and(|s| { + s.commands + .try_send(( + Request::DisconnectExit { + network: network.into(), + peer: peer.into(), + }, + oneshot::channel().0, + )) + .is_ok() + }) + .into() +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_failed( + _: JNIEnv, + _: JObject, + id: jlong, +) -> jni::sys::jboolean { + current() + .as_ref() + .is_some_and(|s| s.id == id && matches!(*s.state.borrow(), State::Error(_))) + .into() +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id: jlong) { + let mut slot = current(); + if slot.as_ref().is_some_and(|s| s.id == id) + && let Some(session) = slot.take() + { + session.stop.send_replace(true); + } +} +fn underlay_ips(addresses: &str) -> Vec { + addresses + .split(',') + .take(32) + .filter_map(|s| s.parse().ok()) + .collect() +} +#[unsafe(no_mangle)] +extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged( + mut env: JNIEnv, + _: JObject, + id: jlong, + addresses: JString, +) { + let Ok(raw) = env.get_string(&addresses) else { + return; + }; + if let Some(s) = current().as_ref().filter(|s| s.id == id) { + s.underlay.send_replace(underlay_ips(&String::from(raw))); + let _ = s + .commands + .try_send((Request::NetworkChanged, oneshot::channel().0)); + } +} diff --git a/crates/tsunagi-android/src/dns.rs b/crates/tsunagi-android/src/dns.rs new file mode 100644 index 0000000..917c173 --- /dev/null +++ b/crates/tsunagi-android/src/dns.rs @@ -0,0 +1,122 @@ +//! Device-local split DNS. Only questions outside the signed mesh zones reach Android's resolver. +use simple_dns::{Packet, PacketFlag, RCODE}; +use std::{net::Ipv4Addr, sync::Arc, time::Duration}; +use tokio::sync::{Semaphore, watch}; +use tsunagi::dns::{ + Zones, + server::{MAX_MESSAGE_LEN, Resolution, parse_message, resolve}, +}; + +#[cfg(unix)] +pub(crate) mod stack; + +type Upstream = dyn Fn(&[u8]) -> Option> + Send + Sync; + +/// One view of all joined zones, shared across TUN replacements. +#[derive(Clone)] +pub struct Resolver { + zones: watch::Sender>>, + listening: watch::Sender>, + upstream: Arc, + pending: Arc, +} + +impl Resolver { + /// The platform callback resolves a wire question on the selected physical network. + pub fn new(upstream: impl Fn(&[u8]) -> Option> + Send + Sync + 'static) -> Self { + Self { + zones: watch::channel(None).0, + listening: watch::channel(None).0, + upstream: Arc::new(upstream), + pending: Arc::new(Semaphore::new(16)), + } + } + + /// Withhold forwarding while configured zones are loading or changing. + pub fn replace(&self, zones: Option) { + self.zones.send_replace(zones.map(Arc::new)); + } + + #[cfg(unix)] + pub(crate) fn publish(&self, address: Option) { + self.listening.send_replace(address); + } + + pub(crate) fn refresh(&self, networks: &[tsunagi::NetworkStatus]) -> tsunagi::ipc::DnsReport { + let view = tsunagi::dns::RosterZones::from_networks(networks); + let names = view.zones.names() as u32; + self.replace(Some(view.zones)); + let address = *self.listening.borrow(); + tsunagi::ipc::DnsReport { + listening: address.map(|ip| format!("{ip}:53")).into_iter().collect(), + publish_error: (address.is_none() && !view.labels.is_empty()) + .then(|| "Waiting for a VPN interface with a DNS address.".into()), + zones: view.labels, + zone_warnings: view.warnings, + names, + ..Default::default() + } + } + + /// Answer a local DNS request. Slow public lookups never block a mesh answer. + pub async fn answer(&self, query: &[u8]) -> Option> { + if query.len() > MAX_MESSAGE_LEN { + return None; + } + let zones = self.zones.borrow().clone(); + let Some(zones) = zones else { + let question = parse_message(query)?; + if question.has_flags(PacketFlag::RESPONSE) { + return None; + } + return error_reply(&question, RCODE::ServerFailure); + }; + match resolve(&zones, query)? { + Resolution::Local(reply) => Some(reply), + Resolution::Outside(_) => { + let question = parse_message(query)?; + if let Ok(permit) = self.pending.clone().try_acquire_owned() { + let upstream = self.upstream.clone(); + let wire = query.to_vec(); + let job = tokio::task::spawn_blocking(move || { + let _permit = permit; + upstream(&wire) + }); + if let Ok(Ok(Some(mut wire))) = + tokio::time::timeout(Duration::from_secs(5), job).await + && wire.len() <= usize::from(u16::MAX) + && parse_message(&wire).is_some_and(|p| { + let [received] = p.questions.as_slice() else { + return false; + }; + let sent = &question.questions[0]; // Resolution::Outside has exactly one IN question. + p.has_flags(PacketFlag::RESPONSE) + && received.qtype == sent.qtype + && received.qclass == sent.qclass + && received + .qname + .to_string() + .eq_ignore_ascii_case(&sent.qname.to_string()) + }) + { + // Android's upstream transaction may have used its own ID. + wire[..2].copy_from_slice(&question.id().to_be_bytes()); + return Some(wire); + } + } + error_reply(&question, RCODE::ServerFailure) + } + } + } +} + +fn error_reply(query: &Packet<'_>, code: RCODE) -> Option> { + let mut answer = Packet::new_reply(query.id()); + answer.questions.clone_from(&query.questions); + if query.has_flags(PacketFlag::RECURSION_DESIRED) { + answer.set_flags(PacketFlag::RECURSION_DESIRED); + } + answer.set_flags(PacketFlag::RECURSION_AVAILABLE); + *answer.rcode_mut() = code; + answer.build_bytes_vec_compressed().ok() +} diff --git a/crates/tsunagi-android/src/dns/stack.rs b/crates/tsunagi-android/src/dns/stack.rs new file mode 100644 index 0000000..de2218e --- /dev/null +++ b/crates/tsunagi-android/src/dns/stack.rs @@ -0,0 +1,311 @@ +//! A DNS-only endpoint on the application side of one Android TUN descriptor. +//! The kernel reserves port 53. smoltcp terminates UDP and TCP without root. +use super::Resolver; +use smoltcp::{ + iface::{Config, Interface, SocketHandle, SocketSet}, + phy::{self, Device, DeviceCapabilities, Medium}, + socket::{tcp, udp}, + time::Instant as NetTime, + wire::{HardwareAddress, IpAddress, IpCidr, IpEndpoint}, +}; +use std::{ + collections::VecDeque, + fs::File, + io::Write, + net::{IpAddr, Ipv4Addr}, + sync::Arc, + time::{Duration, Instant}, +}; +use tokio::{ + io::{Interest, unix::AsyncFd}, + sync::mpsc, + task::{JoinHandle, JoinSet}, +}; +use tsunagi::dns::server::{MAX_MESSAGE_LEN, truncate_for_udp}; + +const PORT: u16 = 53; +const QUEUE: usize = 32; +const TCP_CLIENTS: usize = 8; + +#[cfg(test)] +mod tests; + +pub(crate) struct DnsPort { + address: Ipv4Addr, + input: mpsc::Sender>, + worker: JoinHandle<()>, +} + +impl DnsPort { + pub(crate) fn start( + address: Ipv4Addr, + mtu: usize, + resolver: Resolver, + fd: Arc>, + ) -> Self { + let (input, packets) = mpsc::channel(QUEUE); + let worker = tokio::spawn(run(address, mtu, resolver, packets, fd)); + Self { + address, + input, + worker, + } + } + + /// Consume only packets sent to our private endpoint by a local VPN address. + pub(crate) fn intercept(&self, bytes: &[u8], local: &[IpAddr]) -> bool { + let Ok(packet) = smoltcp::wire::Ipv4Packet::new_checked(bytes) else { + return false; + }; + if packet.version() != 4 || packet.dst_addr() != self.address { + return false; + } + if local.contains(&IpAddr::V4(packet.src_addr())) { + let _ = self.input.try_send(bytes.to_vec()); + } + true + } +} + +impl Drop for DnsPort { + fn drop(&mut self) { + self.worker.abort(); + } +} + +struct Wire { + mtu: usize, + input: Option>, + output: VecDeque>, +} +struct Rx(Vec); +impl phy::RxToken for Rx { + fn consume R>(self, f: F) -> R { + f(&self.0) + } +} +struct Tx<'a>(&'a mut VecDeque>); +impl phy::TxToken for Tx<'_> { + fn consume R>(self, len: usize, f: F) -> R { + let mut packet = vec![0; len]; + let result = f(&mut packet); + self.0.push_back(packet); + result + } +} +impl Device for Wire { + type RxToken<'a> = Rx; + type TxToken<'a> = Tx<'a>; + fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> { + self.input + .take() + .map(|packet| (Rx(packet), Tx(&mut self.output))) + } + fn transmit(&mut self, _: NetTime) -> Option> { + (self.output.len() < QUEUE).then_some(Tx(&mut self.output)) + } + fn capabilities(&self) -> DeviceCapabilities { + let mut caps = DeviceCapabilities::default(); + caps.medium = Medium::Ip; + caps.max_transmission_unit = self.mtu; + caps + } +} + +struct TcpSlot { + handle: SocketHandle, + pending: Option, +} +enum Client { + Udp(IpEndpoint), + Tcp { slot: usize, request: u64 }, +} +type Jobs = JoinSet<(Client, Option>)>; + +struct Stack { + iface: Interface, + wire: Wire, + sockets: SocketSet<'static>, + udp: SocketHandle, + tcp: Vec, + next_request: u64, +} + +impl Stack { + fn new(address: Ipv4Addr, mtu: usize) -> Self { + let mut wire = Wire { + mtu, + input: None, + output: VecDeque::new(), + }; + let mut config = Config::new(HardwareAddress::Ip); + config.random_seed = rand::random(); + let mut iface = Interface::new(config, &mut wire, NetTime::from_millis(0)); + // This is a point-to-point IP device. Its only neighbour is Android, whatever + // the OS chose as the source address among the attached networks. + iface.update_ip_addrs(|addrs| { + let _ = addrs.push(IpCidr::new(IpAddress::Ipv4(address), 0)); + }); + let mut sockets = SocketSet::new(Vec::new()); + let datagrams = || { + udp::PacketBuffer::new( + vec![udp::PacketMetadata::EMPTY; QUEUE], + vec![0; QUEUE * mtu], + ) + }; + let mut socket = udp::Socket::new(datagrams(), datagrams()); + let _ = socket.bind(PORT); + let udp = sockets.add(socket); + let tcp = (0..TCP_CLIENTS) + .map(|_| { + let mut socket = tcp::Socket::new( + tcp::SocketBuffer::new(vec![0; MAX_MESSAGE_LEN + 2]), + tcp::SocketBuffer::new(vec![0; usize::from(u16::MAX) + 2]), + ); + socket.set_timeout(Some(smoltcp::time::Duration::from_secs(10))); + let _ = socket.listen(PORT); + TcpSlot { + handle: sockets.add(socket), + pending: None, + } + }) + .collect(); + Self { + iface, + wire, + sockets, + udp, + tcp, + next_request: 0, + } + } + + fn poll(&mut self, now: NetTime) { + self.iface.poll(now, &mut self.wire, &mut self.sockets); + } + + fn dispatch(&mut self, resolver: &Resolver, jobs: &mut Jobs) { + let udp = self.sockets.get_mut::(self.udp); + while let Ok((wire, metadata)) = udp.recv() { + if jobs.len() >= QUEUE || wire.len() > MAX_MESSAGE_LEN { + continue; + } + let resolver = resolver.clone(); + let query = wire.to_vec(); + let limit = self.wire.mtu.saturating_sub(28); + jobs.spawn(async move { + let reply = resolver + .answer(&query) + .await + .map(|reply| truncate_for_udp(&query, reply, limit)); + (Client::Udp(metadata.endpoint), reply) + }); + } + for (index, slot) in self.tcp.iter_mut().enumerate() { + let tcp = self.sockets.get_mut::(slot.handle); + if !tcp.is_open() { + slot.pending = None; + let _ = tcp.listen(PORT); + } + if slot.pending.is_some() || tcp.send_queue() != 0 { + continue; + } + if tcp.state() == tcp::State::CloseWait && tcp.recv_queue() < 2 { + tcp.close(); + continue; + } + let mut header = [0; 2]; + if tcp.peek_slice(&mut header) != Ok(2) { + continue; + } + let len = usize::from(u16::from_be_bytes(header)); + if !(12..=MAX_MESSAGE_LEN).contains(&len) { + tcp.abort(); + continue; + } + if tcp.recv_queue() < len + 2 || jobs.len() >= QUEUE { + continue; + } + let mut query = vec![0; len]; + if tcp.recv_slice(&mut header) != Ok(2) || tcp.recv_slice(&mut query) != Ok(len) { + tcp.abort(); + continue; + } + self.next_request = self.next_request.wrapping_add(1); + let request = self.next_request; + slot.pending = Some(request); + let resolver = resolver.clone(); + jobs.spawn(async move { + ( + Client::Tcp { + slot: index, + request, + }, + resolver.answer(&query).await, + ) + }); + } + } + + fn deliver(&mut self, client: Client, reply: Option>) { + match client { + Client::Udp(peer) => { + if let Some(reply) = reply { + let _ = self + .sockets + .get_mut::(self.udp) + .send_slice(&reply, peer); + } + } + Client::Tcp { slot, request } => { + let slot = &mut self.tcp[slot]; + if slot.pending != Some(request) { + return; + } + slot.pending = None; + let tcp = self.sockets.get_mut::(slot.handle); + if let Some(reply) = reply + && let Ok(len) = u16::try_from(reply.len()) + && tcp.send_slice(&len.to_be_bytes()) == Ok(2) + && tcp.send_slice(&reply) == Ok(reply.len()) + { + return; + } + tcp.abort(); + } + } + } +} + +async fn run( + address: Ipv4Addr, + mtu: usize, + resolver: Resolver, + mut input: mpsc::Receiver>, + fd: Arc>, +) { + let mut stack = Stack::new(address, mtu); + let mut jobs = Jobs::new(); + let start = Instant::now(); + loop { + let now = NetTime::from_millis(start.elapsed().as_millis() as i64); + stack.poll(now); + stack.dispatch(&resolver, &mut jobs); + stack.poll(now); + while let Some(packet) = stack.wire.output.pop_front() { + if !matches!(fd.async_io(Interest::WRITABLE, |mut file| file.write(&packet)).await, Ok(n) if n == packet.len()) + { + return; + } + } + let delay = stack + .iface + .poll_delay(now, &stack.sockets) + .map(Duration::from); + tokio::select! { + packet = input.recv() => match packet { Some(packet) => stack.wire.input = Some(packet), None => return }, + Some(Ok((client, reply))) = jobs.join_next(), if !jobs.is_empty() => stack.deliver(client, reply), + _ = async { if let Some(delay) = delay { tokio::time::sleep(delay).await } else { std::future::pending().await } } => {} + } + } +} diff --git a/crates/tsunagi-android/src/dns/stack/tests.rs b/crates/tsunagi-android/src/dns/stack/tests.rs new file mode 100644 index 0000000..cab51b5 --- /dev/null +++ b/crates/tsunagi-android/src/dns/stack/tests.rs @@ -0,0 +1,105 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +use super::*; +use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, TYPE}; +use std::os::{fd::OwnedFd, unix::net::UnixDatagram}; +use tsunagi::dns::{Zone, ZoneName, Zones}; + +#[tokio::test] +async fn android_tun_dns_truncates_udp_and_returns_the_complete_answer_over_tcp() { + let address = Ipv4Addr::new(192, 0, 2, 53); + let phone = Ipv4Addr::new(10, 10, 0, 1); + let (fd, os) = UnixDatagram::pair().unwrap(); + fd.set_nonblocking(true).unwrap(); + os.set_nonblocking(true).unwrap(); + let fd = AsyncFd::new(File::from(OwnedFd::from(fd))).unwrap(); + let os = tokio::net::UnixDatagram::from_std(os).unwrap(); + let resolver = Resolver::new(|_| panic!("a mesh name went upstream")); + resolver.replace(Some(Zones::new([Zone::new( + ZoneName::new("tsng").unwrap(), + (1..=90).map(|host| ("api".into(), Ipv4Addr::new(10, 1, 2, host))), + )]))); + let port = DnsPort::start(address, 1280, resolver, Arc::new(fd)); + let mut wire = Wire { + mtu: 1280, + input: None, + output: VecDeque::new(), + }; + let mut iface = Interface::new( + Config::new(HardwareAddress::Ip), + &mut wire, + NetTime::from_millis(0), + ); + iface.update_ip_addrs(|a| a.push(IpCidr::new(IpAddress::Ipv4(phone), 0)).unwrap()); + let mut sockets = SocketSet::new(Vec::new()); + let buf = || udp::PacketBuffer::new(vec![udp::PacketMetadata::EMPTY; 4], vec![0; 4096]); + let mut datagram = udp::Socket::new(buf(), buf()); + datagram.bind(41000).unwrap(); + let mut packet = Packet::new_query(42); + packet.questions.push(Question::new( + Name::new("api.tsng").unwrap(), + TYPE::A.into(), + CLASS::IN.into(), + false, + )); + let query = packet.build_bytes_vec().unwrap(); + datagram.send_slice(&query, (address, PORT)).unwrap(); + let udp = sockets.add(datagram); + let tcp = sockets.add(tcp::Socket::new( + tcp::SocketBuffer::new(vec![0; 8192]), + tcp::SocketBuffer::new(vec![0; 512]), + )); + let mut sent = false; + let mut received = Vec::new(); + let mut buf = [0; 1500]; + let start = Instant::now(); + tokio::time::timeout(Duration::from_secs(4), async { + loop { + let now = NetTime::from_millis(start.elapsed().as_millis() as i64); + iface.poll(now, &mut wire, &mut sockets); + if let Ok((reply, from)) = sockets.get_mut::(udp).recv() { + assert_eq!(from.endpoint, (address, PORT).into()); + let reply = Packet::parse(reply).unwrap(); + assert_eq!(reply.id(), 42); + assert!(reply.has_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER)); + sockets + .get_mut::(tcp) + .connect(iface.context(), (address, PORT), 41001) + .unwrap(); + } + let stream = sockets.get_mut::(tcp); + if stream.can_send() && !sent { + let mut frame = (query.len() as u16).to_be_bytes().to_vec(); + frame.extend_from_slice(&query); + assert_eq!(stream.send_slice(&frame).unwrap(), frame.len()); + sent = true; + } + while stream.can_recv() { + let n = stream.recv_slice(&mut buf).unwrap(); + received.extend_from_slice(&buf[..n]); + } + if let Some(prefix) = received.first_chunk::<2>() + && received.len() == 2 + usize::from(u16::from_be_bytes(*prefix)) + { + break; + } + iface.poll(now, &mut wire, &mut sockets); + for outgoing in wire.output.drain(..) { + assert!(port.intercept(&outgoing, &[phone.into()])); + } + let delay = iface + .poll_delay(now, &sockets) + .map(Duration::from) + .unwrap_or(Duration::from_secs(4)); + tokio::select! { + n = os.recv(&mut buf) => wire.input = Some(buf[..n.unwrap()].to_vec()), + _ = tokio::time::sleep(delay) => {} + } + } + }) + .await + .expect("DNS over the Android packet device must complete"); + let reply = Packet::parse(&received[2..]).unwrap(); + assert_eq!(reply.id(), 42); + assert!(!reply.has_flags(PacketFlag::TRUNCATION)); + assert_eq!(reply.answers.len(), 90); +} diff --git a/crates/tsunagi-android/src/lib.rs b/crates/tsunagi-android/src/lib.rs new file mode 100644 index 0000000..75c6a3a --- /dev/null +++ b/crates/tsunagi-android/src/lib.rs @@ -0,0 +1,13 @@ +//! The Android application. Mesh state belongs to one service-owned Rust agent. + +pub mod dns; +pub mod plan; + +#[cfg(target_os = "android")] +mod android; +pub mod service; +#[cfg(test)] +mod tests; +#[cfg(unix)] +pub mod tun; +pub mod view; diff --git a/crates/tsunagi-android/src/plan.rs b/crates/tsunagi-android/src/plan.rs new file mode 100644 index 0000000..5478d5a --- /dev/null +++ b/crates/tsunagi-android/src/plan.rs @@ -0,0 +1,85 @@ +//! All addresses and routes installed in the one Android VPN. +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; + +use tsunagi::overlay::Cidr; + +/// An exhaustive VpnService configuration, derived from local core policy. +#[derive(Clone, Default, Debug, PartialEq, Eq)] +pub struct VpnPlan { + /// One address in each active, non-overlapping network. + pub addresses: Vec, + /// Payload MTU for every attached network. + pub mtu: u32, + /// Capture IPv4 traffic outside the mesh. + pub full_tunnel: bool, + /// Preferred IPv4 source for the default route. + pub exit: Option, + /// Capture the limited broadcast when requested by the core. + pub broadcast: bool, +} + +impl VpnPlan { + /// Device-local DNS endpoint. Never take an address from a joined mesh. + pub fn dns_address(&self) -> Option { + if self.addresses.is_empty() { + return None; + } + [ + Ipv4Addr::new(192, 0, 2, 53), + Ipv4Addr::new(198, 51, 100, 53), + Ipv4Addr::new(203, 0, 113, 53), + ] + .into_iter() + .find(|candidate| { + !self.addresses.iter().any(|cidr| { + let IpAddr::V4(base) = cidr.addr else { + return false; + }; + tsunagi::state::Ipv4Range { + base, + prefix_len: cidr.prefix_len, + } + .contains(*candidate) + }) + }) + } + + /// Android uses the first address as primary for unscoped IPv4 traffic. + pub fn addresses_in_order(&self) -> Vec { + let mut ordered = self.addresses.clone(); + ordered.sort_by_key(|cidr| (Some(cidr.addr) != self.exit, *cidr)); + ordered + } + + /// Explicitly route the entire agreed subnet, including its virtual services. + pub fn routes(&self) -> Vec { + let mut routes: Vec<_> = self + .addresses + .iter() + .map(|cidr| { + let p = cidr.prefix_len; + let base = match cidr.addr { + IpAddr::V4(a) => IpAddr::V4(Ipv4Addr::from( + u32::from(a) & u32::MAX.checked_shl(u32::from(32 - p)).unwrap_or(0), + )), + IpAddr::V6(a) => IpAddr::V6(Ipv6Addr::from( + u128::from(a) & u128::MAX.checked_shl(u32::from(128 - p)).unwrap_or(0), + )), + }; + format!("{base}/{p}") + }) + .collect(); + if let Some(dns) = self.dns_address() { + routes.push(format!("{dns}/32")); + } + if self.full_tunnel { + routes.push("0.0.0.0/0".into()); + } + if self.broadcast { + routes.push("255.255.255.255/32".into()); + } + routes.sort(); + routes.dedup(); + routes + } +} diff --git a/crates/tsunagi-android/src/service.rs b/crates/tsunagi-android/src/service.rs new file mode 100644 index 0000000..371e7de --- /dev/null +++ b/crates/tsunagi-android/src/service.rs @@ -0,0 +1,263 @@ +//! Actions and status for the service-owned Rust agent. +use std::{sync::Arc, time::Instant}; +use tokio::sync::{mpsc, watch}; +use tsunagi::{ + Agent, NetworkName, NetworkSecret, + ipc::{PrivilegeReport, ProtocolReport, StatusReport}, + vip::VipStatus, +}; +use tsunagi_ui::client::Command; +use tsunagi_wg_quic::WireguardPlugin; +use zeroize::Zeroizing; + +/// A platform notification or user gesture. +pub enum Request { + /// A command from the same form used by the tray. + Action(Command), + /// The physical network changed. + NetworkChanged, + /// Disable only the exit identified by the notification the user tapped. + DisconnectExit { + /// Network id captured in the immutable action. + network: String, + /// Endpoint id captured at the same time. + peer: String, + }, +} + +/// A configured default route stays visible if its remote peer goes offline. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExitNotice { + /// Active network identity for the notification action. + pub network: String, + /// Selected remote device identity. + pub peer: String, + /// Human-readable mesh name. + pub network_name: String, + /// Same name shown in the exit chooser. + pub name: String, + /// Whether the peer still offers its exit. + pub online: bool, +} + +/// Only an active network with a selected remote exit needs an ongoing notice. +pub fn exit_notice(report: &StatusReport) -> Option { + report.networks.iter().filter(|n| n.active).find_map(|n| { + let peer = n.exit.via.as_ref()?; + Some(ExitNotice { + network: n.network_id.clone(), + peer: peer.clone(), + network_name: n.name.clone(), + name: tsunagi_ui::devices::name_of(n, peer), + online: n.exit.via_online, + }) + }) +} + +/// Actions are serialized in the service command loop. An old PendingIntent cannot +/// clear a replacement exit selected in this or another network. +pub async fn disconnect_exit( + agent: &Agent, + network: &str, + peer: &str, +) -> Result<(), Box> { + let network = network.parse()?; + let peer = peer.parse()?; + if agent.is_active(network).await && agent.network_status(network).await?.exit_via == Some(peer) + { + agent.set_exit_via(network, None).await?; + } + Ok(()) +} + +/// Private reply delivered only to the UI that requested the action. +pub enum Outcome { + /// The agent has applied the action. + Applied, + /// Revisions returned by a successful signed write. + Saved(Vec), + /// A user-requested, single-use clipboard export. + Clipboard(Zeroizing), +} + +/// Delivery channel for a request. +pub type Reply = tokio::sync::oneshot::Sender>; +/// Pending acknowledgement of a UI action. +pub type Response = tokio::sync::oneshot::Receiver>; + +/// Execute exactly the selection and revision supplied by the form. +pub async fn apply( + command: Command, + agent: &Agent, +) -> Result> { + match command { + Command::Join { name, secret } => { + agent + .join_network(&NetworkName::new(name)?, &NetworkSecret::decode(&secret)?) + .await?; + } + Command::SetActive { network_id, active } => { + let id = network_id.parse()?; + if active { + agent.switch_network(id).await?; + } else { + agent.pause_network(id).await?; + } + } + Command::Leave { network_id } => { + agent.leave_network(network_id.parse()?).await?; + } + Command::SetBroadcast { + network_id, + enabled, + } => agent.set_broadcast(network_id.parse()?, enabled).await?, + Command::SetProtocols { + network_id, + protocols, + } => agent.set_protocols(network_id.parse()?, protocols).await?, + Command::SetHostname(hostname) => { + agent.set_hostname(&hostname).await?; + } + Command::ForgetNode { + network_id, + peer, + expected_version, + } => { + agent + .forget_node(network_id.parse()?, peer.parse()?, expected_version) + .await?; + } + Command::SetExitNode { network_id, peer } => { + agent + .set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?) + .await? + } + Command::SetExitOffer { .. } => { + return Err("This phone can only use a remote exit node.".into()); + } + Command::SaveVip { + network_id, + config, + expected, + delete, + .. + } => { + return Ok(Outcome::Saved( + agent + .save_vip(network_id.parse()?, config, expected, delete) + .await?, + )); + } + Command::CopySecret { network_id } => { + return Ok(Outcome::Clipboard( + agent.network_secret(network_id.parse()?).await?.encode(), + )); + } + } + Ok(Outcome::Applied) +} + +/// State visible to an activity which may be recreated while the service runs. +#[derive(Clone, Default)] +pub enum State { + /// The user can start the VPN. + #[default] + Off, + /// Opening the endpoint or waiting for connectivity. + Starting, + /// The last complete snapshot and its monotonic observation time. + Ready(Arc, Instant), + /// Actionable startup or status error. + Error(String), +} + +/// Build the same network and counter reports used by the desktop client. +pub async fn report( + agent: &Agent, + wg: Option<&WireguardPlugin>, + dns: &crate::dns::Resolver, +) -> tsunagi::Result { + let status = agent.status().await?; + Ok(StatusReport { + networks: tsunagi_runtime::report::networks(&status, agent.overlay().as_ref(), wg), + dns: Some(dns.refresh(&status.networks)), + endpoint_id: status.endpoint_id.to_string(), + hostname: status.hostname, + bound_sockets: status + .bound_sockets + .iter() + .map(ToString::to_string) + .collect(), + cache_healthy: status.cache_healthy, + available_protocols: tsunagi_runtime::PROTOCOLS + .iter() + .map(|spec| ProtocolReport { + name: spec.name.into(), + summary: spec.summary.into(), + }) + .collect(), + protocols: tsunagi_runtime::PROTOCOLS + .iter() + .map(|spec| format!("{} v{}", spec.name, spec.version)) + .collect(), + privilege: PrivilegeReport::Available, + version: env!("CARGO_PKG_VERSION").into(), + ..Default::default() + }) +} + +/// Drive the agent until Android stops this service instance. +pub async fn serve( + agent: Agent, + wg: Arc, + dns: crate::dns::Resolver, + mut commands: mpsc::Receiver<(Request, Reply)>, + state: &watch::Sender, + mut stop: watch::Receiver, + mut publish_exit: impl FnMut(Option<&ExitNotice>), +) { + let mut poll = tokio::time::interval(std::time::Duration::from_secs(2)); + poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut published_exit = None; + loop { + let reply = tokio::select! { + biased; + _ = stop.wait_for(|stopped| *stopped) => break, + command = commands.recv() => { + let Some((request, reply)) = command else { break }; + let result = match request { + Request::Action(cmd) => { + if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) { + dns.replace(None); + } + apply(cmd, &agent).await.map_err(|e| e.to_string()) + } + Request::NetworkChanged => { + agent.endpoint().network_change().await; + agent.recheck().await; + Ok(Outcome::Applied) + } + Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await + .map(|()| Outcome::Applied).map_err(|e| e.to_string()), + }; + Some((reply, result)) + } + _ = poll.tick() => None, + }; + state.send_replace(match report(&agent, Some(&wg), &dns).await { + Ok(report) => { + let notice = exit_notice(&report); + if published_exit.as_ref() != Some(¬ice) { + publish_exit(notice.as_ref()); + published_exit = Some(notice); + } + State::Ready(Arc::new(report), Instant::now()) + } + Err(error) => State::Error(error.to_string()), + }); + if let Some((reply, outcome)) = reply { + let _ = reply.send(outcome); + } + } + agent.shutdown().await; +} diff --git a/crates/tsunagi-android/src/tests.rs b/crates/tsunagi-android/src/tests.rs new file mode 100644 index 0000000..46e4855 --- /dev/null +++ b/crates/tsunagi-android/src/tests.rs @@ -0,0 +1,651 @@ +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use super::plan::VpnPlan; +use std::net::{IpAddr, Ipv4Addr}; +use tsunagi::overlay::Cidr; + +fn addr(octet: u8) -> Cidr { + Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap() +} + +#[tokio::test] +async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() { + use crate::service::{disconnect_exit, exit_notice, report}; + use tsunagi::{ + discovery::SharedMemoryDiscovery, + testing::{TestAgent, network, wait_until}, + }; + let discovery = SharedMemoryDiscovery::new(); + let phone = TestAgent::spawn(&discovery).await.unwrap(); + let rules = std::sync::Arc::new(tsunagi::overlay::MockHostRules::new()); + let tuns = tsunagi::overlay::MemoryTunFactory::new().with_host_rules(rules); + let exit = TestAgent::spawn_with( + |cfg| cfg.with_interface(std::sync::Arc::new(tuns), "gateway", 1280), + &discovery, + ) + .await + .unwrap(); + let (name, secret) = network("travel"); + let id = phone.agent.join_network(&name, &secret).await.unwrap(); + exit.agent.set_hostname("gateway").await.unwrap(); + exit.agent.join_network(&name, &secret).await.unwrap(); + exit.agent.set_exit_offer(id, true).await.unwrap(); + let peer = exit.agent.endpoint_id(); + wait_until("authenticated exit offer", || async { + phone + .agent + .network_status(id) + .await + .ok()? + .peers + .iter() + .any(|p| p.endpoint_id == peer && p.exit_node) + .then_some(()) + }) + .await; + let dns = crate::dns::Resolver::new(|_| None); + assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none()); + phone.agent.set_exit_via(id, Some(peer)).await.unwrap(); + let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap(); + assert_eq!(notice.name, "gateway"); + assert_eq!(notice.network_name, "travel"); + assert!(notice.online); + disconnect_exit( + &phone.agent, + &id.to_string(), + &phone.agent.endpoint_id().to_string(), + ) + .await + .unwrap(); + assert_eq!( + phone.agent.network_status(id).await.unwrap().exit_via, + Some(peer) + ); + exit.stop().await; + wait_until( + "offline exit remains selected in the notification", + || async { + let report = report(&phone.agent, None, &dns).await.ok()?; + exit_notice(&report).filter(|n| !n.online) + }, + ) + .await; + disconnect_exit(&phone.agent, ¬ice.network, ¬ice.peer) + .await + .unwrap(); + assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none()); + assert!(phone.agent.is_active(id).await); + phone.stop().await; +} + +#[tokio::test] +async fn vpn_dns_answers_hosts_and_vips_in_each_zone_and_only_forwards_external_names() { + use crate::dns::Resolver; + use simple_dns::{CLASS, Name, Packet, PacketFlag, Question, RCODE, TYPE, rdata::RData}; + use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }; + use tsunagi::dns::{Zone, ZoneName, Zones}; + + fn query(name: &str, kind: TYPE) -> Vec { + let mut packet = Packet::new_query(119); + packet.set_flags(PacketFlag::RECURSION_DESIRED); + packet.questions.push(Question::new( + Name::new(name).unwrap(), + kind.into(), + CLASS::IN.into(), + false, + )); + packet.build_bytes_vec().unwrap() + } + let calls = Arc::new(AtomicUsize::new(0)); + let forwarded = calls.clone(); + let resolver = Resolver::new(move |wire| { + forwarded.fetch_add(1, Ordering::Relaxed); + let query = Packet::parse(wire).unwrap(); + let mut answer = Packet::new_reply(999); + answer.questions = query.questions; + answer.build_bytes_vec().ok() + }); + let private = query("k8s.tsng", TYPE::A); + let answer = resolver.answer(&private).await.unwrap(); + assert_eq!( + Packet::parse(&answer).unwrap().rcode(), + RCODE::ServerFailure + ); + let lab = |name, members| Zone::new(ZoneName::new(name).unwrap(), members); + resolver.replace(Some(Zones::new([ + lab( + "tsng", + vec![ + ("ai".into(), [10, 1, 1, 100].into()), + ("k8s".into(), [10, 1, 1, 106].into()), + ], + ), + lab("lab", vec![("ai".into(), [10, 2, 1, 100].into())]), + ]))); + for (name, ip) in [ + ("AI.TSNG", [10, 1, 1, 100]), + ("k8s.tsng", [10, 1, 1, 106]), + ("ai.lab", [10, 2, 1, 100]), + ] { + let reply = resolver.answer(&query(name, TYPE::A)).await.unwrap(); + let packet = Packet::parse(&reply).unwrap(); + assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER)); + assert!( + matches!(&packet.answers[0].rdata, RData::A(a) if Ipv4Addr::from(a.address) == Ipv4Addr::from(ip)) + ); + } + for (name, kind, code) in [ + ("missing.tsng", TYPE::A, RCODE::NameError), + ("k8s.tsng", TYPE::AAAA, RCODE::NoError), + ] { + let reply = resolver.answer(&query(name, kind)).await.unwrap(); + let packet = Packet::parse(&reply).unwrap(); + assert_eq!(packet.rcode(), code); + assert!(packet.answers.is_empty()); + assert!(packet.has_flags(PacketFlag::AUTHORITATIVE_ANSWER)); + } + assert!(resolver.answer(b"invalid").await.is_none()); + assert_eq!(calls.load(Ordering::Relaxed), 0); + let reply = resolver + .answer(&query("example.org", TYPE::HTTPS)) + .await + .unwrap(); + let packet = Packet::parse(&reply).unwrap(); + assert_eq!(packet.id(), 119); + assert_eq!(packet.questions[0].qtype, TYPE::HTTPS.into()); + assert_eq!(calls.load(Ordering::Relaxed), 1); +} + +#[test] +fn local_dns_address_is_routed_and_cannot_claim_an_overlay_ip() { + let mut plan = VpnPlan { + addresses: vec![addr(1)], + ..Default::default() + }; + let dns = plan.dns_address().unwrap(); + assert!(plan.routes().contains(&format!("{dns}/32"))); + plan.addresses.push(Cidr::new(dns.into(), 24).unwrap()); + let other = plan.dns_address().unwrap(); + assert_ne!(other, dns); + assert!(plan.routes().contains(&format!("{other}/32"))); + plan.addresses.clear(); + assert!(plan.dns_address().is_none()); +} + +#[tokio::test] +async fn service_dns_tracks_signed_hostnames_vip_deletion_and_reverse_ranges() { + use tsunagi::{ + Agent, + dns::{Answer, Query, RosterZones}, + testing, + vip::VipConfig, + }; + let dir = tempfile::tempdir().unwrap(); + let agent = Agent::spawn(testing::local_config(dir.path())) + .await + .unwrap(); + let (network, secret) = testing::network("tsng"); + let id = agent.join_network(&network, &secret).await.unwrap(); + agent.set_hostname("worker").await.unwrap(); + let vip = agent + .save_vip(id, VipConfig::new("k8s"), None, false) + .await + .unwrap() + .remove(0); + let status = agent.status().await.unwrap(); + let roster = RosterZones::from_networks(&status.networks); + let worker = status.networks[0] + .members + .iter() + .find(|m| m.hostname.as_deref() == Some("worker")) + .unwrap() + .overlay_address_v4 + .unwrap(); + for (name, ip) in [("worker.tsng", worker), ("k8s.tsng", vip.address.unwrap())] { + assert_eq!( + roster.zones.lookup(name, Query::A).unwrap().1, + Answer::Addresses(vec![ip]) + ); + let [a, b, c, d] = ip.octets(); + assert_eq!( + roster + .zones + .lookup(&format!("{d}.{c}.{b}.{a}.in-addr.arpa"), Query::Ptr) + .unwrap() + .1, + Answer::Name(name.into()) + ); + } + assert!( + roster + .zones + .lookup("8.8.8.8.in-addr.arpa", Query::Ptr) + .is_none() + ); + agent + .save_vip(id, vip.config, Some(vip.revision), true) + .await + .unwrap(); + let zones = RosterZones::from_networks(&agent.status().await.unwrap().networks).zones; + assert_eq!( + zones.lookup("k8s.tsng", Query::A).unwrap().1, + Answer::NoSuchName + ); + agent.shutdown().await; +} + +#[test] +fn changing_the_exit_keeps_every_mesh_route_and_prefers_the_selected_source() { + let first = addr(2); + let second = addr(5); + let mut plan = VpnPlan { + addresses: vec![first, second], + mtu: 1280, + ..Default::default() + }; + assert_eq!( + plan.routes(), + ["10.2.42.0/24", "10.5.42.0/24", "192.0.2.53/32"] + ); + assert_eq!(plan.addresses_in_order(), [first, second]); + plan.full_tunnel = true; + plan.exit = Some(second.addr); + assert_eq!(plan.addresses_in_order(), [second, first]); + assert!(plan.routes().contains(&"0.0.0.0/0".into())); + assert!(plan.routes().contains(&"10.2.42.0/24".into())); + plan.full_tunnel = false; + plan.exit = None; + plan.addresses.remove(0); + assert_eq!(plan.routes(), ["10.5.42.0/24", "192.0.2.53/32"]); +} + +#[test] +fn broadcast_route_is_only_present_when_requested() { + let mut plan = VpnPlan { + addresses: vec![addr(1)], + mtu: 1280, + ..Default::default() + }; + plan.broadcast = true; + assert!(plan.routes().contains(&"255.255.255.255/32".into())); + plan.broadcast = false; + assert_eq!(plan.routes(), ["10.1.42.0/24", "192.0.2.53/32"]); +} + +#[tokio::test] +async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() { + use tsunagi::{Agent, testing}; + use tsunagi_runtime::{Carriers, PROTOCOLS}; + let dir = tempfile::tempdir().unwrap(); + let names = ["wg", "awg", "wg-quic", "tcp-tls"]; + let (network, secret) = testing::network("carriers"); + for restart in [false, true] { + let config = testing::local_config(dir.path()); + let (config, carriers) = Carriers::configure(config, &[], None, |spec| { + if spec.name == "tcp-tls" { + vec![("port".into(), "0".into())] + } else { + Vec::new() + } + }) + .await + .unwrap(); + assert_eq!( + config + .carriers + .iter() + .map(|c| c.protocol_id()) + .collect::>(), + names + ); + assert!( + config + .carriers + .iter() + .zip(PROTOCOLS) + .all(|(c, spec)| c.protocol_version() == spec.version) + ); + let agent = Agent::spawn(config).await.unwrap(); + let _listeners = carriers.listen(&agent); + let id = agent.join_network(&network, &secret).await.unwrap(); + let saved = agent.network_status(id).await.unwrap().protocols; + if restart { + assert_eq!(saved, ["tcp-tls", "wg"]); + } else { + assert_eq!(saved, names); + agent + .set_protocols(id, vec!["tcp-tls".into(), "wg".into()]) + .await + .unwrap(); + let (other, secret) = testing::network("other"); + let second = agent.join_network(&other, &secret).await.unwrap(); + assert_eq!(agent.network_status(second).await.unwrap().protocols, names); + } + agent.shutdown().await; + } +} + +#[tokio::test] +async fn commands_scope_vip_edits_and_leaving_to_the_selected_network() { + use crate::service::apply; + use tsunagi::vip::VipConfig; + use tsunagi::{Agent, NetworkName, NetworkSecret, testing}; + use tsunagi_ui::client::Command; + let dir = tempfile::tempdir().unwrap(); + let agent = Agent::spawn(testing::local_config(dir.path())) + .await + .unwrap(); + let name = NetworkName::new("shared-name").unwrap(); + let one = NetworkSecret::generate(); + let two = NetworkSecret::generate(); + for secret in [&one, &two] { + apply( + Command::Join { + name: name.to_string(), + secret: secret.encode(), + }, + &agent, + ) + .await + .unwrap(); + } + let first = tsunagi::identity::NetworkKeys::derive(&name, &one) + .network_id() + .to_string(); + let second = tsunagi::identity::NetworkKeys::derive(&name, &two).network_id(); + let config = VipConfig::new("web"); + let save = |expected, delete| Command::SaveVip { + token: "draft".into(), + network_id: first.clone(), + config: config.clone(), + expected, + delete, + }; + apply(save(None, false), &agent).await.unwrap(); + assert!( + apply(save(Some("stale".into()), true), &agent) + .await + .is_err() + ); + assert_eq!( + agent + .network_status(first.parse().unwrap()) + .await + .unwrap() + .vips + .len(), + 1 + ); + assert!(agent.network_status(second).await.unwrap().vips.is_empty()); + assert!( + apply( + Command::SetExitNode { + network_id: second.to_string(), + peer: Some(agent.endpoint_id().to_string()) + }, + &agent + ) + .await + .is_err() + ); + assert!( + apply( + Command::SetExitOffer { + network_id: second.to_string(), + enabled: true + }, + &agent + ) + .await + .is_err() + ); + apply(Command::Leave { network_id: first }, &agent) + .await + .unwrap(); + let saved = agent.list_networks().await.unwrap(); + assert_eq!(saved.len(), 1); + assert_eq!(saved[0].network_id, second); + agent.shutdown().await; +} + +#[cfg(unix)] +#[tokio::test] +async fn tun_reader_survives_address_changes_failed_establish_and_last_network_leaving() { + use std::io; + use std::os::{fd::OwnedFd, unix::net::UnixDatagram}; + use std::sync::{Arc, Mutex}; + use tsunagi::overlay::{TunFactory, TunRequest}; + let sockets = Arc::new(Mutex::new(Vec::new())); + let peers = sockets.clone(); + let factory = crate::tun::AndroidTun::new( + crate::dns::Resolver::new(|_| None), + move |plan| { + if plan.addresses.contains(&addr(9)) { + return Err(io::Error::other("permission revoked")); + } + let (dev, os) = UnixDatagram::pair()?; + dev.set_nonblocking(true)?; + peers.lock().unwrap().push(os); + Ok(OwnedFd::from(dev).into()) + }, + |_, _| Ok(()), + ); + let mut req = TunRequest::bare("tsun0", 1280); + let dev = factory.create(req.clone()).await.unwrap(); + let reader = tokio::spawn({ + let dev = dev.clone(); + async move { dev.recv().await.unwrap() } + }); + req.addresses = vec![addr(2)]; + factory.reconfigure(req.clone()).await.unwrap(); + assert_eq!(factory.assigned_addresses(), [addr(2).addr]); + req.addresses.push(addr(9)); + assert!(factory.reconfigure(req.clone()).await.is_err()); + assert_eq!(factory.assigned_addresses(), [addr(2).addr]); + sockets + .lock() + .unwrap() + .last() + .unwrap() + .send(b"first") + .unwrap(); + assert_eq!( + &tokio::time::timeout(std::time::Duration::from_secs(2), reader) + .await + .unwrap() + .unwrap()[..], + b"first" + ); + req.addresses.clear(); + factory.reconfigure(req.clone()).await.unwrap(); + assert!( + dev.send(bytes::Bytes::from_static(b"offline")) + .await + .is_err() + ); + assert!(factory.assigned_addresses().is_empty()); + req.addresses = vec![addr(5)]; + factory.reconfigure(req).await.unwrap(); + sockets + .lock() + .unwrap() + .last() + .unwrap() + .send(b"second") + .unwrap(); + assert_eq!(&dev.recv().await.unwrap()[..], b"second"); +} + +#[tokio::test] +async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() { + use crate::{ + service::{State, report}, + view::{Phone, configure}, + }; + use egui::epaint::Shape; + use std::{sync::Arc, time::Instant}; + let dir = tempfile::tempdir().unwrap(); + let agent = tsunagi::Agent::spawn(tsunagi::testing::local_config(dir.path())) + .await + .unwrap(); + let (name, secret) = tsunagi::testing::network("layout"); + agent.join_network(&name, &secret).await.unwrap(); + let mut sample = report(&agent, None, &crate::dns::Resolver::new(|_| None)) + .await + .unwrap(); + sample.networks[0].overlay = Some(tsunagi::ipc::OverlayReport { + address: Some("10.1.2.3".into()), + ..Default::default() + }); + let state = State::Ready(Arc::new(sample), Instant::now()); + let ctx = egui::Context::default(); + configure(&ctx); + let mut phone = Phone::default(); + let frame = ctx.run( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(360., 720.), + )), + ..Default::default() + }, + |ctx| { + phone.draw(ctx, &state, |_| { + panic!("drawing the overview issued a command") + }); + }, + ); + let y = |label: &str| { + frame + .shapes + .iter() + .find_map(|shape| match &shape.shape { + Shape::Text(text) if text.galley.text() == label => Some(text.pos.y), + _ => None, + }) + .unwrap_or_else(|| panic!("missing label {label}")) + }; + assert!((0.0..=26.0).contains(&(y("host") - y("device")))); + assert!((0.0..=26.0).contains(&(y("range") - y("id")))); + assert!((0.0..=26.0).contains(&(y("peers") - y("addr")))); + agent.shutdown().await; +} + +#[test] +fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() { + use crate::service::State; + use crate::view::{Phone, configure}; + use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape}; + use std::{sync::Arc, time::Instant}; + use tsunagi::{ + ipc::{NetworkReport, StatusReport}, + vip::{ + Backend, BackendStatus, Counters, Listener, ListenerStatus, Protocol, VipConfig, + VipStatus, + }, + }; + let backend = Backend { + peer: "node".into(), + port: 8080, + }; + let mut config = VipConfig::new("web"); + let mut listener = Listener::new(Protocol::Tcp, 80); + listener.backends.push(backend.clone()); + config.listeners.push(listener); + let network = NetworkReport { + active: true, + name: "lab".into(), + network_id: "network".into(), + vips: vec![VipStatus { + config, + address: None, + revision: "r1".into(), + error: None, + listeners: vec![ListenerStatus { + protocol: Protocol::Tcp, + port: 80, + selected: Some(backend.clone()), + counters: Counters::default(), + backends: vec![BackendStatus { + backend, + state: "ready".into(), + rtt_us: Some(1000), + measurement_age_ms: Some(1), + active_flows: 1, + counters: Counters::default(), + }], + }], + }], + ..Default::default() + }; + let state = State::Ready( + Arc::new(StatusReport { + networks: vec![network], + ..Default::default() + }), + Instant::now(), + ); + let ctx = egui::Context::default(); + configure(&ctx); + let mut phone = Phone::default(); + let mut frame = |events| { + ctx.run( + RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))), + events, + ..Default::default() + }, + |ctx| { + phone.draw(ctx, &state, |_| panic!("navigation wrote to the network")); + }, + ) + }; + let position = |output: &egui::FullOutput, label: &str| { + output + .shapes + .iter() + .find_map(|s| match &s.shape { + Shape::Text(t) if t.galley.text() == label => { + Some(t.pos + t.galley.rect.center().to_vec2()) + } + _ => None, + }) + .unwrap_or_else(|| panic!("missing {label}")) + }; + let mut click = |label: &str| { + frame(vec![]); + let p = position(&frame(vec![]), label); + for pressed in [true, false] { + frame(vec![ + Event::PointerMoved(p), + Event::PointerButton { + pos: p, + button: PointerButton::Primary, + pressed, + modifiers: Default::default(), + }, + ]); + } + frame(vec![]) + }; + let live = click("VIP"); + for label in ["Overview", "Configuration", "Next new flow", "node:8080"] { + let p = position(&live, label); + assert!( + (0.0..360.0).contains(&p.x), + "{label} is outside the portrait view" + ); + } + let editor = click("Configuration"); + for label in [ + "Active TCP port checks", + "Checks and flow expiry", + "+ Backend", + "+ Listener", + ] { + position(&editor, label); + } +} diff --git a/crates/tsunagi-android/src/tun.rs b/crates/tsunagi-android/src/tun.rs new file mode 100644 index 0000000..120bfce --- /dev/null +++ b/crates/tsunagi-android/src/tun.rs @@ -0,0 +1,287 @@ +//! A stable packet device over the file descriptors replaced by VpnService. +use crate::dns::{Resolver, stack::DnsPort}; +use crate::plan::VpnPlan; +use bytes::Bytes; +use std::{ + fmt, + fs::File, + io::{self, Read, Write}, + sync::Arc, +}; +use tokio::{ + io::unix::AsyncFd, + sync::{Mutex, watch}, +}; +use tsunagi::{ + BoxFuture, + overlay::{ + OverlayError, TunDevice, TunFactory, TunRequest, + hostrules::{ + BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan, + ExitHostReport, ExitHostRules, RuleOutcome, + }, + }, +}; + +type Establish = dyn Fn(&VpnPlan) -> io::Result + Send + Sync; +type BindSocket = + dyn Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()> + Send + Sync; +struct Attachment { + device: Arc>, + addresses: Vec, + dns: DnsPort, +} +type Descriptor = Option>; + +/// The only OS call is supplied by the Android service. Tokio owns the detached fd. +#[derive(Clone)] +pub struct AndroidTun(Arc); +struct Inner { + establish: Box, + bind: Box, + resolver: Resolver, + plan: Mutex, + current: watch::Sender, +} + +impl fmt::Debug for AndroidTun { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AndroidTun") + } +} +impl AndroidTun { + /// Attach a nonblocking device returned by Builder.establish(). + pub fn new( + resolver: Resolver, + establish: impl Fn(&VpnPlan) -> io::Result + Send + Sync + 'static, + bind: impl Fn(&tokio::net::TcpSocket, std::net::Ipv4Addr) -> io::Result<()> + + Send + + Sync + + 'static, + ) -> Self { + Self(Arc::new(Inner { + establish: Box::new(establish), + bind: Box::new(bind), + resolver, + plan: Mutex::default(), + current: watch::channel(None).0, + })) + } + + async fn update(&self, edit: impl FnOnce(&mut VpnPlan)) -> Result<(), OverlayError> { + let mut applied = self.0.plan.lock().await; + let mut next = applied.clone(); + edit(&mut next); + if *applied == next { + return Ok(()); + } + let dns_address = next.dns_address(); + let fd = if next.addresses.is_empty() { + None + } else { + let address = dns_address.ok_or_else(|| OverlayError::Unavailable( + "Mesh ranges overlap every device-local DNS address. Choose a narrower mesh range.".into() + ))?; + let file = (self.0.establish)(&next) + .and_then(AsyncFd::new) + .map(Arc::new) + .map_err(|err| OverlayError::Unavailable(err.to_string()))?; + let dns = DnsPort::start( + address, + next.mtu as usize, + self.0.resolver.clone(), + file.clone(), + ); + Some(Arc::new(Attachment { + device: file, + addresses: next.addresses.iter().map(|a| a.addr).collect(), + dns, + })) + }; + self.0.current.send_replace(fd); + self.0.resolver.publish(dns_address); + *applied = next; + Ok(()) + } +} + +#[derive(Debug)] +struct Device { + name: String, + mtu: u32, + tun: AndroidTun, +} + +impl TunDevice for Device { + fn name(&self) -> &str { + &self.name + } + fn mtu(&self) -> u32 { + self.mtu + } + fn recv(&self) -> BoxFuture<'_, Option> { + Box::pin(async move { + let mut rx = self.tun.0.current.subscribe(); + let mut buffer = vec![0; self.mtu as usize + 1]; + loop { + let fd = rx.borrow_and_update().clone(); + if let Some(fd) = fd { + let result = tokio::select! { + biased; + _ = rx.changed() => continue, + read = fd.device.async_io(tokio::io::Interest::READABLE, |mut file| file.read(&mut buffer)) => read, + }; + if let Ok(len @ 1..) = result { + if fd.dns.intercept(&buffer[..len], &fd.addresses) { + continue; + } + buffer.truncate(len); + return Some(buffer.into()); + } + } + // No networks yet, last one left, or Android revoked this fd. + // A later establish wakes the same reader on the new device. + rx.changed().await.ok()?; + } + }) + } + fn send<'a>(&'a self, packet: Bytes) -> BoxFuture<'a, Result<(), OverlayError>> { + Box::pin(async move { + let mut rx = self.tun.0.current.subscribe(); + let fd = rx + .borrow_and_update() + .clone() + .ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".into()))?; + let len = tokio::select! { + biased; + _ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())), + write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) => + write.map_err(|e| OverlayError::Other(e.to_string()))?, + }; + if len != packet.len() { + return Err(OverlayError::Other("short VPN datagram write".into())); + } + Ok(()) + }) + } +} + +impl TunFactory for AndroidTun { + fn name(&self) -> &str { + "Android VpnService" + } + fn bind_overlay_socket( + &self, + socket: &tokio::net::TcpSocket, + source: std::net::Ipv4Addr, + ) -> io::Result<()> { + (self.0.bind)(socket, source)?; + socket.bind((source, 0).into()) + } + fn assigned_addresses(&self) -> Vec { + self.0 + .current + .borrow() + .as_ref() + .map(|fd| fd.addresses.clone()) + .unwrap_or_default() + } + fn on_host(&self) -> bool { + true + } + fn create<'a>( + &'a self, + req: TunRequest, + ) -> BoxFuture<'a, Result, OverlayError>> { + Box::pin(async move { + let dev = Device { + name: req.name.clone(), + mtu: req.mtu, + tun: self.clone(), + }; + self.reconfigure(req).await?; + Ok(Arc::new(dev) as Arc) + }) + } + fn reconfigure<'a>(&'a self, req: TunRequest) -> BoxFuture<'a, Result<(), OverlayError>> { + Box::pin(self.update(move |plan| { + plan.addresses = req.addresses; + plan.mtu = req.mtu; + })) + } + fn host_rules(&self) -> Option> { + Some(Arc::new(self.clone())) + } + fn destroy<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> { + Box::pin(async { + let _ = self.update(|plan| *plan = VpnPlan::default()).await; + }) + } +} + +fn outcome(result: Result<(), OverlayError>) -> RuleOutcome { + match result { + Ok(()) => RuleOutcome::Applied, + Err(error) => RuleOutcome::Failed(error.to_string()), + } +} +impl BroadcastHostRules for AndroidTun { + fn name(&self) -> &str { + "Android VpnService" + } + fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> { + Box::pin(async move { + let route = outcome(self.update(|p| p.broadcast = true).await); + BroadcastRulesReport { + plan: plan.clone(), + route, + // Android delivers accepted traffic directly through the VPN fd. + firewall: RuleOutcome::Applied, + } + }) + } + fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> { + Box::pin(async { + let _ = self.update(|p| p.broadcast = false).await; + }) + } + fn exit_rules(&self) -> Option<&dyn ExitHostRules> { + Some(self) + } +} +impl ExitHostRules for AndroidTun { + fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> { + Box::pin(async move { + let result = self + .update(|p| { + p.full_tunnel = plan.client; + p.exit = plan.client_source.map(Into::into); + }) + .await; + ExitHostReport { + offer: plan + .offer + .iter() + .map(|range| { + ( + *range, + RuleOutcome::Failed("Android supports exit clients only".into()), + ) + }) + .collect(), + forwarding: None, + client: plan.client.then(|| outcome(result)), + } + }) + } + fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> { + Box::pin(async { + let _ = self + .update(|p| { + p.full_tunnel = false; + p.exit = None; + }) + .await; + }) + } +} diff --git a/crates/tsunagi-android/src/view.rs b/crates/tsunagi-android/src/view.rs new file mode 100644 index 0000000..5e229a4 --- /dev/null +++ b/crates/tsunagi-android/src/view.rs @@ -0,0 +1,361 @@ +//! Android supplies navigation and the VPN lifecycle to the shared egui forms. +use crate::service::{Outcome, Response, State}; +use egui::{Color32, Context}; +use egui_phosphor::regular as icon; +use std::cell::RefCell; +use tsunagi_ui::{ + about, + client::{Client, Command, Snapshot, VipSaveResult}, + devices, + home::{self, UiState}, + stats::{Traffic, Unit}, + vip, +}; +use zeroize::{Zeroize, Zeroizing}; + +const BAD: Color32 = Color32::from_rgb(0xd0, 0x4a, 0x3c); + +#[derive(Default, PartialEq, Eq)] +enum Page { + #[default] + Home, + About, + Join, + Devices(String), + Vips(String), + Exit(String), + Leave(String), +} +impl Page { + fn network(&self) -> Option<&str> { + match self { + Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id), + _ => None, + } + } + fn title(&self) -> &'static str { + match self { + Self::Home => "tsunagi", + Self::About => "About", + Self::Join => "Join a network", + Self::Devices(_) => "Devices", + Self::Vips(_) => "VIP", + Self::Exit(_) => "Exit node", + Self::Leave(_) => "Leave network", + } + } +} + +/// Operations that require the Android activity. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum SystemAction { + /// Request VPN consent and start the foreground service. + Start, + /// Stop the service while preserving this identity and its networks. + Stop, + /// Read the clipboard after a user gesture. + PasteSecret, + /// Return to the previous Android activity. + Finish, +} + +struct Actions { + command: RefCell>, + busy: bool, +} +impl Client for Actions { + fn send(&self, cmd: Command) { + if !self.busy() { + self.command.replace(Some(cmd)); + } + } + fn busy(&self) -> bool { + self.busy || self.command.borrow().is_some() + } +} + +struct Pending { + result: Response, + vip: Option, + go_home: bool, +} + +/// Presentation state of the single Android viewport. +#[derive(Default)] +pub struct Phone { + page: Page, + forms: UiState, + traffic: Traffic, + snapshot: Snapshot, + pending: Option, + error: Option, + clipboard: Option>, +} + +/// Keep reads at tray density. Extra hit area is reserved for the navigation bar. +pub fn configure(ctx: &Context) { + ctx.set_fonts(tsunagi_ui::app_fonts()); + ctx.style_mut(|style| { + style.spacing.interact_size.y = 19.0; + style.spacing.button_padding = egui::vec2(6.0, 3.0); + style.spacing.item_spacing = egui::vec2(6.0, 3.0); + }); +} + +impl Phone { + fn home(&mut self) { + if let Page::Vips(id) = &self.page { + self.forms.vip_windows.remove(id); + } + self.forms.join.name.clear(); + self.forms.join.secret.zeroize(); + self.forms.exit_confirm = None; + self.forms.forget_confirm = None; + self.page = Page::Home; + } + + /// System Back and toolbar Back use the same draft and confirmation state. + pub fn back(&mut self) -> Option { + if self.pending.is_some() { + return None; + } + if self.forms.exit_confirm.take().is_some() || self.forms.forget_confirm.take().is_some() { + return None; + } + if let Page::Vips(id) = &self.page + && let Some(editor) = self.forms.vip_windows.get_mut(id) + && editor.dirty() + { + editor.request_close(); + } else if self.page == Page::Home { + return Some(SystemAction::Finish); + } else { + self.home(); + } + None + } + /// Accept a user-initiated paste into the join form. + pub fn paste_secret(&mut self, value: String) { + if self.page == Page::Join { + self.forms.join.secret.zeroize(); + self.forms.join.secret = Zeroizing::new(value); + } + } + /// Request password input with IME suggestions disabled. + pub fn secret_focused(&self, ctx: &Context) -> bool { + ctx.memory(|m| m.has_focus("join-secret".into())) + } + /// Present an error from an Android operation. + pub fn error(&mut self, message: String) { + self.error = Some(message); + } + + /// Take a secret once for the platform’s sensitive clipboard. + pub fn take_copied_secret(&mut self) -> Option> { + self.clipboard.take() + } + + fn acknowledge(&mut self) { + let Some(pending) = &mut self.pending else { + return; + }; + let outcome = match pending.result.try_recv() { + Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return, + Err(tokio::sync::oneshot::error::TryRecvError::Closed) => { + Err("VPN service stopped".to_owned()) + } + Ok(v) => v, + }; + if let Some(token) = pending.vip.take() { + let result = outcome.and_then(|r| match r { + Outcome::Saved(vips) => Ok(vips), + _ => Err("Missing VIP save acknowledgement".into()), + }); + self.snapshot.vip_result = Some(VipSaveResult { token, result }); + } else { + match outcome { + Ok(Outcome::Clipboard(text)) => self.clipboard = Some(text), + Ok(_) if pending.go_home => self.home(), + Ok(_) => {} + Err(e) => self.error = Some(e), + } + } + self.pending = None; + } + + /// Render a tray view in this viewport and send gestures to the service. + pub fn draw( + &mut self, + ctx: &Context, + state: &State, + mut submit: impl FnMut(Command) -> Result, + ) -> Option { + self.acknowledge(); + let report = if let State::Ready(report, at) = state { + if self.snapshot.at != Some(*at) { + self.snapshot.generation = self.snapshot.generation.wrapping_add(1); + self.snapshot.at = Some(*at); + self.snapshot.status = Some(Ok(report.clone())); + self.traffic.observe(report, *at); + } + if self + .page + .network() + .is_some_and(|id| !report.networks.iter().any(|n| n.network_id == id)) + { + self.home(); + } + Some(report) + } else { + if self.page.network().is_some() || self.page == Page::Join { + self.home(); + } + self.snapshot = Snapshot::default(); + self.traffic = Traffic::default(); + None + }; + let actions = Actions { + command: RefCell::default(), + busy: self.pending.is_some(), + }; + let mut system = None; + egui::TopBottomPanel::top("navigation").show(ctx, |ui| { + ui.horizontal(|ui| { + ui.spacing_mut().interact_size.y = 32.0; + if self.page != Page::Home && ui.button(icon::ARROW_LEFT).clicked() { + system = self.back(); + } + ui.heading(self.page.title()); + if self.page == Page::Home { + ui.weak(env!("CARGO_PKG_VERSION")); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(icon::INFO).clicked() { + self.page = Page::About; + } + if report.is_some() { + ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes"); + ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts"); + } + }); + } else if self.page == Page::About + && !matches!(state, State::Off) + && ui.button("Stop VPN").clicked() + { + system = Some(SystemAction::Stop); + } + }); + if let Some(error) = &self.error { + ui.colored_label(BAD, error); + } + }); + let selected = self + .page + .network() + .and_then(|id| report?.networks.iter().find(|n| n.network_id == id)); + match (&self.page, selected) { + (Page::About, _) => about::show(ctx, None, &self.snapshot), + (Page::Vips(id), Some(network)) => { + let editor = self.forms.vip_windows.entry(id.clone()).or_default(); + if vip::show(ctx, &actions, editor, network, &self.snapshot) { + self.home(); + } + } + (Page::Devices(_), Some(network)) => { + if let Some(report) = report { + devices::show( + ctx, + &actions, + &mut self.forms.unit, + (&mut self.forms.exit_confirm, &mut self.forms.forget_confirm), + network, + &report.endpoint_id, + &self.traffic, + ); + } + } + _ => { + egui::CentralPanel::default().show(ctx, |ui| { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let Some(report) = report else { + match state { + State::Starting => {ui.spinner(); ui.label("Starting VPN…");} + _ => { + if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("VPN is stopped");} + if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);} + } + } + return; + }; + match &self.page { + Page::Home => { + home::draw_header(ui, &actions, &mut self.forms, report); + ui.separator(); + if ui.button("Join or create a network").clicked() {self.page = Page::Join;} + for n in &report.networks { + if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());} + if self.forms.open_devices.remove(&n.network_id) {self.page = Page::Devices(n.network_id.clone());} + if self.forms.vip_windows.contains_key(&n.network_id) {self.page = Page::Vips(n.network_id.clone());} + } + } + Page::Join => { + home::draw_join(ui, &actions, &mut self.forms.join); + if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);} + } + Page::Exit(_) => { + if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) { + self.forms.exit_confirm = Some(choice); + } + } + Page::Leave(id) => { + if let Some(n) = selected { + ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name)); + if ui.button("Leave network").clicked() {actions.send(Command::Leave {network_id: id.clone()});} + if ui.button("Cancel").clicked() {self.home();} + } + } + _ => {} + } + }); + }); + devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None); + } + } + if let Some(command) = actions.command.into_inner() { + self.error = None; + if let Command::Leave { network_id } = &command + && !matches!(self.page, Page::Leave(_)) + { + self.page = Page::Leave(network_id.clone()); + } else { + let token = match &command { + Command::SaveVip { token, .. } => Some(token.clone()), + _ => None, + }; + let go_home = matches!( + command, + Command::Join { .. } | Command::Leave { .. } | Command::SetExitNode { .. } + ); + match submit(command) { + Ok(result) => { + self.pending = Some(Pending { + result, + vip: token, + go_home, + }) + } + Err(error) => { + if let Some(token) = token { + self.snapshot.vip_result = Some(VipSaveResult { + token, + result: Err(error), + }); + } else { + self.error = Some(error); + } + } + } + } + } + system + } +} diff --git a/crates/tsunagi-core/src/agent/mod.rs b/crates/tsunagi-core/src/agent/mod.rs index 901de0f..e4af583 100644 --- a/crates/tsunagi-core/src/agent/mod.rs +++ b/crates/tsunagi-core/src/agent/mod.rs @@ -1179,6 +1179,19 @@ impl Agent { self.inner.networks.read().await.contains_key(&network_id) } + /// Retrieve the locally stored secret for an explicit user export. + /// Status and ordinary network listings never include it. + pub async fn network_secret(&self, network_id: NetworkId) -> Result { + self.inner + .storage + .list_networks() + .await? + .into_iter() + .find(|network| network.network_id == network_id) + .map(|network| network.secret) + .ok_or(Error::NetworkUnknown(network_id)) + } + /// Lists configured networks and whether each is running. pub async fn list_networks(&self) -> Result> { let active: Vec = self.inner.networks.read().await.keys().copied().collect(); diff --git a/crates/tsunagi-core/src/dns/mod.rs b/crates/tsunagi-core/src/dns/mod.rs index 7748b0a..765bcc0 100644 --- a/crates/tsunagi-core/src/dns/mod.rs +++ b/crates/tsunagi-core/src/dns/mod.rs @@ -59,6 +59,56 @@ pub fn listen_plan(port: u16) -> ListenPlan { pub use server::{DnsServer, SharedZone}; pub use zone::{Answer, Query, Zone, ZoneError, ZoneName, Zones}; +/// Authoritative zones and the publication diagnostics for one agent snapshot. +pub struct RosterZones { + /// Member and service records indexed by zone. + pub zones: Zones, + /// Zone names in configured-network order. + pub labels: Vec, + /// Unusable or potentially conflicting zone names. + pub warnings: Vec, +} + +impl RosterZones { + /// Build the desktop and mobile DNS view from the same signed state. + pub fn from_networks(networks: &[crate::NetworkStatus]) -> Self { + let mut zones = Vec::new(); + let mut labels = Vec::new(); + let mut warnings = Vec::new(); + for network in networks { + let zone = match ZoneName::new(network.name.as_str()) { + Ok(zone) => zone, + Err(err) => { + warnings.push(format!( + "`{}` cannot be a zone, so its members have no names: {err}", + network.name + )); + continue; + } + }; + if let Some(warning) = zone.collision() { + warnings.push(warning); + } + labels.push(zone.as_str().to_string()); + let members = network + .members + .iter() + .filter_map(|member| Some((member.hostname.clone()?, member.overlay_address_v4?))); + let services = network + .vips + .iter() + .filter(|vip| vip.error.is_none()) + .filter_map(|vip| Some((vip.config.name.clone(), vip.address?))); + zones.push(Zone::new(zone, members.chain(services)).with_reverse_range(network.range)); + } + Self { + zones: Zones::new(zones), + labels, + warnings, + } + } +} + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] diff --git a/crates/tsunagi-core/src/dns/server.rs b/crates/tsunagi-core/src/dns/server.rs index bb4abaf..f98eb52 100644 --- a/crates/tsunagi-core/src/dns/server.rs +++ b/crates/tsunagi-core/src/dns/server.rs @@ -81,7 +81,22 @@ impl SharedZone { /// server should reply to, and replying anyway would make this a useful /// amplifier for somebody spoofing a source address. pub fn respond(zones: &Zones, query: &[u8]) -> Option> { - let packet = simple_dns::Packet::parse(query).ok()?; + match resolve(zones, query)? { + Resolution::Local(reply) | Resolution::Outside(reply) => Some(reply), + } +} + +/// An authoritative decision for a host resolver that also handles external domains. +pub enum Resolution { + /// Answer locally, including authoritative denials and protocol errors. + Local(Vec), + /// A well-formed question outside all mesh zones, with the authoritative server's REFUSED reply. + Outside(Vec), +} + +/// Distinguish an external question from an unknown name inside a mesh zone. +pub fn resolve(zones: &Zones, query: &[u8]) -> Option { + let packet = parse_message(query)?; if packet.has_flags(PacketFlag::RESPONSE) { return None; } @@ -95,18 +110,18 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option> { if packet.opcode() != simple_dns::OPCODE::StandardQuery { *reply.rcode_mut() = RCODE::NotImplemented; - return reply.build_bytes_vec().ok(); + return reply.build_bytes_vec().ok().map(Resolution::Local); } // Exactly one question. Zero is nothing to answer; more than one has no // agreed meaning and every real server rejects it. let [question] = packet.questions.as_slice() else { *reply.rcode_mut() = RCODE::FormatError; - return reply.build_bytes_vec().ok(); + return reply.build_bytes_vec().ok().map(Resolution::Local); }; if !matches!(question.qclass, QCLASS::CLASS(simple_dns::CLASS::IN)) { *reply.rcode_mut() = RCODE::Refused; - return reply.build_bytes_vec().ok(); + return reply.build_bytes_vec().ok().map(Resolution::Local); } let qname = question.qname.to_string(); @@ -117,7 +132,10 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option> { None => { reply.questions.push(question.clone()); *reply.rcode_mut() = RCODE::Refused; - return reply.build_bytes_vec_compressed().ok(); + return reply + .build_bytes_vec_compressed() + .ok() + .map(Resolution::Outside); } }; reply.questions.push(question.clone()); @@ -163,7 +181,22 @@ pub fn respond(zones: &Zones, query: &[u8]) -> Option> { } } - reply.build_bytes_vec_compressed().ok() + reply + .build_bytes_vec_compressed() + .ok() + .map(Resolution::Local) +} + +/// Parse a DNS message only after bounding its section allocations against the bytes received. +pub fn parse_message(wire: &[u8]) -> Option> { + let header = wire.get(..12)?; + let counts = |at: usize| usize::from(u16::from_be_bytes([header[at], header[at + 1]])); + // Even a root question needs five bytes. An empty root resource record needs eleven. + let minimum = 12 + counts(4) * 5 + (counts(6) + counts(8) + counts(10)) * 11; + if wire.len() < minimum || wire.len() > usize::from(u16::MAX) { + return None; + } + simple_dns::Packet::parse(wire).ok() } /// The zone's start of authority. @@ -202,8 +235,7 @@ fn query_kind(qtype: QTYPE) -> Query { /// Whether the client offered EDNS, and so how large an answer it will take. fn udp_limit(query: &[u8]) -> usize { - simple_dns::Packet::parse(query) - .ok() + parse_message(query) .and_then(|packet| packet.opt().map(|opt| opt.udp_packet_size as usize)) .unwrap_or(CLASSIC_UDP_LIMIT as u16 as usize) .clamp(CLASSIC_UDP_LIMIT, MAX_MESSAGE_LEN) @@ -214,20 +246,19 @@ fn udp_limit(query: &[u8]) -> usize { /// The records are dropped and the truncated bit set, which tells a resolver /// to ask again over TCP. Sending a reply it cannot reassemble would just /// look like packet loss. -fn truncate_for_udp(query: &[u8], reply: Vec) -> Vec { - let limit = udp_limit(query); +pub fn truncate_for_udp(query: &[u8], reply: Vec, payload_limit: usize) -> Vec { + let limit = udp_limit(query).min(payload_limit); if reply.len() <= limit { return reply; } - let Ok(parsed) = simple_dns::Packet::parse(&reply) else { + let Some(mut short) = parse_message(&reply) else { return reply; }; - let mut short = simple_dns::Packet::new_reply(parsed.id()); - short.set_flags(PacketFlag::TRUNCATION | PacketFlag::AUTHORITATIVE_ANSWER); - *short.rcode_mut() = parsed.rcode(); - for question in &parsed.questions { - short.questions.push(question.clone()); - } + short.set_flags(PacketFlag::TRUNCATION); + short.answers.clear(); + short.name_servers.clear(); + short.additional_records.clear(); + *short.opt_mut() = None; short.build_bytes_vec().unwrap_or(reply) } @@ -264,7 +295,7 @@ impl DnsServer { let Some(reply) = respond(&udp_zone.get(), query) else { continue; }; - let reply = truncate_for_udp(query, reply); + let reply = truncate_for_udp(query, reply, MAX_MESSAGE_LEN); if let Err(err) = udp.send_to(&reply, from).await { tracing::debug!(%err, "dns udp reply failed"); } @@ -494,7 +525,7 @@ mod tests { "the test needs a big answer" ); - let short = truncate_for_udp(&query, full); + let short = truncate_for_udp(&query, full, MAX_MESSAGE_LEN); assert!(short.len() <= CLASSIC_UDP_LIMIT); let parsed = simple_dns::Packet::parse(&short).unwrap(); assert!(parsed.has_flags(PacketFlag::TRUNCATION)); diff --git a/crates/tsunagi-core/src/dns/zone.rs b/crates/tsunagi-core/src/dns/zone.rs index 699117f..8c5899b 100644 --- a/crates/tsunagi-core/src/dns/zone.rs +++ b/crates/tsunagi-core/src/dns/zone.rs @@ -208,6 +208,7 @@ pub enum Answer { #[derive(Debug, Clone)] pub struct Zone { origin: ZoneName, + reverse_range: Option, /// Name relative to the origin, to the addresses it answers to. hosts: BTreeMap>, /// Address to the name that holds it. @@ -246,12 +247,23 @@ impl Zone { let serial = content_serial(&hosts); Self { origin, + // Standalone authoritative zones retain their original broad PTR view. + // Agent snapshots scope the authority to each network's actual range. + reverse_range: Some(crate::state::Ipv4Range { + base: Ipv4Addr::UNSPECIFIED, + prefix_len: 0, + }), hosts, names, serial, } } + pub(super) fn with_reverse_range(mut self, range: Option) -> Self { + self.reverse_range = range; + self + } + /// The zone's origin. pub fn origin(&self) -> &ZoneName { &self.origin @@ -300,6 +312,12 @@ impl Zone { /// Answers one question. pub fn lookup(&self, qname: &str, query: Query) -> Answer { if let Some(address) = reverse_address(qname) { + if !self + .reverse_range + .is_some_and(|range| range.contains(address)) + { + return Answer::NotOurs; + } return match self.names.get(&address) { Some(name) if query == Query::Ptr => { Answer::Name(format!("{name}.{}", self.origin.as_str())) diff --git a/crates/tsunagi-core/src/net.rs b/crates/tsunagi-core/src/net.rs index 3b56b76..f4da30d 100644 --- a/crates/tsunagi-core/src/net.rs +++ b/crates/tsunagi-core/src/net.rs @@ -254,12 +254,16 @@ impl EndpointAdapter { Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase())); { let interface_filter = Arc::clone(&owned_interface); + let factory = config.tun_factory.clone(); let filter = iroh::address_lookup::AddrFilter::new(move |addrs| { let owned_interface = interface_filter .read() .unwrap_or_else(|p| p.into_inner()) .clone(); let mut overlay_ips = std::collections::HashSet::new(); + if let Some(factory) = &factory { + overlay_ips.extend(factory.assigned_addresses()); + } for iface in netdev::get_interfaces() { let name = iface.name.to_lowercase(); let friendly = iface diff --git a/crates/tsunagi-core/src/overlay/hostrules/exit.rs b/crates/tsunagi-core/src/overlay/hostrules/exit.rs index 96addd6..cf536c4 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/exit.rs @@ -35,6 +35,8 @@ pub struct ExitHostPlan { pub offer: Vec, /// Whether this device sends its internet traffic through a member. pub client: bool, + /// Local address in the selected exit network, for hosts that choose a primary address. + pub client_source: Option, /// The range of every network on the interface. Only the using side /// reads it, to keep this agent's own traffic *to* the overlay inside it /// where the host has no per-user routing (macOS). diff --git a/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs b/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs index 3245f12..c3db54a 100644 --- a/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs +++ b/crates/tsunagi-core/src/overlay/hostrules/windows_exit.rs @@ -407,6 +407,7 @@ mod tests { overlay: vec![range()], bypass: vec![Ipv4Addr::new(138, 201, 61, 182)], bypass_hosts: vec!["relay.example".into()], + ..Default::default() } } diff --git a/crates/tsunagi-core/src/overlay/interface.rs b/crates/tsunagi-core/src/overlay/interface.rs index ebc0149..225495f 100644 --- a/crates/tsunagi-core/src/overlay/interface.rs +++ b/crates/tsunagi-core/src/overlay/interface.rs @@ -231,6 +231,7 @@ impl Interface { let tally = Arc::new(Tally::default()); let vip_task = { + let factory = Arc::clone(&factory); let routes = Arc::clone(&routes); let carrier = Arc::clone(&carrier); tokio::spawn(async move { @@ -242,7 +243,10 @@ impl Interface { _=interval.tick()=>{ let (probes,jobs)=routes.vips.tick(routes.vips.check_capacity().saturating_sub(checks.len())); for (route,packet) in probes {carrier.carry(route,packet);} - for job in jobs {checks.spawn(job.run());} + for job in jobs { + let factory = Arc::clone(&factory); + checks.spawn(job.run(move |socket, source| factory.bind_overlay_socket(socket, source))); + } }, Some(result)=checks.join_next(),if !checks.is_empty()=>{ if let Ok((job,ok))=result {routes.vips.checked(job,ok);} @@ -415,7 +419,7 @@ impl Interface { .collect(); ranges.sort_by_key(|range| (range.base, range.prefix_len)); ranges.dedup(); - let client = self.routes.exit_via().is_some(); + let (client, client_source) = self.routes.exit_client(); let overlay = self.routes.overlay_ranges(); let (bypass, bypass_hosts) = if client && exit.needs_bypass() { self.underlay_targets(&overlay) @@ -426,6 +430,7 @@ impl Interface { interface: self.name.clone(), offer: ranges, client, + client_source, overlay, bypass, bypass_hosts, diff --git a/crates/tsunagi-core/src/overlay/router.rs b/crates/tsunagi-core/src/overlay/router.rs index e17fe10..80c6c94 100644 --- a/crates/tsunagi-core/src/overlay/router.rs +++ b/crates/tsunagi-core/src/overlay/router.rs @@ -281,6 +281,15 @@ impl RoutingTable { exit_via(&self.read()) } + /// Whether a default route is selected and the local source valid in that network. + pub(crate) fn exit_client(&self) -> (bool, Option) { + let networks = self.read(); + match exit_via(&networks) { + Some((id, _)) => (true, networks.get(&id).and_then(|routes| routes.local)), + None => (false, None), + } + } + /// Networks that offer this agent as an exit node, with the range each /// agreed. A network that has not agreed one yet has nothing to /// masquerade and is left out. diff --git a/crates/tsunagi-core/src/overlay/tun.rs b/crates/tsunagi-core/src/overlay/tun.rs index 1f5bb2e..a04bc76 100644 --- a/crates/tsunagi-core/src/overlay/tun.rs +++ b/crates/tsunagi-core/src/overlay/tun.rs @@ -90,6 +90,21 @@ pub trait TunFactory: Send + Sync + std::fmt::Debug + 'static { /// land on the second. fn on_host(&self) -> bool; + /// Bind a socket carrying a VIP health check to this overlay on platforms + /// that explicitly route mesh transport sockets outside the VPN. + fn bind_overlay_socket( + &self, + _socket: &tokio::net::TcpSocket, + _source: std::net::Ipv4Addr, + ) -> std::io::Result<()> { + Ok(()) + } + + /// Assigned overlay addresses when the OS chooses a new interface name on reconfiguration. + fn assigned_addresses(&self) -> Vec { + Vec::new() + } + /// Creates a device. fn create<'a>( &'a self, @@ -229,37 +244,34 @@ impl TunDevice for MemoryTun { /// enough here: the agent chose the address, so anything else holding it is a /// problem in its own right. pub fn address_is_local(address: std::net::IpAddr) -> bool { - if std::net::UdpSocket::bind((address, 0)).is_ok() { - return true; - } + let bound = std::net::UdpSocket::bind((address, 0)).is_ok(); #[cfg(all(feature = "tun-device", target_os = "windows"))] - { - if let Ok(interfaces) = std::panic::catch_unwind(netdev::get_interfaces) { - for iface in interfaces { - if iface.is_up() { - match address { - std::net::IpAddr::V4(v4) => { - if iface.ipv4.iter().any(|ip| ip.addr() == v4) { - return true; - } + if !bound && let Ok(interfaces) = std::panic::catch_unwind(netdev::get_interfaces) { + for iface in interfaces { + if iface.is_up() { + match address { + std::net::IpAddr::V4(v4) => { + if iface.ipv4.iter().any(|ip| ip.addr() == v4) { + return true; } - std::net::IpAddr::V6(v6) => { - if iface.ipv6.iter().any(|ip| ip.addr() == v6) { - return true; - } + } + std::net::IpAddr::V6(v6) => { + if iface.ipv6.iter().any(|ip| ip.addr() == v6) { + return true; } } } } } } - false + bound } /// Creates [`MemoryTun`] devices. #[derive(Debug, Clone, Default)] pub struct MemoryTunFactory { created: Arc>>>, + rules: Option>, } impl MemoryTunFactory { @@ -268,6 +280,12 @@ impl MemoryTunFactory { Self::default() } + /// Simulate host rule outcomes alongside this in-memory interface. + pub fn with_host_rules(mut self, rules: Arc) -> Self { + self.rules = Some(rules); + self + } + /// The device created for an interface name, if any. pub fn device(&self, name: &str) -> Option> { let guard = match self.created.lock() { @@ -291,6 +309,9 @@ impl MemoryTunFactory { } impl TunFactory for MemoryTunFactory { + fn host_rules(&self) -> Option> { + self.rules.clone() + } fn name(&self) -> &str { "memory" } diff --git a/crates/tsunagi-core/src/vip/router.rs b/crates/tsunagi-core/src/vip/router.rs index 470aaf0..1852a43 100644 --- a/crates/tsunagi-core/src/vip/router.rs +++ b/crates/tsunagi-core/src/vip/router.rs @@ -92,18 +92,20 @@ type CheckKey = (NetworkId, EndpointId, Ipv4Addr, Protocol, u16); /// A bounded TCP connect check prepared off the packet path. pub(crate) struct CheckJob { key: CheckKey, + source: Ipv4Addr, timeout: Duration, } impl CheckJob { - pub async fn run(self) -> (Self, bool) { - let ok = matches!( - tokio::time::timeout( - self.timeout, - tokio::net::TcpStream::connect((self.key.2, self.key.4)) - ) - .await, - Ok(Ok(_)) - ); + pub async fn run( + self, + bind: impl FnOnce(&tokio::net::TcpSocket, Ipv4Addr) -> std::io::Result<()>, + ) -> (Self, bool) { + let connect = async { + let socket = tokio::net::TcpSocket::new_v4()?; + bind(&socket, self.source)?; + socket.connect((self.key.2, self.key.4).into()).await + }; + let ok = matches!(tokio::time::timeout(self.timeout, connect).await, Ok(Ok(_))); (self, ok) } } @@ -396,6 +398,7 @@ impl VipRouter { for (l, b) in listeners { let key = (network, peer, address, l.protocol, b.port); wanted_checks.insert(key); + let Some(source) = source else { continue }; if l.protocol != Protocol::Tcp || !l.port_check { continue; } @@ -412,6 +415,7 @@ impl VipRouter { { jobs.push(CheckJob { key, + source, timeout: Duration::from_millis(u64::from(l.check_timeout_ms)), }); } @@ -1078,6 +1082,38 @@ mod tests { }; assert_eq!(packet::tuple(&reply), Some(t.reverse())); } + #[tokio::test] + async fn tcp_check_connects_only_after_the_overlay_socket_is_bound() { + use std::io; + use std::sync::atomic::{AtomicUsize, Ordering}; + let (_, network, local, _, _, _) = fixture(Protocol::Tcp); + let server = tokio::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .await + .unwrap(); + let port = server.local_addr().unwrap().port(); + let job = || CheckJob { + key: (network, local, Ipv4Addr::LOCALHOST, Protocol::Tcp, port), + source: Ipv4Addr::LOCALHOST, + timeout: Duration::from_secs(1), + }; + let called = AtomicUsize::new(0); + let (_, ok) = job() + .run(|_, source| { + assert_eq!(source, Ipv4Addr::LOCALHOST); + called.fetch_add(1, Ordering::Relaxed); + Err(io::Error::other("VPN replaced")) + }) + .await; + assert!(!ok); + assert_eq!(called.load(Ordering::Relaxed), 1); + let (_, ok) = job() + .run(|socket, source| socket.bind((source, 0).into())) + .await; + assert!(ok); + let (_, peer) = server.accept().await.unwrap(); + assert_eq!(peer.ip(), Ipv4Addr::LOCALHOST); + } + #[tokio::test] async fn active_tcp_port_checks_recover_after_a_real_listener_appears() { let (r, n, local, _, _, _) = fixture(Protocol::Tcp); @@ -1099,7 +1135,7 @@ mod tests { } let (_, jobs) = r.tick(32); for job in jobs { - let (job, ok) = job.run().await; + let (job, ok) = job.run(|_, _| Ok(())).await; assert!(ok); r.checked(job, ok); } @@ -1112,7 +1148,7 @@ mod tests { } let (_, jobs) = r.tick(32); for job in jobs { - let (job, ok) = job.run().await; + let (job, ok) = job.run(|_, _| Ok(())).await; assert!(!ok); r.checked(job, ok); } @@ -1127,7 +1163,7 @@ mod tests { } let (_, jobs) = r.tick(32); for job in jobs { - let (job, ok) = job.run().await; + let (job, ok) = job.run(|_, _| Ok(())).await; r.checked(job, ok); } assert!(r.statuses(n)[0].listeners[0].selected.is_some()); diff --git a/crates/tsunagi-runtime/Cargo.toml b/crates/tsunagi-runtime/Cargo.toml new file mode 100644 index 0000000..f15ea10 --- /dev/null +++ b/crates/tsunagi-runtime/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "tsunagi-runtime" +version = "1.0.0" +description = "Built-in mesh transports and status reporting for native tsunagi agents." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +tsunagi-core = { path = "../tsunagi-core", version = "1.0.0" } +tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.0" } +tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.0" } +tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.0" } +tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.0" } +tokio.workspace = true +tracing.workspace = true + +[lints] +workspace = true diff --git a/crates/tsunagi-runtime/src/lib.rs b/crates/tsunagi-runtime/src/lib.rs new file mode 100644 index 0000000..7bcefe4 --- /dev/null +++ b/crates/tsunagi-runtime/src/lib.rs @@ -0,0 +1,190 @@ +//! Construct the native data transports in one place for both the CLI and Android. +//! The embedding application supplies the Tokio runtime, TUN and discovery policy. +use std::{ + net::{IpAddr, Ipv4Addr}, + sync::Arc, +}; +use tokio::{sync::watch, task::JoinSet}; +use tsunagi::{ + Agent, AgentConfig, TransportPolicy, dataplane::transport::iroh_link::IrohCarrier, + iroh_types::EndpointAddr, +}; +use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport}; +use tsunagi_tcp_tls::{TCP_TLS_PROTOCOL, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport}; +use tsunagi_wireguard::WG_PROTOCOL; + +pub mod report; + +/// What a protocol is called, what it speaks, and what it takes. +/// +/// A registry rather than a lookup on the plugins themselves, because +/// `tsng protocols` has to answer before anything is constructed, and +/// because this is the list `--protocol` resolves against. +pub struct ProtocolSpec { + /// The name on the wire, which is what peers compare. + pub name: &'static str, + /// The wire version. Not the software version: two peers on different + /// builds carry traffic for each other as long as this matches. + pub version: u16, + /// One line about what it is. + pub summary: &'static str, + /// The settings it accepts. + pub options: &'static [tsunagi::dataplane::ProtocolOption], +} + +const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption { + key: "port", + value: "PORT", + help: "preferred local UDP port; additional pairs use dynamic ports", + default: Some("51820"), +}]; + +/// Every protocol this build has. +pub const PROTOCOLS: &[ProtocolSpec] = &[ + ProtocolSpec { + name: WG_PROTOCOL, + version: tsunagi_wireguard::WG_WIRE_VERSION, + summary: "Pure WireGuard direct UDP transport", + options: WG_OPTIONS, + }, + ProtocolSpec { + name: AWG_PROTOCOL, + version: AWG_WIRE_VERSION, + summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt", + options: AwgPlugin::OPTIONS, + }, + ProtocolSpec { + name: "wg-quic", + version: 1, + summary: "iroh QUIC datagram carrier with NAT traversal and relays", + options: &[], + }, + ProtocolSpec { + name: TCP_TLS_PROTOCOL, + version: tsunagi_tcp_tls::TCP_TLS_VERSION, + summary: "TCP TLS 1.3 carrier", + options: TcpTlsConfig::OPTIONS, + }, +]; + +/// Incoming direct connections to attach after the agent has acquired its identity. +pub struct Carriers { + udp: [Arc; 2], + tls: Arc, +} + +impl Carriers { + /// Register the complete catalog. CLI options and phone defaults use the same + /// constructors and wire versions. Android supplies the addresses of its selected + /// physical network; desktop discovers addresses on its host interfaces. + pub async fn configure( + mut config: AgentConfig, + bootstrap: &[EndpointAddr], + underlay: Option>>, + options: impl Fn(&ProtocolSpec) -> Vec<(String, String)>, + ) -> Result<(AgentConfig, Self), Box> { + let options_for = |name| { + PROTOCOLS + .iter() + .find(|p| p.name == name) + .map(&options) + .unwrap_or_default() + }; + let wg_opts = options_for(WG_PROTOCOL); + let port = wg_opts + .iter() + .find(|(k, _)| k == "port") + .map(|(_, v)| v.parse::()) + .transpose()? + .unwrap_or(51820); + let awg_opts = options_for(AWG_PROTOCOL); + const STUN: &str = "stun.l.google.com:19302"; + let server = awg_opts + .iter() + .find(|(key, _)| key == "stun") + .map_or(STUN, |(_, value)| value.as_str()); + if server.len() > 255 || (server != "off" && !server.contains(':')) { + return Err("awg:stun must be HOST:PORT or off".into()); + } + let public = config.transport != TransportPolicy::LocalOnly; + let db = config.paths.state_db(); + let identity = tokio::task::spawn_blocking(move || { + tsunagi::storage::StateStore::open(db)?.load_or_create_device_identity() + }) + .await??; + let bind = Ipv4Addr::UNSPECIFIED; + let udp = [ + AwgTransport::wireguard_with_port( + identity.endpoint_id(), + bind, + public.then(|| STUN.into()), + port, + ), + AwgTransport::new_with_stun( + identity.endpoint_id(), + bind, + (public && server != "off").then(|| server.into()), + ), + ]; + for transport in &udp { + transport.exclude_interface(config.interface_name.clone()); + if let Some(source) = &underlay { + transport.set_underlay(source.clone()); + } + config = config + .with_carrier(AwgPlugin::new(transport.clone())) + .with_custom_transport(transport.protocol_id(), transport.clone()); + } + let settings = + TcpTlsConfig::configure(TcpTlsConfig::new(), &options_for(TCP_TLS_PROTOCOL))?; + let tls = Arc::new( + TcpTlsTransport::bind(&identity, settings.port, settings.sni) + .await + .map_err(|error| -> Box { error })?, + ); + for address in bootstrap { + for ip in address.ip_addrs() { + tls.set_peer_addr(address.id, *ip); + } + } + let carrier = TcpTlsCarrier::with_interface(tls.clone(), config.interface_name.clone()); + if let Some(source) = underlay { + carrier.set_underlay(source); + } + config = config + .with_carrier(Arc::new(IrohCarrier)) + .with_carrier(carrier) + .with_custom_transport(TCP_TLS_PROTOCOL, tls.clone()); + Ok((config, Self { udp, tls })) + } + + /// Accept incoming authenticated links until the caller drops the returned task set. + #[must_use = "keep the listeners alive for the lifetime of this agent"] + pub fn listen(self, agent: &Agent) -> JoinSet<()> { + let mut tasks = JoinSet::new(); + for transport in self.udp { + let agent = agent.clone(); + tasks.spawn(async move { + while let Some(inbound) = transport.next_inbound().await { + if let Err(error) = agent.install_inbound_link(inbound).await { + tracing::debug!(%error, protocol=transport.protocol_id(), "inbound link rejected"); + } + } + }); + } + let agent = agent.clone(); + tasks.spawn(async move { + self.tls + .accept_loop(move |inbound| { + let agent = agent.clone(); + tokio::spawn(async move { + if let Err(error) = agent.install_inbound_link(inbound).await { + tracing::debug!(%error, "inbound tcp-tls link rejected"); + } + }); + }) + .await; + }); + tasks + } +} diff --git a/crates/tsunagi-runtime/src/report.rs b/crates/tsunagi-runtime/src/report.rs new file mode 100644 index 0000000..58e2390 --- /dev/null +++ b/crates/tsunagi-runtime/src/report.rs @@ -0,0 +1,201 @@ +//! Combine the core snapshot and live WireGuard observations for local clients. +use tsunagi::ipc::{MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport}; +use tsunagi::{AgentStatus, agent::OverlayStatus}; +use tsunagi_wg_quic::WireguardPlugin; + +/// Build the same per-network view for an in-process client and the CLI's IPC server. +pub fn networks( + status: &AgentStatus, + overlay: Option<&OverlayStatus>, + wireguard: Option<&WireguardPlugin>, +) -> Vec { + status + .networks + .iter() + .map(|network| { + let wg_view = wireguard.and_then(|plugin| plugin.overview(network.network_id)); + let wg_overlay_addr = wg_view.as_ref().and_then(|v| v.overlay_address_v4); + let wg_prefix_len = wg_view + .as_ref() + .and_then(|v| v.ipv4_range) + .map_or(0, |r| r.prefix_len); + let has_any_plugin = wg_view.is_some(); + + let overlay = if has_any_plugin && overlay.is_some() { + let mut peers: Vec = Vec::new(); + + if let Some(view) = &wg_view { + for peer in &view.peers { + let tunnel = peer.tunnel.as_ref(); + peers.push(OverlayPeerReport { + counter_epoch: tunnel.map_or(0, |t| t.stats.counter_epoch), + endpoint_id: peer.endpoint_id.to_string(), + protocol: String::new(), + public_key: peer.public_key.to_string(), + address: peer.overlay_address_v4.map(|a| a.to_string()), + handshake_secs_ago: tunnel + .and_then(|t| t.health.since_handshake.map(|s| s.as_secs())), + tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets), + rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets), + tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes), + rx_bytes: tunnel.map_or(0, |t| t.stats.rx_bytes), + dropped: tunnel.map_or(0, |t| { + t.stats.dropped_wrong_source + t.stats.dropped_oversize + }), + protocol_errors: tunnel.map_or(0, |t| t.stats.protocol_errors), + path: tunnel.map_or_else(|| "no data path".into(), |t| t.path.clone()), + }); + } + } + + let (address, prefix_len) = if wg_overlay_addr.is_some() { + (wg_overlay_addr.map(|addr| addr.to_string()), wg_prefix_len) + } else { + ( + network + .members + .iter() + .find(|m| m.endpoint_id == status.endpoint_id) + .and_then(|m| m.overlay_address_v4) + .map(|a| a.to_string()), + network.range.map_or(0, |r| r.prefix_len), + ) + }; + + Some(OverlayReport { + interface: overlay.map_or_else(String::new, |o| o.interface.clone()), + on_host: overlay.is_some_and(|o| o.on_host), + mtu: overlay.map_or(0, |o| o.mtu), + address, + prefix_len, + peers, + unroutable_packets: overlay.map_or(0, |o| o.counters.unroutable), + multicast_packets: overlay.map_or(0, |o| o.counters.multicast), + unroutable_sample: overlay + .and_then(|o| o.counters.unroutable_sample.map(|a| a.to_string())), + broadcast_rules: overlay.and_then(|o| o.broadcast_rules.as_ref()).map( + |rules| tsunagi::ipc::HostRulesReport { + ok: rules.is_ok(), + detail: rules.summary(), + source: rules.plan.source.to_string(), + }, + ), + }) + } else { + None + }; + + NetworkReport { + vips: network.vips.clone(), + protocols: network.protocols.clone(), + auto_start: network.auto_start, + exit: exit_report(network), + broadcast: network.broadcast, + name: network.name.to_string(), + network_id: network.network_id.to_string(), + active: matches!(network.state, tsunagi::agent::NetworkState::Active), + candidates: network.candidates.len() as u32, + relay_forwarded: network.relay.forwarded, + relay_sent_via: network.relay.sent_via, + relay_received_via: network.relay.received_via, + peers: network + .peers + .iter() + .map(|peer| PeerReport { + data_error: peer.data_error.clone(), + endpoint_id: peer.endpoint_id.to_string(), + hostname: peer.hostname.clone(), + transport: peer.transport.to_string(), + rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64), + exit_node: peer.exit_node, + path: data_path_report(&peer.data_path), + }) + .collect(), + members: network + .members + .iter() + .map(|member| MemberReport { + record_version: member.record_version, + endpoint_id: member.endpoint_id.to_string(), + overlay_address_v4: member.overlay_address_v4.map(|addr| addr.to_string()), + // What this agent is currently experiencing trying to + // reach it, so a dial-failure count can be attributed + // to the member it belongs to instead of floating + // free as a network-wide number. + failed_dials: network + .candidates + .iter() + .find(|candidate| candidate.endpoint_id == member.endpoint_id) + .map_or(0, |candidate| candidate.consecutive_failures), + hostname: member + .last_hostname + .clone() + .or_else(|| member.hostname.clone()), + online: member.online, + path: data_path_report(&member.data_path), + hostname_conflict: member.hostname_conflict.as_ref().map(conflict_report), + }) + .collect(), + range: network.range.map(|range| range.to_string()), + range_conflict: network.range_conflict.map(|range| range.to_string()), + range_conflicts: network + .range_conflicts + .iter() + .map(|c| tsunagi::ipc::RangeConflictReport { + network_id: c.network_id.to_string(), + name: c.name.to_string(), + range: c.range.to_string(), + }) + .collect(), + dial_failures: network.metrics.dial_failures, + handshake_failures: network.metrics.handshake_failures, + control_messages: ( + network.metrics.control_messages_sent, + network.metrics.control_messages_received, + ), + overlay, + hostname_conflict: network.hostname_conflict.as_ref().map(conflict_report), + } + }) + .collect() +} + +fn data_path_report(path: &tsunagi::agent::DataPath) -> tsunagi::ipc::DataPathReport { + match path { + tsunagi::agent::DataPath::None => tsunagi::ipc::DataPathReport::None, + tsunagi::agent::DataPath::Direct { transport } => tsunagi::ipc::DataPathReport::Direct { + transport: transport.clone(), + }, + tsunagi::agent::DataPath::Relayed { hops, via } => tsunagi::ipc::DataPathReport::Relayed { + hops: *hops, + via: via.to_string(), + }, + } +} + +fn conflict_report( + conflict: &tsunagi::agent::HostnameConflict, +) -> tsunagi::ipc::HostnameConflictReport { + tsunagi::ipc::HostnameConflictReport { + name: conflict.name.clone(), + holder: conflict.holder.to_string(), + } +} + +/// One network's exit-node settings, as the control interface reports them. +fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitReport { + let rules = |report: &Option| { + report.as_ref().map(|report| tsunagi::ipc::RuleSetReport { + ok: report.ok, + detail: report.detail.clone(), + }) + }; + tsunagi::ipc::ExitReport { + offering: network.exit_offer, + offer_rules: rules(&network.exit_rules.offer), + forwarding: network.exit_rules.forwarding, + via: network.exit_via.map(|peer| peer.to_string()), + via_online: network.exit_via_online, + client_rules: rules(&network.exit_rules.client), + } +} diff --git a/crates/tsunagi-tcp-tls/src/plugin.rs b/crates/tsunagi-tcp-tls/src/plugin.rs index d611f04..d9b77e5 100644 --- a/crates/tsunagi-tcp-tls/src/plugin.rs +++ b/crates/tsunagi-tcp-tls/src/plugin.rs @@ -156,10 +156,7 @@ pub(crate) fn is_candidate_ip(addr: std::net::IpAddr) -> bool { } let segments = v6.segments(); // Filter link-local fe80::/10 - if (segments[0] & 0xffc0) == 0xfe80 { - return false; - } - true + (segments[0] & 0xffc0) != 0xfe80 } } } @@ -238,6 +235,7 @@ impl TcpTlsConfig { pub struct TcpTlsCarrier { transport: Arc, excluded_interface: std::sync::Mutex>, + underlay: std::sync::OnceLock>>, peers: std::sync::Mutex< std::collections::HashMap<(NetworkId, EndpointId), Vec>, >, @@ -248,6 +246,7 @@ impl TcpTlsCarrier { Arc::new(Self { transport, excluded_interface: std::sync::Mutex::new(None), + underlay: Default::default(), peers: Default::default(), }) } @@ -256,9 +255,14 @@ impl TcpTlsCarrier { Arc::new(Self { transport, excluded_interface: std::sync::Mutex::new(Some(interface)), + underlay: Default::default(), peers: Default::default(), }) } + /// Use only the addresses assigned to the OS-selected physical network. + pub fn set_underlay(&self, source: tokio::sync::watch::Receiver>) { + let _ = self.underlay.set(source); + } fn update_peer( &self, network: NetworkId, @@ -302,17 +306,23 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier { &self, _: NetworkId, ) -> Result, PluginError> { - let data = postcard::to_allocvec(&( - self.transport.bound_port(), - local_ip_candidates_excluding( + let ips = match self.underlay.get() { + Some(source) => source + .borrow() + .iter() + .copied() + .filter(|ip| is_candidate_ip(*ip)) + .collect(), + None => local_ip_candidates_excluding( self.excluded_interface .lock() .unwrap_or_else(|p| p.into_inner()) .as_deref(), - ) - .into_iter() - .take(32) - .collect::>(), + ), + }; + let data = postcard::to_allocvec(&( + self.transport.bound_port(), + ips.into_iter().take(32).collect::>(), )) .map_err(|_| PluginError::Other("cannot encode TLS addresses".into()))?; Ok(Some(tsunagi::dataplane::PluginCapability { diff --git a/crates/tsunagi-tray/Cargo.toml b/crates/tsunagi-tray/Cargo.toml index 22b3e8b..5ba67d0 100644 --- a/crates/tsunagi-tray/Cargo.toml +++ b/crates/tsunagi-tray/Cargo.toml @@ -12,6 +12,7 @@ name = "tsunagi-tray" path = "src/main.rs" [dependencies] +tsunagi-ui = { path = "../tsunagi-ui" } # The agent control client and the report types: the GUI is a thin client over # the same local control interface the CLI uses, so it reuses these directly # and never re-implements the protocol. diff --git a/crates/tsunagi-tray/src/agent.rs b/crates/tsunagi-tray/src/agent.rs index 73588a8..efb4188 100644 --- a/crates/tsunagi-tray/src/agent.rs +++ b/crates/tsunagi-tray/src/agent.rs @@ -14,76 +14,21 @@ use std::time::{Duration, Instant}; use eframe::egui; use tokio::sync::mpsc; -use tsunagi::ipc::{self, StatusReport}; +use tsunagi::ipc; /// How often the worker refreshes status while idle. const POLL_INTERVAL: Duration = Duration::from_secs(2); -/// A request from the UI to the agent. -pub(crate) enum Command { - SaveVip { - token: String, - network_id: String, - config: tsunagi::vip::VipConfig, - expected: Option, - delete: bool, - }, - /// Retire the exact offline-node claim selected in the devices window. - ForgetNode { - network_id: String, - peer: String, - expected_version: u64, - }, - /// Replace the network's enabled protocols in preference order. - SetProtocols { - network_id: String, - protocols: Vec, - }, - /// Stop serving a network, or start serving it again. - SetActive { network_id: String, active: bool }, - /// Turn local broadcast participation on or off for a network. - SetBroadcast { network_id: String, enabled: bool }, - /// Offer this device as an exit node in a network, or stop. - SetExitOffer { network_id: String, enabled: bool }, - /// Send all this device's internet traffic through a member of a - /// network, or (`None`) back the ordinary way. - SetExitNode { - network_id: String, - peer: Option, - }, - /// Join a network, or start one already configured. - Join { name: String, secret: String }, - /// Leave a network entirely. - Leave { network_id: String }, - /// Change the hostname this device announces. - SetHostname(String), - /// Fetch a network's shared secret and place it on the clipboard. - CopySecret { network_id: String }, -} +use tsunagi_ui::client::Client; +pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult}; -/// The latest the worker knows, read by the UI each frame. -#[derive(Clone)] -pub(crate) struct VipSaveResult { - pub token: String, - pub result: Result, String>, -} -#[derive(Clone, Default)] -pub(crate) struct Snapshot { - pub vip_result: Option, - /// The last status, or the reason it could not be read (agent down, no - /// permission on the socket, …). - pub status: Option>, - /// The outcome of the most recent command, for a transient banner. - pub last_action: Option>, - /// Whether a command is currently being executed. - pub busy: bool, - /// Bumped each time `status` is refreshed, so the UI can tell new data from - /// a repaint of the same data and sample traffic rates only on change. - pub generation: u64, - /// When this status was read, for computing rates between refreshes. - pub at: Option, - /// The socket the last request went to. - pub socket: PathBuf, +impl Client for AgentClient { + fn send(&self, command: Command) { + self.send(command); + } + fn busy(&self) -> bool { + lock(&self.shared).busy + } } /// Handle the UI holds: send commands, read the latest snapshot. @@ -97,18 +42,6 @@ pub(crate) struct AgentClient { } impl AgentClient { - #[cfg(test)] - pub(crate) fn test_client() -> (Self, mpsc::UnboundedReceiver) { - let (tx, rx) = mpsc::unbounded_channel(); - ( - Self { - tx, - shared: Arc::new(Mutex::new(Snapshot::default())), - pending_copy: Arc::new(Mutex::new(None)), - }, - rx, - ) - } /// Starts the worker on `runtime`, reporting to `ctx` (for repaints). pub(crate) fn spawn(runtime: &tokio::runtime::Handle, ctx: egui::Context) -> Self { let (tx, rx) = mpsc::unbounded_channel(); @@ -203,7 +136,7 @@ async fn refresh(shared: &Arc>, ctx: &egui::Context) { .map_err(|err| err.to_string()); { let mut guard = lock(shared); - guard.status = Some(status); + guard.status = Some(status.map(Arc::new)); guard.generation = guard.generation.wrapping_add(1); guard.at = Some(Instant::now()); guard.socket = socket; diff --git a/crates/tsunagi-tray/src/app.rs b/crates/tsunagi-tray/src/app.rs index c89c941..1789f35 100644 --- a/crates/tsunagi-tray/src/app.rs +++ b/crates/tsunagi-tray/src/app.rs @@ -15,11 +15,7 @@ use crate::devices; use crate::stats::Traffic; use crate::ui::{self, UiState}; -fn app_fonts() -> egui::FontDefinitions { - let mut fonts = egui::FontDefinitions::default(); - egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); - fonts -} +use tsunagi_ui::app_fonts; /// The window's state. pub(crate) struct App { @@ -140,7 +136,7 @@ impl App { egui::ViewportId::from_hash_of("about"), builder, |vctx, _class| { - about::show(vctx, &socket, snapshot); + about::show(vctx, Some(&socket), snapshot); !vctx.input(|i| i.viewport().close_requested()) }, ); diff --git a/crates/tsunagi-tray/src/main.rs b/crates/tsunagi-tray/src/main.rs index dd2019a..f10e771 100644 --- a/crates/tsunagi-tray/src/main.rs +++ b/crates/tsunagi-tray/src/main.rs @@ -9,19 +9,15 @@ // Nothing here is a library. #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] -mod about; +use tsunagi_ui::about; mod agent; mod app; -mod devices; -mod exit; -mod format; +use tsunagi_ui::devices; mod icon; -mod stats; -mod table; +use tsunagi_ui::stats; mod tray; mod ui; -mod vip; -mod vip_status; +use tsunagi_ui::vip; mod watch; use eframe::egui; diff --git a/crates/tsunagi-tray/src/ui.rs b/crates/tsunagi-tray/src/ui.rs index bb90249..6f743cd 100644 --- a/crates/tsunagi-tray/src/ui.rs +++ b/crates/tsunagi-tray/src/ui.rs @@ -3,67 +3,22 @@ //! [`crate::devices`]), opened from each tile. //! //! Pure rendering: state comes from the snapshot and the traffic sampler, a -//! change to a switch or button sends a [`Command`] to the worker, and local UI +//! change to a switch or button sends a [`tsunagi_ui::client::Command`] to the worker, and local UI //! state (the join form, the unit toggle, which devices windows are open, an //! in-progress hostname edit) lives in [`UiState`]. -use std::collections::BTreeSet; +pub(crate) use tsunagi_ui::home::UiState; +use tsunagi_ui::home::{draw_header, draw_join, draw_network}; use eframe::egui; use egui_phosphor::regular as icon; -use tsunagi::ipc::{NetworkReport, StatusReport}; - -use crate::agent::{AgentClient, Command, Snapshot}; +use crate::agent::{AgentClient, Snapshot}; use crate::devices; -use crate::exit; -use crate::format; use crate::stats::{Traffic, Unit}; const OK: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a); const BAD: egui::Color32 = egui::Color32::from_rgb(0xd0, 0x4a, 0x3c); -/// A neutral, not-garish red for the Leave button. -const LEAVE_RED: egui::Color32 = egui::Color32::from_rgb(0xa8, 0x3a, 0x3a); - -/// Join form fields. -#[derive(Default)] -pub(crate) struct JoinForm { - pub(crate) name: String, - pub(crate) secret: String, -} - -/// Local UI state kept across frames. -pub(crate) struct UiState { - pub(crate) join: JoinForm, - /// Whether rates and sparklines are shown in packets or bytes. - pub(crate) unit: Unit, - /// An in-progress hostname edit (`None` when not editing). - pub(crate) host_edit: Option, - /// Network ids whose devices window is open. - pub(crate) open_devices: BTreeSet, - pub(crate) vip_windows: std::collections::BTreeMap, - /// Whether the About window is open. - pub(crate) about_open: bool, - /// An exit-node choice waiting for the user to confirm it. - pub(crate) exit_confirm: Option, - /// A selected offline claim waiting for cleanup confirmation. - pub(crate) forget_confirm: Option, -} - -impl Default for UiState { - fn default() -> Self { - Self { - join: JoinForm::default(), - unit: Unit::Packets, - host_edit: None, - open_devices: BTreeSet::new(), - vip_windows: Default::default(), - about_open: false, - exit_confirm: None, - forget_confirm: None, - } - } -} /// Draws the main window. pub(crate) fn draw( @@ -128,7 +83,7 @@ pub(crate) fn draw( ui.weak("No networks yet — join one below."); } for network in &report.networks { - draw_network(ui, agent, state, traffic, network, report); + draw_network(ui, agent, state, traffic, network, report, true); } }); } @@ -154,350 +109,3 @@ fn draw_unreachable(ui: &mut egui::Ui, agent: &AgentClient, error: &str) { (its group, mode 0660).", ); } - -/// The device header: id (with a copy button) and an editable hostname. -fn draw_header(ui: &mut egui::Ui, agent: &AgentClient, state: &mut UiState, report: &StatusReport) { - ui.add_space(4.0); - ui.horizontal(|ui| { - ui.weak("device"); - // Clicking the shortened id copies the full one. - format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id); - }); - - ui.horizontal(|ui| { - ui.weak("host"); - match &mut state.host_edit { - None => { - ui.label(&report.hostname); - if ui - .small_button(icon::PENCIL_SIMPLE) - .on_hover_text("rename") - .clicked() - { - state.host_edit = Some(report.hostname.clone()); - } - } - Some(buffer) => { - let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0)); - let submit = (response.lost_focus() - && ui.input(|i| i.key_pressed(egui::Key::Enter))) - || ui.small_button(icon::CHECK).on_hover_text("save").clicked(); - if submit { - agent.send(Command::SetHostname(buffer.trim().to_string())); - state.host_edit = None; - } else if ui.small_button(icon::X).on_hover_text("cancel").clicked() { - state.host_edit = None; - } - } - } - }); - - if !report.cache_healthy { - ui.colored_label( - egui::Color32::from_rgb(0xd9, 0x9a, 0x00), - "cache unavailable", - ); - } -} - -/// One compact network tile. -fn draw_network( - ui: &mut egui::Ui, - agent: &AgentClient, - state: &mut UiState, - traffic: &Traffic, - network: &NetworkReport, - report: &StatusReport, -) { - ui.add_space(6.0); - egui::Frame::group(ui.style()).show(ui, |ui| { - ui.horizontal(|ui| { - format::copy_field(ui, network.name.as_str(), &network.name); - if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();} - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let leave = - egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE)) - .fill(LEAVE_RED); - if ui.add(leave).clicked() { - agent.send(Command::Leave { - network_id: network.network_id.clone(), - }); - } - }); - }); - - let address = network.overlay.as_ref().and_then(|o| o.address.as_ref()); - let series = traffic.network(&network.network_id); - - egui::Grid::new(("net", &network.network_id)) - .num_columns(2) - .spacing([10.0, 3.0]) - .show(ui, |ui| { - ui.weak("id"); - format::copy_field(ui, &format::short(&network.network_id), &network.network_id); - ui.end_row(); - - if let Some(range) = &network.range { - ui.weak("range"); - format::copy_field(ui, range, range); - ui.end_row(); - } - if let Some(address) = address { - ui.weak("addr"); - format::copy_field(ui, address, address); - ui.end_row(); - } - ui.weak("peers"); - ui.label(format!( - "{} online · {} known", - devices::online_count(network, &report.endpoint_id), - devices::known_count(network, &report.endpoint_id) - )); - ui.end_row(); - }); - - draw_protocols(ui, agent, network, &report.available_protocols); - - format::sparkline(ui, series, state.unit, 34.0); - - if !network.range_conflicts.is_empty() { - ui.colored_label(BAD, "Stopped: overlapping network ranges"); - for conflict in &network.range_conflicts { - ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range)); - } - ui.label("Switching suspends these networks until this network stops, then resumes them automatically."); - if network.auto_start { ui.weak("This network will resume automatically when its range is free."); } - } - ui.horizontal(|ui| { - if !network.active && !network.range_conflicts.is_empty() { - if ui.button("Switch to this network").clicked() { - agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true }); - } - if network.auto_start && ui.button("Keep stopped").clicked() { - agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false }); - } - } else { - let mut active = network.active; - if ui.checkbox(&mut active, "active").changed() { - agent.send(Command::SetActive { - network_id: network.network_id.clone(), - active, - }); - } - } - let mut broadcast = network.broadcast; - if ui.checkbox(&mut broadcast, "broadcast").changed() { - agent.send(Command::SetBroadcast { - network_id: network.network_id.clone(), - enabled: broadcast, - }); - } - let mut offering = network.exit.offering; - if ui - .checkbox(&mut offering, "exit node") - .on_hover_text( - "let other members send all their internet traffic through this \ - device, which can see it", - ) - .changed() - { - agent.send(Command::SetExitOffer { - network_id: network.network_id.clone(), - enabled: offering, - }); - } - }); - ui.horizontal(|ui| { - // In the bottom left corner while this device sends its traffic through - // somebody: green while that works, red while it does not. - if let Some(via) = &network.exit.via { - let color = if network.exit.via_online { - exit::GOOD - } else { - exit::LOUD - }; - let response = ui - .add( - egui::Label::new( - egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color), - ) - .sense(egui::Sense::click()), - ) - .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text(format!( - "exit node: {} — click to stop", - exit::name_of(network, via) - )); - if response.clicked() { - state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via)); - } - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Show devices").clicked() { - state.open_devices.insert(network.network_id.clone()); - } - if ui - .button(format!("{} Copy secret", icon::COPY)) - .on_hover_text("copy this network's secret to the clipboard") - .clicked() - { - agent.send(Command::CopySecret { - network_id: network.network_id.clone(), - }); - } - }); - }); - for warning in exit::warnings(network) { - draw_exit_warning(ui, &warning); - } - }); -} - -fn draw_protocols( - ui: &mut egui::Ui, - agent: &AgentClient, - network: &NetworkReport, - available: &[tsunagi::ipc::ProtocolReport], -) { - let summary = if network.protocols.is_empty() { - "none".into() - } else { - network.protocols.join(", ") - }; - egui::CollapsingHeader::new(format!("data transports {summary}")) - .id_salt(("protocols", &network.network_id)) - .show(ui, |ui| { - ui.weak("Preference order; changes apply immediately and are saved."); - let mut selected = network.protocols.clone(); - let mut changed = false; - ui.add_enabled_ui(!agent.snapshot().busy, |ui| { - // Enabled items follow the user's preference; unchecked items - // follow the agent's catalog. The worker refreshes after edits. - let ordered: Vec<_> = network - .protocols - .iter() - .filter_map(|name| available.iter().find(|p| &p.name == name)) - .chain( - available - .iter() - .filter(|p| !network.protocols.contains(&p.name)), - ) - .collect(); - for protocol in ordered { - ui.horizontal(|ui| { - let mut on = selected.contains(&protocol.name); - if ui.checkbox(&mut on, &protocol.name).changed() { - if on { - selected.push(protocol.name.clone()); - } else { - selected.retain(|p| p != &protocol.name); - } - changed = true; - } - if let Some(index) = selected.iter().position(|p| p == &protocol.name) { - if ui - .add_enabled(index > 0, egui::Button::new(icon::ARROW_UP)) - .on_hover_text("prefer earlier") - .clicked() - { - selected.swap(index, index - 1); - changed = true; - } - if ui - .add_enabled( - index + 1 < selected.len(), - egui::Button::new(icon::ARROW_DOWN), - ) - .on_hover_text("prefer later") - .clicked() - { - selected.swap(index, index + 1); - changed = true; - } - } - }); - ui.indent(("description", &network.network_id, &protocol.name), |ui| { - ui.weak(&protocol.summary); - }); - } - }); - if selected.is_empty() { - ui.weak("Control only; no IP traffic in this network."); - } - if changed { - agent.send(Command::SetProtocols { - network_id: network.network_id.clone(), - protocols: selected, - }); - } - }); -} - -/// A prominent line about an exit node. One that carries a command copies it -/// when clicked. -fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) { - let text = egui::RichText::new(format!("{} {}", icon::WARNING, warning.text)) - .color(exit::LOUD) - .strong(); - let label = egui::Label::new(text).wrap(); - match warning.copy { - Some(command) => { - let response = ui - .add(label.sense(egui::Sense::click())) - .on_hover_cursor(egui::CursorIcon::PointingHand) - .on_hover_text("click to copy the command"); - if response.clicked() { - ui.ctx().copy_text(command.to_owned()); - } - } - None => { - ui.add(label); - } - } -} - -/// The join form: aligned name and secret, a generate button, and Join. -fn draw_join(ui: &mut egui::Ui, agent: &AgentClient, join: &mut JoinForm) { - const INPUT_WIDTH: f32 = 208.0; - ui.label("Join or create a network"); - egui::Grid::new("join") - .num_columns(2) - .spacing([8.0, 6.0]) - .show(ui, |ui| { - ui.label("name"); - ui.add(egui::TextEdit::singleline(&mut join.name).desired_width(INPUT_WIDTH)); - ui.end_row(); - - ui.label("secret"); - ui.horizontal(|ui| { - ui.add( - egui::TextEdit::singleline(&mut join.secret) - .desired_width(INPUT_WIDTH - 26.0) - .password(true), - ); - if ui - .button(icon::SHUFFLE) - .on_hover_text("Generate a new random secret") - .clicked() - { - join.secret = tsunagi::identity::NetworkSecret::generate() - .encode() - .as_str() - .to_owned(); - } - }); - ui.end_row(); - }); - - let ready = !join.name.trim().is_empty() && !join.secret.trim().is_empty(); - if ui - .add_enabled(ready, egui::Button::new("Join / create")) - .clicked() - { - agent.send(Command::Join { - name: join.name.trim().to_string(), - secret: join.secret.trim().to_string(), - }); - join.secret.clear(); - } -} diff --git a/crates/tsunagi-ui/Cargo.toml b/crates/tsunagi-ui/Cargo.toml new file mode 100644 index 0000000..edf76a8 --- /dev/null +++ b/crates/tsunagi-ui/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "tsunagi-ui" +version = "1.0.0" +description = "Shared egui widgets for the tray and Android clients." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] +egui = "0.31" +egui-phosphor = "0.9" +zeroize = "1.9" +tsunagi-core = { path = "../tsunagi-core" } + +[lints] +workspace = true diff --git a/crates/tsunagi-tray/src/about.rs b/crates/tsunagi-ui/src/about.rs similarity index 83% rename from crates/tsunagi-tray/src/about.rs rename to crates/tsunagi-ui/src/about.rs index d454eab..2a4026c 100644 --- a/crates/tsunagi-tray/src/about.rs +++ b/crates/tsunagi-ui/src/about.rs @@ -4,11 +4,9 @@ //! half is whatever the agent says about itself, so a client and an agent that //! are not the same build show up as such. -use eframe::egui; - use tsunagi::ipc::{PrivilegeReport, StatusReport}; -use crate::agent::Snapshot; +use crate::client::Snapshot; use crate::format; const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); @@ -16,7 +14,7 @@ const AUTHOR: &str = "AB "; const VERSION: &str = env!("CARGO_PKG_VERSION"); /// Draws the window body into its viewport. -pub(crate) fn show(ctx: &egui::Context, socket: &std::path::Path, snapshot: &Snapshot) { +pub fn show(ctx: &egui::Context, socket: Option<&std::path::Path>, snapshot: &Snapshot) { egui::CentralPanel::default().show(ctx, |ui| { // Long paths and a taller agent table must scroll rather than be cut. egui::ScrollArea::both() @@ -25,7 +23,7 @@ pub(crate) fn show(ctx: &egui::Context, socket: &std::path::Path, snapshot: &Sna }); } -fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) { +fn body(ui: &mut egui::Ui, socket: Option<&std::path::Path>, snapshot: &Snapshot) { { ui.horizontal(|ui| { ui.heading("tsunagi"); @@ -61,11 +59,13 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) { ui.add_space(8.0); section(ui, "agent"); - let socket = socket.display().to_string(); + let socket = socket.map(|p| p.display().to_string()); match &snapshot.status { None => { grid(ui, "about agent", |ui| { - row(ui, "socket", |ui| format::copy_field(ui, &socket, &socket)); + if let Some(socket) = &socket { + row(ui, "socket", |ui| format::copy_field(ui, socket, socket)); + } row(ui, "state", |ui| { ui.label("connecting…"); }); @@ -73,7 +73,9 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) { } Some(Err(error)) => { grid(ui, "about agent", |ui| { - row(ui, "socket", |ui| format::copy_field(ui, &socket, &socket)); + if let Some(socket) = &socket { + row(ui, "socket", |ui| format::copy_field(ui, socket, socket)); + } row(ui, "state", |ui| { ui.colored_label(egui::Color32::from_rgb(0xd8, 0x4a, 0x3a), "unreachable"); }); @@ -82,14 +84,16 @@ fn body(ui: &mut egui::Ui, socket: &std::path::Path, snapshot: &Snapshot) { }); }); } - Some(Ok(report)) => agent_table(ui, &socket, report), + Some(Ok(report)) => agent_table(ui, socket.as_deref(), report), } } } -fn agent_table(ui: &mut egui::Ui, socket: &str, report: &StatusReport) { +fn agent_table(ui: &mut egui::Ui, socket: Option<&str>, report: &StatusReport) { grid(ui, "about agent", |ui| { - row(ui, "socket", |ui| format::copy_field(ui, socket, socket)); + if let Some(socket) = socket { + row(ui, "socket", |ui| format::copy_field(ui, socket, socket)); + } row(ui, "state", |ui| { ui.colored_label(egui::Color32::from_rgb(0x3c, 0xb0, 0x4a), "connected"); }); @@ -134,7 +138,11 @@ fn agent_table(ui: &mut egui::Ui, socket: &str, report: &StatusReport) { ui.weak("unknown"); } PrivilegeReport::Available => { - ui.label("can be managed (CAP_NET_ADMIN)"); + ui.label(if socket.is_some() { + "can be managed (CAP_NET_ADMIN)" + } else { + "Android VPN service" + }); } PrivilegeReport::Missing(_) => { ui.colored_label(egui::Color32::from_rgb(0xd8, 0x9a, 0x2a), "no privileges"); diff --git a/crates/tsunagi-ui/src/client.rs b/crates/tsunagi-ui/src/client.rs new file mode 100644 index 0000000..f193563 --- /dev/null +++ b/crates/tsunagi-ui/src/client.rs @@ -0,0 +1,121 @@ +//! Commands and observations shared by both graphical clients. +use std::{path::PathBuf, time::Instant}; +use tsunagi::ipc::StatusReport; + +/// A request from the UI to the agent. +pub enum Command { + /// Commit one complete VIP draft if its revision is current. + SaveVip { + /// Local acknowledgement token for this Save. + token: String, + /// Exact network identity. + network_id: String, + /// Complete edited configuration. + config: tsunagi::vip::VipConfig, + /// Revision originally opened in the form. + expected: Option, + /// Retire this revision when saved. + delete: bool, + }, + /// Retire the exact offline-node claim selected in the devices window. + ForgetNode { + /// Exact network identity. + network_id: String, + /// Selected member identity. + peer: String, + /// Observed claim version. + expected_version: u64, + }, + /// Replace the network's enabled protocols in preference order. + SetProtocols { + /// Exact network identity. + network_id: String, + /// Enabled transports in preference order. + protocols: Vec, + }, + /// Stop serving a network, or start serving it again. + SetActive { + /// Exact network identity. + network_id: String, + /// Whether to run the network. + active: bool, + }, + /// Turn local broadcast participation on or off for a network. + SetBroadcast { + /// Exact network identity. + network_id: String, + /// Requested local setting. + enabled: bool, + }, + /// Offer this device as an exit node in a network, or stop. + SetExitOffer { + /// Exact network identity. + network_id: String, + /// Requested local setting. + enabled: bool, + }, + /// Send all this device's internet traffic through a member of a + /// network, or (`None`) back the ordinary way. + SetExitNode { + /// Exact network identity. + network_id: String, + /// Selected member identity. + peer: Option, + }, + /// Join a network, or start one already configured. + Join { + /// Network name. + name: String, + /// Locally supplied join secret. + secret: zeroize::Zeroizing, + }, + /// Leave a network entirely. + Leave { + /// Exact network identity. + network_id: String, + }, + /// Change the hostname this device announces. + SetHostname(String), + /// Fetch a network's shared secret and place it on the clipboard. + CopySecret { + /// Exact network identity. + network_id: String, + }, +} + +/// Response to one revision-checked VIP write. +#[derive(Clone)] +pub struct VipSaveResult { + /// Request being acknowledged. + pub token: String, + /// Current VIPs or the error for this draft. + pub result: Result, String>, +} +/// Current observations and last command outcome from a local agent. +#[derive(Clone, Default)] +pub struct Snapshot { + /// Most recent saved draft. + pub vip_result: Option, + /// The last status, or the reason it could not be read (agent down, no + /// permission on the socket, …). + pub status: Option, String>>, + /// The outcome of the most recent command, for a transient banner. + pub last_action: Option>, + /// Whether a command is currently being executed. + pub busy: bool, + /// Bumped each time `status` is refreshed, so the UI can tell new data from + /// a repaint of the same data and sample traffic rates only on change. + pub generation: u64, + /// When this status was read, for computing rates between refreshes. + pub at: Option, + /// The socket the last request went to. + pub socket: PathBuf, +} + +/// Delivers a user gesture to the owning worker without blocking the UI. +pub trait Client { + /// Queue an action from a form. + fn send(&self, command: Command); + /// An earlier action is waiting for an acknowledgement. + fn busy(&self) -> bool; +} diff --git a/crates/tsunagi-tray/src/devices.rs b/crates/tsunagi-ui/src/devices.rs similarity index 87% rename from crates/tsunagi-tray/src/devices.rs rename to crates/tsunagi-ui/src/devices.rs index 316bfef..8ea9759 100644 --- a/crates/tsunagi-tray/src/devices.rs +++ b/crates/tsunagi-ui/src/devices.rs @@ -6,13 +6,16 @@ //! the main window. use std::collections::HashMap; +mod compact; +mod exit_picker; +pub use crate::exit::name_of; +pub use exit_picker::choose_exit; -use eframe::egui; use egui_phosphor::regular as icon; use tsunagi::ipc::{DataPathReport, NetworkReport, OverlayPeerReport}; -use crate::agent::{AgentClient, Command}; +use crate::client::{Client, Command}; use crate::exit; use crate::format; use crate::stats::{Traffic, Unit}; @@ -22,7 +25,7 @@ use crate::stats::{Traffic, Unit}; const AMBER: egui::Color32 = egui::Color32::from_rgb(0xd9, 0xa4, 0x2c); /// A readable title for a network's window. -pub(crate) fn title(network: &NetworkReport) -> String { +pub fn title(network: &NetworkReport) -> String { format!("tsunagi · {}", network.name) } @@ -58,7 +61,7 @@ struct Device<'a> { /// An exit-node choice the user has to confirm: all their traffic goes through /// somebody else's device, or stops doing so. -pub(crate) struct ExitConfirm { +pub struct ExitConfirm { network_id: String, peer_id: String, name: String, @@ -69,7 +72,7 @@ pub(crate) struct ExitConfirm { } /// An exact offline claim selected for durable cleanup. -pub(crate) struct ForgetConfirm { +pub struct ForgetConfirm { network_id: String, peer: String, version: u64, @@ -79,7 +82,7 @@ pub(crate) struct ForgetConfirm { impl ExitConfirm { /// A question about stopping the exit node a network's tile shows. - pub(crate) fn stop_from_tile(network: &NetworkReport, peer_id: &str) -> Self { + pub fn stop_from_tile(network: &NetworkReport, peer_id: &str) -> Self { Self { network_id: network.network_id.clone(), peer_id: peer_id.to_string(), @@ -126,9 +129,9 @@ fn name_cell(ui: &mut egui::Ui, device: &Device<'_>) { } /// Draws the window body into its viewport. -pub(crate) fn show( +pub fn show( ctx: &egui::Context, - agent: &AgentClient, + agent: &dyn Client, unit: &mut Unit, confirmations: (&mut Option, &mut Option), network: &NetworkReport, @@ -148,6 +151,23 @@ pub(crate) fn show( // A copy of the chosen unit for the read-only rendering below. let unit = *unit; + if ctx.os() == egui::os::OperatingSystem::Android || ui.available_width() < 620.0 { + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .show(ui, |ui| { + ui.collapsing("Network details", |ui| summary(ui, network)); + format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0); + compact::roster( + ui, + network, + own_id, + traffic, + unit, + (confirm, forget_confirm), + ); + }); + return; + } summary(ui, network); ui.add_space(6.0); @@ -185,7 +205,7 @@ pub(crate) fn show( fn confirm_forget( ctx: &egui::Context, - agent: &AgentClient, + agent: &dyn Client, confirm: &mut Option, network: &str, ) { @@ -216,7 +236,7 @@ fn confirm_forget( } ui.label("The network will forget this claim and free its name and IP. A returning device can publish a new claim; this does not ban it."); ui.horizontal(|ui| { - accepted = ui.add_enabled(!agent.snapshot().busy, egui::Button::new("Forget")).clicked(); + accepted = ui.add_enabled(!agent.busy(), egui::Button::new("Forget")).clicked(); cancelled = ui.button("Cancel").clicked(); }); }); @@ -237,9 +257,9 @@ fn confirm_forget( /// /// `network_id` is the devices window the question is drawn in, or `None` for /// the main window; a question appears in the window it was asked in only. -pub(crate) fn confirm_exit( +pub fn confirm_exit( ctx: &egui::Context, - agent: &AgentClient, + agent: &dyn Client, confirm: &mut Option, network_id: Option<&str>, ) { @@ -266,14 +286,24 @@ pub(crate) fn confirm_exit( .resizable(false) .anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0]) .show(ctx, |ui| { - ui.set_max_width(380.0); + ui.set_max_width((ctx.screen_rect().width() - 40.0).clamp(160.0, 380.0)); + let phone = ctx.os() == egui::os::OperatingSystem::Android; ui.label(if pending.stop { format!("Stop using {}?", pending.name) + } else if phone { + format!( + "Route this phone’s IPv4 internet traffic through {}?", + pending.name + ) } else { format!("Use {} as exit node?", pending.name) }); ui.add_space(8.0); ui.horizontal(|ui| { + if phone { + ui.spacing_mut().interact_size = egui::vec2(104., 48.); + ui.spacing_mut().button_padding.x = 18.; + } if ui .button(if pending.stop { "Stop" } else { "Use" }) .clicked() @@ -303,7 +333,12 @@ fn summary(ui: &mut egui::Ui, network: &NetworkReport) { .spacing([12.0, 3.0]) .show(ui, |ui| { ui.weak("id"); - format::copy_field(ui, &network.network_id, &network.network_id); + let id = if ui.ctx().os() == egui::os::OperatingSystem::Android { + format::short(&network.network_id) + } else { + network.network_id.clone() + }; + format::copy_field(ui, &id, &network.network_id); ui.end_row(); ui.weak("active"); @@ -365,12 +400,12 @@ fn known_ids<'a>(network: &'a NetworkReport, own_id: &str) -> Vec<&'a str> { } /// How many other devices can be reached now, by any path. -pub(crate) fn online_count(network: &NetworkReport, own_id: &str) -> usize { +pub fn online_count(network: &NetworkReport, own_id: &str) -> usize { devices(network, own_id).iter().filter(|d| d.online).count() } /// How many other devices this network knows of, connected or not. -pub(crate) fn known_count(network: &NetworkReport, own_id: &str) -> usize { +pub fn known_count(network: &NetworkReport, own_id: &str) -> usize { known_ids(network, own_id).len() } @@ -688,22 +723,7 @@ fn device_table( |column, ui| match column { 0 => { name_cell(ui, device); - if !device.online - && !device.in_use - && let Some(version) = device.record_version - && ui - .add_enabled(network.active, egui::Button::new("Forget")) - .on_hover_text("Free this offline device's name and IPv4") - .clicked() - { - *forget_confirm = Some(ForgetConfirm { - network_id: network.network_id.clone(), - peer: device.id.into(), - version, - name: device.name(), - address: device.address.clone(), - }); - } + forget_button(ui, device, network, forget_confirm); } 1 => exit_cell(ui, device, network_id, confirm), 2 => tunnel_cell(ui, device), @@ -842,6 +862,30 @@ fn data_path_cell(ui: &mut egui::Ui, device: &Device<'_>) { }); } +fn forget_button( + ui: &mut egui::Ui, + device: &Device<'_>, + network: &NetworkReport, + confirm: &mut Option, +) { + if !device.online + && !device.in_use + && let Some(version) = device.record_version + && ui + .add_enabled(network.active, egui::Button::new("Forget")) + .on_hover_text("Free this offline device's name and IPv4") + .clicked() + { + *confirm = Some(ForgetConfirm { + network_id: network.network_id.clone(), + peer: device.id.into(), + version, + name: device.name(), + address: device.address.clone(), + }); + } +} + fn yes_no(value: bool) -> &'static str { if value { "yes" } else { "no" } } @@ -862,6 +906,109 @@ mod tests { } } + #[test] + fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() { + struct ReadOnly; + impl Client for ReadOnly { + fn send(&self, _: Command) { + panic!("reading a row issued an action"); + } + fn busy(&self) -> bool { + false + } + } + let mut network = NetworkReport { + network_id: "a".repeat(60), + name: "lab".into(), + ..Default::default() + }; + for (i, name) in [ + "alpha", + "bravo", + "charlie", + "long-hostname-that-cannot-fit-a-phone-row", + ] + .into_iter() + .enumerate() + { + let mut m = member(name, i < 2, DataPathReport::None); + m.hostname = Some(name.into()); + m.overlay_address_v4 = Some(format!("192.168.254.{}", 240 + i)); + network.members.push(m); + } + for width in [320.0, 360.0, 430.0, 870.0] { + let ctx = egui::Context::default(); + ctx.set_os(egui::os::OperatingSystem::Android); + let frame = |events| { + ctx.run( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size( + egui::Pos2::ZERO, + egui::vec2(width, 720.), + )), + events, + ..Default::default() + }, + |ctx| { + show( + ctx, + &ReadOnly, + &mut Unit::Packets, + (&mut None, &mut None), + &network, + "self", + &Traffic::default(), + ) + }, + ) + }; + let positions = |out: &egui::FullOutput, value: &str| -> Vec { + out.shapes + .iter() + .filter_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == value => { + Some(t.pos + t.galley.rect.center().to_vec2()) + } + _ => None, + }) + .collect() + }; + frame(vec![]); + let out = frame(vec![]); + let a = positions(&out, "alpha")[0]; + let b = positions(&out, "bravo")[0]; + assert!( + (15.0..=29.0).contains(&(b.y - a.y)), + "one text line per device at {width}" + ); + for i in 240..244 { + let p = positions(&out, &format!("192.168.254.{i}"))[0]; + assert!(p.x < width - 30.0, "IPv4 outside row at {width}: {p:?}"); + } + assert!(positions(&out, "Endpoint ID").is_empty()); + let click = |p: egui::Pos2| { + for pressed in [true, false] { + frame(vec![ + egui::Event::PointerMoved(p), + egui::Event::PointerButton { + pos: p, + button: egui::PointerButton::Primary, + pressed, + modifiers: Default::default(), + }, + ]); + } + frame(vec![]) + }; + let expanded = click(a); + assert_eq!(positions(&expanded, "Endpoint ID").len(), 1); + let switched = click(positions(&expanded, "bravo")[0]); + assert_eq!(positions(&switched, "Endpoint ID").len(), 1); + let closed = click(positions(&switched, "bravo")[0]); + assert!(positions(&closed, "Endpoint ID").is_empty()); + } + } + #[test] fn a_device_reached_through_another_is_online_whatever_its_tunnel_says() { // The tray used to call a device online only while its tunnel had diff --git a/crates/tsunagi-ui/src/devices/compact.rs b/crates/tsunagi-ui/src/devices/compact.rs new file mode 100644 index 0000000..d9a5144 --- /dev/null +++ b/crates/tsunagi-ui/src/devices/compact.rs @@ -0,0 +1,193 @@ +//! One line per member and one expanded detail block, with no horizontal scroller. +use super::{ + AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text, + devices, exit, forget_button, format, icon, rtt_text, tunnel_cell, +}; + +pub(super) fn roster( + ui: &mut egui::Ui, + network: &NetworkReport, + own_id: &str, + traffic: &Traffic, + unit: Unit, + (exit, forget): (&mut Option, &mut Option), +) { + let members = devices(network, own_id); + let online = members.iter().filter(|m| m.online).count(); + ui.strong(format!( + "devices ({} online / {} known)", + online, + members.len() + )); + let id = ui.make_persistent_id(("expanded device", &network.network_id)); + let mut selected = ui.data(|d| d.get_temp::(id)); + let width = ui.available_width(); + let font = egui::TextStyle::Body.resolve(ui.style()); + let measure = |s: &str| { + ui.painter() + .layout_no_wrap(s.to_owned(), font.clone(), ui.visuals().text_color()) + .size() + .x + }; + let rtt_x = width - (measure("9999 ms") + 18.0).min(width * 0.25); + let ip_x = rtt_x - (measure("255.255.255.255") + 14.0).min(width * 0.40); + let offsets = [16.0, ip_x, rtt_x]; + let size = egui::vec2(width, ui.text_style_height(&egui::TextStyle::Body) + 8.0); + ui.spacing_mut().item_spacing.y = 1.0; + let (header, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + for (x, title) in offsets.into_iter().zip(["device", "IPv4", "RTT"]) { + ui.painter().text( + header.left_center() + egui::vec2(x, 0.), + egui::Align2::LEFT_CENTER, + title, + font.clone(), + ui.visuals().weak_text_color(), + ); + } + for (index, member) in members.iter().enumerate() { + let (row, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + let response = ui.interact(row, id.with(member.id), egui::Sense::click()); + if response.clicked() { + selected = (selected.as_deref() != Some(member.id)).then(|| member.id.to_owned()); + } + let open = selected.as_deref() == Some(member.id); + if open || index % 2 == 0 { + ui.painter().rect_filled( + row, + 2.0, + if open { + ui.visuals().widgets.hovered.weak_bg_fill + } else { + ui.visuals().faint_bg_color + }, + ); + } + let dot = row.left_center() + egui::vec2(6., 0.); + if member.online { + ui.painter().circle_filled(dot, 3., exit::GOOD); + } else { + ui.painter().circle_stroke( + dot, + 3., + egui::Stroke::new(1.0_f32, ui.visuals().weak_text_color()), + ); + } + let name = member.name(); + let rtt = rtt_text(member.control_rtt_ms); + let labels = [ + name.as_str(), + member.address.as_deref().unwrap_or("—"), + rtt.as_str(), + ]; + let color = if member.online { + ui.visuals().text_color() + } else { + ui.visuals().weak_text_color() + }; + for ((x, end), label) in offsets + .into_iter() + .zip([ip_x, rtt_x, width - 13.0]) + .zip(labels) + { + let mut job = + egui::text::LayoutJob::simple_singleline(label.into(), font.clone(), color); + job.wrap.max_rows = 1; + job.wrap.max_width = (end - x - 4.0).max(0.0); + job.wrap.break_anywhere = true; + let galley = ui.painter().layout_job(job); + let origin = row.left_center() + egui::vec2(x, -galley.size().y * 0.5); + ui.painter().galley(origin, galley, color); + } + ui.painter().text( + row.right_center(), + egui::Align2::RIGHT_CENTER, + if open { + icon::CARET_DOWN + } else { + icon::CARET_RIGHT + }, + font.clone(), + ui.visuals().weak_text_color(), + ); + if open { + ui.push_id(member.id, |ui| { + details(ui, network, member, traffic, unit, exit, forget) + }); + } + } + ui.data_mut(|d| match selected { + Some(member) => d.insert_temp(id, member), + None => d.remove::(id), + }); +} + +fn details( + ui: &mut egui::Ui, + network: &NetworkReport, + member: &Device<'_>, + traffic: &Traffic, + unit: Unit, + exit: &mut Option, + forget: &mut Option, +) { + ui.horizontal_wrapped(|ui| { + ui.weak(if member.online { "online" } else { "offline" }); + if let Some(name) = &member.copy { + format::copy_field(ui, &member.name(), name); + } + if let Some(address) = &member.address { + format::copy_field(ui, address, address); + } + }); + ui.horizontal_wrapped(|ui| { + ui.weak("Endpoint ID"); + format::copy_field(ui, &format::short(member.id), member.id); + }); + let (path, _) = data_path_text(member.path, member.via_name.as_deref(), member.online); + ui.horizontal_wrapped(|ui| { + ui.label(path); + tunnel_cell(ui, member); + }); + if let Some(error) = member.data_error { + ui.colored_label(AMBER, error); + } + if let Some((taken, holder)) = &member.name_taken { + ui.colored_label(AMBER, format!("Name {taken} belongs to {holder}.")); + } + if let Some(peer) = member.overlay { + let series = traffic.peer(&network.network_id, &peer.public_key); + ui.horizontal_wrapped(|ui| { + ui.label(format!( + "TX {} · {} pkts", + format::bytes(peer.tx_bytes as f64), + peer.tx_packets + )); + ui.label(format!( + "RX {} · {} pkts", + format::bytes(peer.rx_bytes as f64), + peer.rx_packets + )); + ui.weak(format::series_rate(series, unit)); + }); + format::sparkline(ui, series, unit, 22.); + } + if (member.exit_node || member.in_use) + && ui + .button(if member.in_use { + "Stop using exit node" + } else { + "Use exit node" + }) + .clicked() + { + *exit = Some(ExitConfirm { + network_id: network.network_id.clone(), + peer_id: member.id.into(), + name: member.name(), + stop: member.in_use, + main: false, + }); + } + forget_button(ui, member, network, forget); + ui.separator(); +} diff --git a/crates/tsunagi-ui/src/devices/exit_picker.rs b/crates/tsunagi-ui/src/devices/exit_picker.rs new file mode 100644 index 0000000..d160688 --- /dev/null +++ b/crates/tsunagi-ui/src/devices/exit_picker.rs @@ -0,0 +1,340 @@ +//! The remote-exit chooser. Each radio row is one touch target, including its telemetry. +use super::{ExitConfirm, devices, rtt_text}; +use crate::exit; +use egui::{Align2, FontId, Pos2, Rect, Sense, Ui}; +use tsunagi::ipc::{DataPathReport, NetworkReport}; + +/// Draw the selectable exits for one network and return a choice for confirmation. +pub fn choose_exit(ui: &mut Ui, network: &NetworkReport, own: &str) -> Option { + ui.heading(&network.name); + if let Some(rules) = &network.exit.client_rules + && !rules.ok + { + ui.colored_label(exit::LOUD, &rules.detail); + } + let width = ui.available_width(); + let (header, _) = ui.allocate_exact_size(egui::vec2(width, 22.), Sense::hover()); + let columns = Columns::new(header); + let muted = ui.visuals().weak_text_color(); + for (x, label) in [ + (columns.name, "Exit node"), + (columns.rtt, "RTT"), + (columns.path, "Path"), + ] { + ui.painter().text( + egui::pos2(x, header.center().y), + Align2::LEFT_CENTER, + label, + egui::TextStyle::Small.resolve(ui.style()), + muted, + ); + } + let current = network.exit.via.as_deref(); + let mut choice = None; + let local = Row { + peer: None, + name: "No exit node", + address: None, + rtt: None, + path: "Local", + transport: None, + selected: current.is_none(), + }; + if local.draw(ui, &network.network_id) + && let Some(id) = current + { + choice = Some(ExitConfirm::stop_from_tile(network, id)); + } + let mut candidates = devices(network, own); + candidates.retain(|d| d.exit_node || d.in_use); + candidates.sort_by_key(|d| !d.in_use); + if let Some(id) = current + && !candidates.iter().any(|d| d.id == id) + { + Row { + peer: Some(id), + name: &exit::name_of(network, id), + address: None, + rtt: None, + path: "Offline", + transport: None, + selected: true, + } + .draw(ui, &network.network_id); + } + for candidate in &candidates { + let name = candidate.name(); + let relayed; + let (path, transport) = if !candidate.online { + ("Offline", None) + } else if candidate.in_use && !network.exit.via_online || candidate.data_error.is_some() { + ("Unavailable", None) + } else { + match candidate.path { + Some(DataPathReport::Direct { transport }) => ("Direct", Some(transport.as_str())), + Some(DataPathReport::Relayed { hops, .. }) => { + relayed = format!("{hops} hops"); + ("Relayed", Some(relayed.as_str())) + } + _ => ("Connecting", None), + } + }; + let row = Row { + peer: Some(candidate.id), + name: &name, + address: candidate.address.as_deref(), + rtt: candidate.control_rtt_ms, + path, + transport, + selected: candidate.in_use, + }; + if row.draw(ui, &network.network_id) && !candidate.in_use { + choice = Some(ExitConfirm { + network_id: network.network_id.clone(), + peer_id: candidate.id.into(), + name, + stop: false, + main: true, + }); + } + } + if !candidates.iter().any(|d| d.exit_node) { + ui.weak("No connected peers offer an exit node."); + } + choice +} + +struct Columns { + name: f32, + rtt: f32, + path: f32, +} +impl Columns { + fn new(rect: Rect) -> Self { + let path = rect.right() - (rect.width() * 0.24).clamp(66., 110.); + Self { + name: rect.left() + 31., + rtt: path - 61., + path, + } + } +} + +struct Row<'a> { + peer: Option<&'a str>, + name: &'a str, + address: Option<&'a str>, + rtt: Option, + path: &'a str, + transport: Option<&'a str>, + selected: bool, +} +impl Row<'_> { + fn draw(&self, ui: &mut Ui, network: &str) -> bool { + let font = egui::TextStyle::Body.resolve(ui.style()); + let small = egui::TextStyle::Small.resolve(ui.style()); + let height = (font.size + small.size + 18.).max(52.); + let (rect, _) = + ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover()); + let id = ui.make_persistent_id(("exit choice", network, self.peer)); + let response = ui.interact(rect, id, Sense::click()); + response.widget_info(|| { + egui::WidgetInfo::selected( + egui::WidgetType::RadioButton, + true, + self.selected, + self.name, + ) + }); + let visuals = ui.style().interact_selectable(&response, self.selected); + let painter = ui.painter(); + if self.selected || response.hovered() || response.has_focus() { + painter.rect_filled(rect, 3., visuals.weak_bg_fill); + } + painter.hline( + rect.x_range(), + rect.bottom(), + ui.visuals().widgets.noninteractive.bg_stroke, + ); + let dot = rect.left_center() + egui::vec2(15., 0.); + painter.circle_stroke(dot, 6., visuals.fg_stroke); + if self.selected { + painter.circle_filled(dot, 3., visuals.text_color()); + } + let c = Columns::new(rect); + let center = rect.center().y; + let muted = ui.visuals().weak_text_color(); + let line = |x: f32, end: f32, y: f32, value: &str, font: &FontId, color| { + let mut job = + egui::text::LayoutJob::simple_singleline(value.into(), font.clone(), color); + job.wrap.max_rows = 1; + job.wrap.break_anywhere = true; + job.wrap.max_width = (end - x - 5.).max(0.); + let text = painter.layout_job(job); + painter.galley(Pos2::new(x, y - text.size().y * 0.5), text, color); + }; + let pair = |x, end, label, detail: Option<&str>| { + let y = if detail.is_some() { + center - small.size * 0.55 + } else { + center + }; + line(x, end, y, label, &font, visuals.text_color()); + if let Some(detail) = detail { + line(x, end, center + font.size * 0.65, detail, &small, muted); + } + }; + pair(c.name, c.rtt, self.name, self.address); + line( + c.rtt, + c.path, + center, + &rtt_text(self.rtt), + &font, + visuals.text_color(), + ); + pair(c.path, rect.right(), self.path, self.transport); + response.clicked() + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::choose_exit; + use egui::{CentralPanel, Context, Event, PointerButton, Pos2, RawInput, Rect, Shape}; + use tsunagi::ipc::{DataPathReport, ExitReport, MemberReport, NetworkReport, PeerReport}; + + #[test] + fn exit_table_fits_phone_widths_and_the_whole_row_selects_the_exact_peer() { + let mut network = NetworkReport { + name: "lab".into(), + network_id: "network-id".into(), + exit: ExitReport { + via: Some("old-id".into()), + ..Default::default() + }, + ..Default::default() + }; + for (id, name, offer) in [ + ("new-id", "west", true), + ("self", "my-phone", true), + ("ordinary", "worker", false), + ] { + network.peers.push(PeerReport { + endpoint_id: id.into(), + hostname: Some(name.into()), + rtt_ms: Some(37), + path: DataPathReport::Direct { + transport: "wg".into(), + }, + exit_node: offer, + ..Default::default() + }); + } + network.members.push(MemberReport { + endpoint_id: "old-id".into(), + hostname: Some("east".into()), + ..Default::default() + }); + network.members.push(MemberReport { + endpoint_id: "new-id".into(), + hostname: Some("west".into()), + overlay_address_v4: Some("10.9.0.4".into()), + ..Default::default() + }); + for width in [320., 430.] { + let ctx = Context::default(); + let frame = |events| { + let mut chosen = None; + let out = ctx.run( + RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(width, 640.))), + events, + ..Default::default() + }, + |ctx| { + CentralPanel::default().show(ctx, |ui| { + chosen = choose_exit(ui, &network, "self"); + }); + }, + ); + (out, chosen) + }; + let (out, initial) = frame(Vec::new()); + assert!(initial.is_none()); + let labels: Vec<_> = out + .shapes + .iter() + .filter_map(|s| match &s.shape { + Shape::Text(t) => Some((t.galley.text(), t.visual_bounding_rect())), + _ => None, + }) + .collect(); + for text in [ + "No exit node", + "east", + "west", + "10.9.0.4", + "37 ms", + "Direct", + "wg", + "Offline", + ] { + assert!( + labels.iter().any(|(label, _)| *label == text), + "missing {text}" + ); + } + assert!( + !labels + .iter() + .any(|(label, _)| matches!(*label, "my-phone" | "worker")) + ); + assert!( + labels + .iter() + .all(|(_, r)| r.left() >= 0. && r.right() <= width + 1.) + ); + let y = |name| { + labels + .iter() + .find(|(label, _)| *label == name) + .unwrap() + .1 + .center() + .y + }; + assert!(y("west") - y("east") >= 44.); + let tap = |name| { + let pos = egui::pos2(width - 14., y(name) + 8.0); + frame(vec![ + Event::PointerMoved(pos), + Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed: true, + modifiers: Default::default(), + }, + ]); + frame(vec![Event::PointerButton { + pos, + button: PointerButton::Primary, + pressed: false, + modifiers: Default::default(), + }]) + .1 + }; + assert!(tap("east").is_none()); + let select = tap("west").unwrap(); + assert!(!select.stop); + assert_eq!( + (select.network_id.as_str(), select.peer_id.as_str()), + ("network-id", "new-id") + ); + let stop = tap("No exit node").unwrap(); + assert!(stop.stop); + assert_eq!(stop.peer_id, "old-id"); + } + } +} diff --git a/crates/tsunagi-tray/src/exit.rs b/crates/tsunagi-ui/src/exit.rs similarity index 98% rename from crates/tsunagi-tray/src/exit.rs rename to crates/tsunagi-ui/src/exit.rs index 45314ed..4234027 100644 --- a/crates/tsunagi-tray/src/exit.rs +++ b/crates/tsunagi-ui/src/exit.rs @@ -1,8 +1,6 @@ //! Exit nodes as the windows show them: what to call one, and what is wrong //! with the ones in play. -use eframe::egui; - use tsunagi::ipc::NetworkReport; use crate::format; @@ -30,7 +28,7 @@ pub(crate) struct Warning { } /// What to call a device in a network, even while it is away. -pub(crate) fn name_of(network: &NetworkReport, id: &str) -> String { +pub fn name_of(network: &NetworkReport, id: &str) -> String { network .peers .iter() diff --git a/crates/tsunagi-tray/src/format.rs b/crates/tsunagi-ui/src/format.rs similarity index 92% rename from crates/tsunagi-tray/src/format.rs rename to crates/tsunagi-ui/src/format.rs index 5b9b191..cdcf8e5 100644 --- a/crates/tsunagi-tray/src/format.rs +++ b/crates/tsunagi-ui/src/format.rs @@ -3,8 +3,6 @@ use std::time::{Duration, Instant}; -use eframe::egui; - use crate::stats::{Series, Unit}; /// Sparkline accent. @@ -15,7 +13,7 @@ const COPIED_GREEN: egui::Color32 = egui::Color32::from_rgb(0x3c, 0xb0, 0x4a); const FLASH: Duration = Duration::from_secs(1); /// A short, readable prefix of a long identifier (char-safe, no panic). -pub(crate) fn short(id: &str) -> String { +pub fn short(id: &str) -> String { const KEEP: usize = 12; if id.chars().count() <= KEEP { id.to_string() @@ -25,7 +23,7 @@ pub(crate) fn short(id: &str) -> String { } /// A byte count in binary units. -pub(crate) fn bytes(n: f64) -> String { +pub fn bytes(n: f64) -> String { const UNITS: [&str; 5] = ["B", "kB", "MB", "GB", "TB"]; let mut value = n.max(0.0); let mut unit = 0; @@ -41,7 +39,7 @@ pub(crate) fn bytes(n: f64) -> String { } /// A rate in the chosen unit, per second. -pub(crate) fn rate(value: f32, unit: Unit) -> String { +pub fn rate(value: f32, unit: Unit) -> String { match unit { Unit::Packets => { if value >= 1000.0 { @@ -55,14 +53,14 @@ pub(crate) fn rate(value: f32, unit: Unit) -> String { } /// The current rate of a series as a string, or a dash when unsampled. -pub(crate) fn series_rate(series: Option<&Series>, unit: Unit) -> String { +pub fn series_rate(series: Option<&Series>, unit: Unit) -> String { series.map_or_else(|| "—".to_string(), |s| rate(s.rate(unit), unit)) } /// A label whose text is `display` and which copies `value` to the clipboard /// when clicked. Feedback is a green flash that fades back over a second — the /// text itself never changes, so a dense table does not reflow on a copy. -pub(crate) fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) { +pub fn copy_field(ui: &mut egui::Ui, display: &str, value: &str) { let id = ui.make_persistent_id(("copy", value, display)); let copied_at: Option = ui.memory(|memory| memory.data.get_temp(id)); // 1.0 right after the click, fading to 0.0 a second later. @@ -103,7 +101,7 @@ fn lerp_color(a: egui::Color32, b: egui::Color32, t: f32) -> egui::Color32 { /// A fixed-height sparkline of a series' recent rate, with the peak (top-left) /// and current value (bottom-right) overlaid. The space is always reserved — /// even with no data — so the layout never jumps when data arrives. -pub(crate) fn sparkline(ui: &mut egui::Ui, series: Option<&Series>, unit: Unit, height: f32) { +pub fn sparkline(ui: &mut egui::Ui, series: Option<&Series>, unit: Unit, height: f32) { let width = ui.available_width(); let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover()); let painter = ui.painter_at(rect); diff --git a/crates/tsunagi-ui/src/home.rs b/crates/tsunagi-ui/src/home.rs new file mode 100644 index 0000000..f56fb7e --- /dev/null +++ b/crates/tsunagi-ui/src/home.rs @@ -0,0 +1,412 @@ +//! Shared compact network tiles, device header and join form. +use crate::{ + client::{Client, Command}, + devices, exit, format, + stats::{Traffic, Unit}, +}; +use egui_phosphor::regular as icon; +use std::collections::BTreeSet; +use tsunagi::ipc::{NetworkReport, StatusReport}; +use zeroize::{Zeroize, Zeroizing}; + +const BAD: egui::Color32 = egui::Color32::from_rgb(0xd0, 0x4a, 0x3c); +/// A neutral, not-garish red for the Leave button. +const LEAVE_RED: egui::Color32 = egui::Color32::from_rgb(0xa8, 0x3a, 0x3a); + +/// Join form fields. +#[derive(Default)] +pub struct JoinForm { + /// Visible network name. + pub name: String, + /// User-entered network secret. + pub secret: Zeroizing, +} + +/// Local UI state kept across frames. +pub struct UiState { + /// Join form draft. + pub join: JoinForm, + /// Whether rates and sparklines are shown in packets or bytes. + pub unit: Unit, + /// An in-progress hostname edit (`None` when not editing). + pub host_edit: Option, + /// Network ids whose devices window is open. + pub open_devices: BTreeSet, + /// Per-network VIP drafts. + pub vip_windows: std::collections::BTreeMap, + /// Whether the About window is open. + pub about_open: bool, + /// An exit-node choice waiting for the user to confirm it. + pub exit_confirm: Option, + /// A selected offline claim waiting for cleanup confirmation. + pub forget_confirm: Option, +} + +impl Default for UiState { + fn default() -> Self { + Self { + join: JoinForm::default(), + unit: Unit::Packets, + host_edit: None, + open_devices: BTreeSet::new(), + vip_windows: Default::default(), + about_open: false, + exit_confirm: None, + forget_confirm: None, + } + } +} + +/// The device header: id (with a copy button) and an editable hostname. +pub fn draw_header( + ui: &mut egui::Ui, + agent: &dyn Client, + state: &mut UiState, + report: &StatusReport, +) { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.weak("device"); + // Clicking the shortened id copies the full one. + format::copy_field(ui, &format::short(&report.endpoint_id), &report.endpoint_id); + }); + + ui.horizontal(|ui| { + ui.weak("host"); + match &mut state.host_edit { + None => { + ui.label(&report.hostname); + if ui + .small_button(icon::PENCIL_SIMPLE) + .on_hover_text("rename") + .clicked() + { + state.host_edit = Some(report.hostname.clone()); + } + } + Some(buffer) => { + let response = ui.add(egui::TextEdit::singleline(buffer).desired_width(150.0)); + let submit = (response.lost_focus() + && ui.input(|i| i.key_pressed(egui::Key::Enter))) + || ui.small_button(icon::CHECK).on_hover_text("save").clicked(); + if submit { + agent.send(Command::SetHostname(buffer.trim().to_string())); + state.host_edit = None; + } else if ui.small_button(icon::X).on_hover_text("cancel").clicked() { + state.host_edit = None; + } + } + } + }); + + if !report.cache_healthy { + ui.colored_label( + egui::Color32::from_rgb(0xd9, 0x9a, 0x00), + "cache unavailable", + ); + } +} + +/// One compact network tile. +pub fn draw_network( + ui: &mut egui::Ui, + agent: &dyn Client, + state: &mut UiState, + traffic: &Traffic, + network: &NetworkReport, + report: &StatusReport, + offer_exit: bool, +) -> bool { + let mut pick_exit = false; + ui.add_space(6.0); + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.horizontal(|ui| { + format::copy_field(ui, network.name.as_str(), &network.name); + if ui.button("VIP").clicked(){state.vip_windows.entry(network.network_id.clone()).or_default();} + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let leave = + egui::Button::new(egui::RichText::new("Leave").color(egui::Color32::WHITE)) + .fill(LEAVE_RED); + if ui.add(leave).clicked() { + agent.send(Command::Leave { + network_id: network.network_id.clone(), + }); + } + }); + }); + + let address = network.overlay.as_ref().and_then(|o| o.address.as_ref()); + let series = traffic.network(&network.network_id); + + egui::Grid::new(("net", &network.network_id)) + .num_columns(2) + .spacing([10.0, 3.0]) + .show(ui, |ui| { + ui.weak("id"); + format::copy_field(ui, &format::short(&network.network_id), &network.network_id); + ui.end_row(); + + if let Some(range) = &network.range { + ui.weak("range"); + format::copy_field(ui, range, range); + ui.end_row(); + } + if let Some(address) = address { + ui.weak("addr"); + format::copy_field(ui, address, address); + ui.end_row(); + } + ui.weak("peers"); + ui.label(format!( + "{} online · {} known", + devices::online_count(network, &report.endpoint_id), + devices::known_count(network, &report.endpoint_id) + )); + ui.end_row(); + }); + + draw_protocols(ui, agent, network, &report.available_protocols); + + format::sparkline(ui, series, state.unit, 34.0); + + if !network.range_conflicts.is_empty() { + ui.colored_label(BAD, "Stopped: overlapping network ranges"); + for conflict in &network.range_conflicts { + ui.label(format!("{} ({}) uses {}", conflict.name, conflict.network_id, conflict.range)); + } + ui.label("Switching suspends these networks until this network stops, then resumes them automatically."); + if network.auto_start { ui.weak("This network will resume automatically when its range is free."); } + } + ui.horizontal_wrapped(|ui| { + if !network.active && !network.range_conflicts.is_empty() { + if ui.button("Switch to this network").clicked() { + agent.send(Command::SetActive { network_id: network.network_id.clone(), active: true }); + } + if network.auto_start && ui.button("Keep stopped").clicked() { + agent.send(Command::SetActive { network_id: network.network_id.clone(), active: false }); + } + } else { + let mut active = network.active; + if ui.checkbox(&mut active, "active").changed() { + agent.send(Command::SetActive { + network_id: network.network_id.clone(), + active, + }); + } + } + let mut broadcast = network.broadcast; + if ui.checkbox(&mut broadcast, "broadcast").changed() { + agent.send(Command::SetBroadcast { + network_id: network.network_id.clone(), + enabled: broadcast, + }); + } + if !offer_exit && ui.button("Exit node…").clicked() { pick_exit = true; } + let mut offering = network.exit.offering; + if offer_exit && ui + .checkbox(&mut offering, "exit node") + .on_hover_text( + "let other members send all their internet traffic through this \ + device, which can see it", + ) + .changed() + { + agent.send(Command::SetExitOffer { + network_id: network.network_id.clone(), + enabled: offering, + }); + } + }); + ui.horizontal(|ui| { + // In the bottom left corner while this device sends its traffic through + // somebody: green while that works, red while it does not. + if let Some(via) = &network.exit.via { + let color = if network.exit.via_online { + exit::GOOD + } else { + exit::LOUD + }; + let response = ui + .add( + egui::Label::new( + egui::RichText::new(icon::SIGN_OUT).size(18.0).color(color), + ) + .sense(egui::Sense::click()), + ) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .on_hover_text(format!( + "exit node: {} — click to stop", + exit::name_of(network, via) + )); + if response.clicked() { + state.exit_confirm = Some(devices::ExitConfirm::stop_from_tile(network, via)); + } + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button("Show devices").clicked() { + state.open_devices.insert(network.network_id.clone()); + } + if ui + .button(format!("{} Copy secret", icon::COPY)) + .on_hover_text("copy this network's secret to the clipboard") + .clicked() + { + agent.send(Command::CopySecret { + network_id: network.network_id.clone(), + }); + } + }); + }); + for warning in exit::warnings(network) { + draw_exit_warning(ui, &warning); + } + }); + pick_exit +} + +fn draw_protocols( + ui: &mut egui::Ui, + agent: &dyn Client, + network: &NetworkReport, + available: &[tsunagi::ipc::ProtocolReport], +) { + let summary = if network.protocols.is_empty() { + "none".into() + } else { + network.protocols.join(", ") + }; + egui::CollapsingHeader::new(format!("data transports {summary}")) + .id_salt(("protocols", &network.network_id)) + .show(ui, |ui| { + ui.weak("Preference order; changes apply immediately and are saved."); + let mut selected = network.protocols.clone(); + let mut changed = false; + ui.add_enabled_ui(!agent.busy(), |ui| { + // Enabled items follow the user's preference; unchecked items + // follow the agent's catalog. The worker refreshes after edits. + let ordered: Vec<_> = network + .protocols + .iter() + .filter_map(|name| available.iter().find(|p| &p.name == name)) + .chain( + available + .iter() + .filter(|p| !network.protocols.contains(&p.name)), + ) + .collect(); + for protocol in ordered { + ui.horizontal(|ui| { + let mut on = selected.contains(&protocol.name); + if ui.checkbox(&mut on, &protocol.name).changed() { + if on { + selected.push(protocol.name.clone()); + } else { + selected.retain(|p| p != &protocol.name); + } + changed = true; + } + if let Some(index) = selected.iter().position(|p| p == &protocol.name) { + if ui + .add_enabled(index > 0, egui::Button::new(icon::ARROW_UP)) + .on_hover_text("prefer earlier") + .clicked() + { + selected.swap(index, index - 1); + changed = true; + } + if ui + .add_enabled( + index + 1 < selected.len(), + egui::Button::new(icon::ARROW_DOWN), + ) + .on_hover_text("prefer later") + .clicked() + { + selected.swap(index, index + 1); + changed = true; + } + } + }); + ui.indent(("description", &network.network_id, &protocol.name), |ui| { + ui.weak(&protocol.summary); + }); + } + }); + if selected.is_empty() { + ui.weak("Control only; no IP traffic in this network."); + } + if changed { + agent.send(Command::SetProtocols { + network_id: network.network_id.clone(), + protocols: selected, + }); + } + }); +} + +/// A prominent line about an exit node. One that carries a command copies it +/// when clicked. +fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) { + let text = egui::RichText::new(format!("{} {}", icon::WARNING, warning.text)) + .color(exit::LOUD) + .strong(); + let label = egui::Label::new(text).wrap(); + match warning.copy { + Some(command) => { + let response = ui + .add(label.sense(egui::Sense::click())) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .on_hover_text("click to copy the command"); + if response.clicked() { + ui.ctx().copy_text(command.to_owned()); + } + } + None => { + ui.add(label); + } + } +} + +/// The join form: aligned name and secret, a generate button, and Join. +pub fn draw_join(ui: &mut egui::Ui, agent: &dyn Client, join: &mut JoinForm) { + const INPUT_WIDTH: f32 = 208.0; + ui.label("Join or create a network"); + egui::Grid::new("join") + .num_columns(2) + .spacing([8.0, 6.0]) + .show(ui, |ui| { + ui.label("name"); + ui.add(egui::TextEdit::singleline(&mut join.name).desired_width(INPUT_WIDTH)); + ui.end_row(); + + ui.label("secret"); + ui.horizontal(|ui| { + ui.add( + egui::TextEdit::singleline(&mut *join.secret) + .id("join-secret".into()) + .desired_width(INPUT_WIDTH - 26.0) + .password(true), + ); + if ui + .button(icon::SHUFFLE) + .on_hover_text("Generate a new random secret") + .clicked() + { + join.secret = tsunagi::identity::NetworkSecret::generate().encode(); + } + }); + ui.end_row(); + }); + + let ready = !join.name.trim().is_empty() && !join.secret.trim().is_empty(); + if ui + .add_enabled(ready, egui::Button::new("Join / create")) + .clicked() + { + agent.send(Command::Join { + name: join.name.trim().to_string(), + secret: Zeroizing::new(join.secret.trim().to_owned()), + }); + join.secret.zeroize(); + } +} diff --git a/crates/tsunagi-ui/src/lib.rs b/crates/tsunagi-ui/src/lib.rs new file mode 100644 index 0000000..3c58f0e --- /dev/null +++ b/crates/tsunagi-ui/src/lib.rs @@ -0,0 +1,19 @@ +//! Shared presentation for the egui clients. +pub mod about; +pub mod client; +pub mod devices; +mod exit; +pub mod format; +pub mod home; +pub mod listeners; +pub mod stats; +mod table; +pub mod vip; +mod vip_status; + +/// Install the tray's regular Phosphor glyphs alongside egui's standard fonts. +pub fn app_fonts() -> egui::FontDefinitions { + let mut fonts = egui::FontDefinitions::default(); + egui_phosphor::add_to_fonts(&mut fonts, egui_phosphor::Variant::Regular); + fonts +} diff --git a/crates/tsunagi-ui/src/listeners.rs b/crates/tsunagi-ui/src/listeners.rs new file mode 100644 index 0000000..991452d --- /dev/null +++ b/crates/tsunagi-ui/src/listeners.rs @@ -0,0 +1,94 @@ +//! Editor for the listener and backend portion of a shared VIP draft. +use tsunagi::vip::{Backend, Listener, Protocol, VipConfig}; + +/// Edit local draft fields. Callers own validation, signed revision and Save. +pub fn edit(ui: &mut egui::Ui, config: &mut VipConfig, members: &[(String, String)]) { + let mut remove = None; + for (index, listener) in config.listeners.iter_mut().enumerate() { + ui.push_id(&listener.id, |ui| { + egui::Frame::group(ui.style()).show(ui, |ui| { + ui.horizontal_wrapped(|ui| { + egui::ComboBox::from_id_salt("protocol") + .selected_text(listener.protocol.to_string()) + .show_ui(ui, |ui| { + ui.selectable_value(&mut listener.protocol, Protocol::Tcp, "TCP"); + ui.selectable_value(&mut listener.protocol, Protocol::Udp, "UDP"); + }); + port_field(ui, "Port", &mut listener.port); + if ui.button("Remove listener").clicked() { + remove = Some(index); + } + }); + if listener.protocol == Protocol::Tcp { + ui.checkbox(&mut listener.port_check, "Active TCP port checks"); + } else { + ui.weak("UDP health uses path probes and explicit port errors."); + } + ui.collapsing("Checks and flow expiry", |ui| { + egui::Grid::new("settings").show(ui, |ui| { + macro_rules! setting { + ($label:literal, $value:ident, $range:expr) => { + ui.label($label); + ui.add(egui::DragValue::new(&mut listener.$value).range($range)); + ui.end_row(); + }; + } + setting!("Check interval, ms", check_interval_ms, 250..=3_600_000); + setting!("Check timeout, ms", check_timeout_ms, 100..=60_000); + setting!("Failures before exclusion", failure_threshold, 1..=255); + setting!("Successes before recovery", recovery_threshold, 1..=255); + setting!("Flow idle timeout, seconds", idle_timeout_secs, 1..=604800); + }); + }); + let mut remove_backend = None; + for (i, backend) in listener.backends.iter_mut().enumerate() { + ui.push_id(i, |ui| { + let width = ui.available_width().min(240.0); + ui.horizontal_wrapped(|ui| { + let selected = members + .iter() + .find(|(id, _)| id == &backend.peer) + .map(|(_, label)| label.to_owned()) + .unwrap_or_else(|| crate::format::short(&backend.peer)); + egui::ComboBox::from_id_salt("node") + .width(width) + .truncate() + .selected_text(selected) + .show_ui(ui, |ui| { + for (id, label) in members { + ui.selectable_value(&mut backend.peer, id.clone(), label); + } + }); + port_field(ui, "Target port", &mut backend.port); + if ui.button("Remove").clicked() { + remove_backend = Some(i); + } + }); + }); + } + if let Some(i) = remove_backend { + listener.backends.remove(i); + } + if ui.button("+ Backend").clicked() { + listener.backends.push(Backend { + peer: members + .first() + .map(|(id, _)| id.clone()) + .unwrap_or_default(), + port: listener.port, + }); + } + }) + }); + } + if let Some(i) = remove { + config.listeners.remove(i); + } + if ui.button("+ Listener").clicked() { + config.listeners.push(Listener::new(Protocol::Tcp, 443)); + } +} +fn port_field(ui: &mut egui::Ui, label: &str, value: &mut u16) { + ui.label(label); + ui.add(egui::DragValue::new(value).range(1..=65535)); +} diff --git a/crates/tsunagi-tray/src/stats.rs b/crates/tsunagi-ui/src/stats.rs similarity index 83% rename from crates/tsunagi-tray/src/stats.rs rename to crates/tsunagi-ui/src/stats.rs index f9ce5c3..49eaf5f 100644 --- a/crates/tsunagi-tray/src/stats.rs +++ b/crates/tsunagi-ui/src/stats.rs @@ -16,7 +16,7 @@ const HISTORY: usize = 60; /// Which quantity a rate or history is of. #[derive(Clone, Copy, PartialEq, Eq)] -pub(crate) enum Unit { +pub enum Unit { /// Packets per second. Packets, /// Bytes per second. @@ -25,7 +25,7 @@ pub(crate) enum Unit { /// One series' rolling packet and byte rates. #[derive(Default)] -pub(crate) struct Series { +pub struct Series { last: Option<(Instant, Counters)>, packets_rate: f32, bytes_rate: f32, @@ -35,7 +35,7 @@ pub(crate) struct Series { impl Series { /// Samples a single cumulative counter pair (VIP histories own their lifetime). - pub(crate) fn sample(&mut self, now: Instant, packets: u64, bytes: u64) { + pub fn sample(&mut self, now: Instant, packets: u64, bytes: u64) { self.sample_peer( now, Counters { @@ -83,7 +83,7 @@ impl Series { } /// The current rate in the chosen unit. - pub(crate) fn rate(&self, unit: Unit) -> f32 { + pub fn rate(&self, unit: Unit) -> f32 { match unit { Unit::Packets => self.packets_rate, Unit::Bytes => self.bytes_rate, @@ -91,7 +91,7 @@ impl Series { } /// The rolling history in the chosen unit. - pub(crate) fn history(&self, unit: Unit) -> &VecDeque { + pub fn history(&self, unit: Unit) -> &VecDeque { match unit { Unit::Packets => &self.packets_history, Unit::Bytes => &self.bytes_history, @@ -107,12 +107,18 @@ fn push(history: &mut VecDeque, value: f32) { } #[derive(Clone, Copy)] -struct Counters { - epoch: u64, - tx_packets: u64, - rx_packets: u64, - tx_bytes: u64, - rx_bytes: u64, +/// Cumulative tunnel counters in one peer epoch. +pub struct Counters { + /// Counter reset generation. + pub epoch: u64, + /// Sent packets. + pub tx_packets: u64, + /// Received packets. + pub rx_packets: u64, + /// Sent bytes. + pub tx_bytes: u64, + /// Received bytes. + pub rx_bytes: u64, } impl From<&OverlayPeerReport> for Counters { @@ -129,32 +135,53 @@ impl From<&OverlayPeerReport> for Counters { /// All traffic series, keyed by a stable string. #[derive(Default)] -pub(crate) struct Traffic { +pub struct Traffic { series: HashMap, } impl Traffic { /// Folds a fresh snapshot into the rates. Call once per new generation. - pub(crate) fn observe(&mut self, report: &StatusReport, now: Instant) { + pub fn observe(&mut self, report: &StatusReport, now: Instant) { + self.observe_peers( + report.networks.iter().filter_map(|network| { + Some(( + network.network_id.as_str(), + network + .overlay + .as_ref()? + .peers + .iter() + .map(|p| (p.public_key.as_str(), Counters::from(p))), + )) + }), + now, + ); + } + + /// Sample live per-peer counters from either an in-process agent or IPC. + pub fn observe_peers<'a, I>( + &mut self, + networks: impl IntoIterator, + now: Instant, + ) where + I: IntoIterator, + { let mut active = HashSet::new(); - for network in &report.networks { - let Some(overlay) = &network.overlay else { - continue; - }; + for (network, peers) in networks { let (mut packets_rate, mut bytes_rate) = (0.0, 0.0); - for peer in &overlay.peers { - let key = peer_key(&network.network_id, &peer.public_key); + for (peer, counters) in peers { + let key = peer_key(network, peer); // Duplicate rows are not additional traffic. if !active.insert(key.clone()) { continue; } let series = self.series.entry(key).or_default(); - series.sample_peer(now, peer.into()); + series.sample_peer(now, counters); packets_rate += series.rate(Unit::Packets); bytes_rate += series.rate(Unit::Bytes); } // Sum rates, not cumulative counters of a changing set of peers. - let key = net_key(&network.network_id); + let key = net_key(network); active.insert(key.clone()); self.series .entry(key) @@ -165,12 +192,12 @@ impl Traffic { } /// The network-total series, if sampled. - pub(crate) fn network(&self, network_id: &str) -> Option<&Series> { + pub fn network(&self, network_id: &str) -> Option<&Series> { self.series.get(&net_key(network_id)) } /// One peer's series, if sampled. - pub(crate) fn peer(&self, network_id: &str, public_key: &str) -> Option<&Series> { + pub fn peer(&self, network_id: &str, public_key: &str) -> Option<&Series> { self.series.get(&peer_key(network_id, public_key)) } } diff --git a/crates/tsunagi-tray/src/table.rs b/crates/tsunagi-ui/src/table.rs similarity index 99% rename from crates/tsunagi-tray/src/table.rs rename to crates/tsunagi-ui/src/table.rs index 625caea..e4b145d 100644 --- a/crates/tsunagi-tray/src/table.rs +++ b/crates/tsunagi-ui/src/table.rs @@ -1,6 +1,5 @@ //! Fixed row geometry for dense live tables. Children cannot resize a row or //! paint into its neighbours; the enclosing scroll area owns overflow. -use eframe::egui; pub(crate) const GAP: f32 = 10.0; diff --git a/crates/tsunagi-tray/src/vip.rs b/crates/tsunagi-ui/src/vip.rs similarity index 81% rename from crates/tsunagi-tray/src/vip.rs rename to crates/tsunagi-ui/src/vip.rs index 9c77981..854b108 100644 --- a/crates/tsunagi-tray/src/vip.rs +++ b/crates/tsunagi-ui/src/vip.rs @@ -1,9 +1,10 @@ //! Per-network VIP editor. Drafts never issue commands until Save is pressed. -use crate::agent::{AgentClient, Command, Snapshot}; +use crate::client::{Client, Command, Snapshot}; use crate::vip_status; -use eframe::egui; use tsunagi::ipc::NetworkReport; -use tsunagi::vip::{Backend, Listener, Protocol, VipConfig}; +use tsunagi::vip::VipConfig; +#[cfg(test)] +use tsunagi::vip::{Listener, Protocol}; #[derive(Clone)] struct Draft { config: VipConfig, @@ -25,7 +26,8 @@ impl Draft { } } #[derive(Default)] -pub(crate) struct Window { +/// A network’s edit draft, selection and traffic history. +pub struct Window { draft: Option, pending: Option, error: Option, @@ -37,28 +39,30 @@ pub(crate) struct Window { acknowledged_generation: Option, } impl Window { + /// Ask whether to discard an outstanding draft. pub fn request_close(&mut self) { self.close_question = true; self.close_after_save = true; } + /// Whether closing needs confirmation. pub fn dirty(&self) -> bool { self.draft.as_ref().is_some_and(Draft::dirty) || self.pending.is_some() } } -fn peer_name<'a>(n: &'a NetworkReport, id: &'a str) -> &'a str { - n.members - .iter() - .find(|m| m.endpoint_id == id) - .and_then(|m| m.hostname.as_deref()) - .unwrap_or(id) -} -pub(crate) fn show( +/// Render the editor and overview. Returns true when its view can close. +pub fn show( ctx: &egui::Context, - agent: &AgentClient, + agent: &dyn Client, state: &mut Window, n: &NetworkReport, snapshot: &Snapshot, ) -> bool { + if state.generation == 0 + && state.draft.is_none() + && let [vip] = n.vips.as_slice() + { + state.draft = Some(Draft::new(vip.config.clone(), Some(vip.revision.clone()))); + } if state.generation != snapshot.generation { state.generation = snapshot.generation; if let Some(at) = snapshot.at { @@ -92,7 +96,7 @@ pub(crate) fn show( ui.heading(format!("VIP · {}", n.name)); ui.weak("Configuration is shared with every member. Changes take effect only after Save."); if state.close_question { - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { ui.label("Unsaved changes."); if ui .add_enabled( @@ -172,7 +176,7 @@ pub(crate) fn show( ); } let busy = state.pending.is_some(); - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { let valid = draft.config.validate(&tsunagi::Limits::default()); if !n.active { ui.weak("Start the network to save changes."); @@ -229,7 +233,7 @@ pub(crate) fn show( .show(ui, |ui| { if state.configure { ui.add_enabled_ui(!busy, |ui| { - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { ui.label("Name"); ui.add( egui::TextEdit::singleline(&mut draft.config.name) @@ -258,32 +262,23 @@ pub(crate) fn show( close } fn edit_listeners(ui: &mut egui::Ui, config: &mut VipConfig, n: &NetworkReport) { - let mut remove = None; - for (index, l) in config.listeners.iter_mut().enumerate() { - ui.push_id(index,|ui|{egui::Frame::group(ui.style()).show(ui,|ui|{ - ui.horizontal(|ui|{egui::ComboBox::from_id_salt("protocol").selected_text(l.protocol.to_string()).show_ui(ui,|ui|{ui.selectable_value(&mut l.protocol,Protocol::Tcp,"TCP");ui.selectable_value(&mut l.protocol,Protocol::Udp,"UDP");});ui.label("Port");ui.add(egui::DragValue::new(&mut l.port).range(1..=65535));if ui.button("Remove listener").clicked(){remove=Some(index);}}); - if l.protocol==Protocol::Tcp{ui.checkbox(&mut l.port_check,"Active TCP port checks");}else{ui.weak("UDP health: encrypted path probes and explicit port errors; application readiness is unknown.");} - ui.collapsing("Checks and flow expiry",|ui|{egui::Grid::new("settings").show(ui,|ui|{ - ui.label("Check interval, ms");ui.add(egui::DragValue::new(&mut l.check_interval_ms).range(250..=3_600_000));ui.end_row(); - ui.label("Check timeout, ms");ui.add(egui::DragValue::new(&mut l.check_timeout_ms).range(100..=60_000));ui.end_row(); - ui.label("Failures before exclusion");ui.add(egui::DragValue::new(&mut l.failure_threshold).range(1..=255));ui.end_row(); - ui.label("Successes before recovery");ui.add(egui::DragValue::new(&mut l.recovery_threshold).range(1..=255));ui.end_row(); - ui.label("Flow idle timeout, seconds");ui.add(egui::DragValue::new(&mut l.idle_timeout_secs).range(1..=604800));ui.end_row(); - });}); - let mut remove_backend=None;for(i,b)in l.backends.iter_mut().enumerate(){ui.push_id(i,|ui|{ui.horizontal(|ui|{ - egui::ComboBox::from_id_salt("node").width(240.).selected_text(peer_name(n,&b.peer)).show_ui(ui,|ui|{for m in &n.members{let label=format!("{} ({})",m.hostname.as_deref().unwrap_or("unnamed"),m.endpoint_id.chars().take(8).collect::());ui.selectable_value(&mut b.peer,m.endpoint_id.clone(),label);}}); - ui.label("Target port");ui.add(egui::DragValue::new(&mut b.port).range(1..=65535));if ui.button("Remove").clicked(){remove_backend=Some(i);} - });});}if let Some(i)=remove_backend{l.backends.remove(i);} - if ui.button("+ Backend").clicked(){l.backends.push(Backend{peer:n.members.first().map(|m|m.endpoint_id.clone()).unwrap_or_default(),port:l.port});} -});}); - } - if let Some(index) = remove { - config.listeners.remove(index); - } - if ui.button("+ Listener").clicked() { - config.listeners.push(Listener::new(Protocol::Tcp, 443)); - } + let members = n + .members + .iter() + .map(|m| { + ( + m.endpoint_id.clone(), + format!( + "{} ({})", + m.hostname.as_deref().unwrap_or("unnamed"), + crate::format::short(&m.endpoint_id) + ), + ) + }) + .collect::>(); + crate::listeners::edit(ui, config, &members); } + #[cfg(test)] mod tests { #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] @@ -291,7 +286,17 @@ mod tests { use tsunagi::vip::VipStatus; #[test] fn editing_the_actual_form_sends_nothing_until_save_is_clicked() { - let (agent, mut commands) = AgentClient::test_client(); + let (tx, commands) = std::sync::mpsc::channel(); + struct TestClient(std::sync::mpsc::Sender); + impl Client for TestClient { + fn send(&self, command: Command) { + self.0.send(command).unwrap(); + } + fn busy(&self) -> bool { + false + } + } + let agent = TestClient(tx); let ctx = egui::Context::default(); let mut config = VipConfig::new("api"); config.listeners.push(Listener::new(Protocol::Tcp, 443)); diff --git a/crates/tsunagi-tray/src/vip_status.rs b/crates/tsunagi-ui/src/vip_status.rs similarity index 92% rename from crates/tsunagi-tray/src/vip_status.rs rename to crates/tsunagi-ui/src/vip_status.rs index daf484c..ea15762 100644 --- a/crates/tsunagi-tray/src/vip_status.rs +++ b/crates/tsunagi-ui/src/vip_status.rs @@ -2,7 +2,6 @@ use std::collections::BTreeMap; use std::time::{Duration, Instant}; -use eframe::egui; use tsunagi::ipc::NetworkReport; use tsunagi::vip::{Backend, BackendStatus, Counters, ListenerStatus, Protocol, VipStatus}; @@ -61,12 +60,14 @@ fn key(v: &VipStatus, l: &ListenerStatus, b: &Backend) -> Key { ) } struct Camera { + layout_width: f32, rect: egui::Rect, members: Vec, } impl Default for Camera { fn default() -> Self { Self { + layout_width: 0.0, rect: egui::Rect::NOTHING, members: Vec::new(), } @@ -450,21 +451,36 @@ fn diagram( .entry((v.config.id.clone(), l.protocol.to_string(), l.port)) .or_default(); let members: Vec<_> = l.backends.iter().map(|b| b.backend.clone()).collect(); - let height = (members.len().max(1) as f32 * 92.0 + 32.0).max(180.0); - let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(860.0, height)); - if camera.members != members || !camera.rect.is_positive() { + let compact = ui.available_width() < 540.0; + let width = if compact { + ui.available_width().max(240.0) + } else { + 860.0 + }; + let pitch = if compact { 66.0 } else { 92.0 }; + let height = (members.len().max(1) as f32 * pitch + 32.0).max(160.0); + let bounds = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + if camera.members != members + || !camera.rect.is_positive() + || (camera.layout_width - width).abs() > 1.0 + { camera.rect = bounds; + camera.layout_width = width; camera.members = members; } ui.horizontal_wrapped(|ui| { legend(ui, "Traffic", ACTIVE, true); legend(ui, "Next new flow", NEXT, false); - ui.weak("Click a backend · drag to pan · Ctrl+scroll to zoom"); + ui.weak(if compact { + "Tap a backend · pinch to zoom" + } else { + "Click a backend · drag to pan · Ctrl+scroll to zoom" + }); if ui.small_button("Fit").clicked() { camera.rect = bounds; } }); - let size = egui::vec2(ui.available_width(), height.clamp(180.0, 360.0)); + let size = egui::vec2(ui.available_width(), height.clamp(160.0, 360.0)); let (outer, _) = ui.allocate_exact_size(size, egui::Sense::hover()); ui.painter() .rect_filled(outer, 6.0, ui.visuals().extreme_bg_color); @@ -475,12 +491,19 @@ fn diagram( .show(&mut child, &mut camera.rect, |ui| { ui.set_min_size(bounds.size()); let center = height / 2.0; - let source = - egui::Rect::from_min_size(egui::pos2(18.0, center - 32.0), egui::vec2(204.0, 64.0)); - let listener = egui::Rect::from_min_size( - egui::pos2(290.0, center - 32.0), - egui::vec2(146.0, 64.0), - ); + let rect = |x, y, w, h| egui::Rect::from_min_size(egui::pos2(x, y), egui::vec2(w, h)); + let (source, listener) = if compact { + let w = width * 0.40; + ( + rect(8.0, center - 65.0, w, 52.0), + rect(8.0, center + 12.0, w, 52.0), + ) + } else { + ( + rect(18.0, center - 32.0, 204.0, 64.0), + rect(290.0, center - 32.0, 146.0, 64.0), + ) + }; let active = l.backends.iter().any(|b| { view.backends .get(&key(v, l, &b.backend)) @@ -488,8 +511,16 @@ fn diagram( }); edge( ui, - source.right_center(), - listener.left_center(), + if compact { + source.center_bottom() + } else { + source.right_center() + }, + if compact { + listener.center_top() + } else { + listener.left_center() + }, if active { ACTIVE } else { NEXT }, active, ); @@ -513,10 +544,16 @@ fn diagram( let key = key(v, l, &b.backend); let rates = view.backends.get(&key); let state = branch(l, b, rates, Instant::now()); - let rect = egui::Rect::from_min_size( - egui::pos2(558.0, 24.0 + index as f32 * 92.0), - egui::vec2(278.0, 68.0), - ); + let rect = if compact { + rect( + width * 0.51, + 10.0 + index as f32 * pitch, + width * 0.49 - 8.0, + 56.0, + ) + } else { + rect(558.0, 24.0 + index as f32 * pitch, 278.0, 68.0) + }; let color = if state.active { ACTIVE } else if state.next { @@ -575,7 +612,7 @@ fn diagram( } if l.backends.is_empty() { ui.painter().text( - egui::pos2(570.0, center), + egui::pos2(if compact { width * 0.52 } else { 570.0 }, center), egui::Align2::LEFT_CENTER, "No backends", egui::FontId::proportional(15.0), @@ -648,14 +685,15 @@ fn text_line( painter.galley(position, painter.layout_job(job), color); } fn edge(ui: &egui::Ui, start: egui::Pos2, end: egui::Pos2, color: egui::Color32, active: bool) { - let bend = (end.x - start.x) * 0.5; + let delta = end - start; + let direction = if delta.x.abs() < 1.0 { + egui::Vec2::Y + } else { + egui::Vec2::X + }; + let bend = direction * delta.dot(direction) * 0.5; let curve = egui::epaint::CubicBezierShape::from_points_stroke( - [ - start, - start + egui::vec2(bend, 0.0), - end - egui::vec2(bend, 0.0), - end, - ], + [start, start + bend, end - bend, end], false, egui::Color32::TRANSPARENT, egui::Stroke::new(if active { 3.0_f32 } else { 1.5_f32 }, color), @@ -668,8 +706,8 @@ fn edge(ui: &egui::Ui, start: egui::Pos2, end: egui::Pos2, color: egui::Color32, ui.ctx().request_repaint_after(Duration::from_millis(40)); } ui.painter().arrow( - end - egui::vec2(12.0, 0.0), - egui::vec2(10.0, 0.0), + end - direction * 12.0, + direction * 10.0, egui::Stroke::new(1.5_f32, color), ); } @@ -859,7 +897,7 @@ mod tests { let (n, v) = fixture(); let ctx = egui::Context::default(); let mut view = View::default(); - for width in [650.0, 1000.0, 1800.0, 650.0] { + for width in [360.0, 412.0, 650.0, 1000.0, 1800.0, 360.0] { for _ in 0..2 { let _ = ctx.run( egui::RawInput { diff --git a/crates/tsunagi-wg-quic/tests/exit_node.rs b/crates/tsunagi-wg-quic/tests/exit_node.rs index 37d165f..8ac3095 100644 --- a/crates/tsunagi-wg-quic/tests/exit_node.rs +++ b/crates/tsunagi-wg-quic/tests/exit_node.rs @@ -19,58 +19,13 @@ use tempfile::TempDir; use tsunagi::dataplane::IpPlugin; use tsunagi::discovery::SharedMemoryDiscovery; use tsunagi::identity::NetworkId; -use tsunagi::overlay::{ - BroadcastHostRules, MemoryTun, MemoryTunFactory, MockHostRules, OverlayError, TunDevice, - TunFactory, TunRequest, -}; +use tsunagi::overlay::{MemoryTun, MemoryTunFactory, MockHostRules}; use tsunagi::testing::{network, wait_until}; use tsunagi::{Agent, NetworkStatus}; use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin}; const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34); -/// An in-memory interface on a host whose rules are a mock. -/// -/// Not "on the host": the agent must not go looking for an address on a real -/// link. It only has host *rules*, which is what an exit node needs from it. -#[derive(Debug, Clone)] -struct RuledTuns { - tuns: MemoryTunFactory, - rules: MockHostRules, -} - -impl TunFactory for RuledTuns { - fn name(&self) -> &str { - "memory-with-rules" - } - - fn on_host(&self) -> bool { - false - } - - fn host_rules(&self) -> Option> { - Some(Arc::new(self.rules.clone())) - } - - fn create<'a>( - &'a self, - request: TunRequest, - ) -> tsunagi::BoxFuture<'a, Result, OverlayError>> { - self.tuns.create(request) - } - - fn reconfigure<'a>( - &'a self, - request: TunRequest, - ) -> tsunagi::BoxFuture<'a, Result<(), OverlayError>> { - self.tuns.reconfigure(request) - } - - fn destroy<'a>(&'a self, name: &'a str) -> tsunagi::BoxFuture<'a, ()> { - self.tuns.destroy(name) - } -} - struct Node { _dir: TempDir, agent: Agent, @@ -94,10 +49,7 @@ impl Node { tsunagi::testing::config_with(dir.path(), discovery) .with_overlay_ipv4_range(Some(tsunagi::state::DEFAULT_IPV4_RANGE)) .with_interface( - Arc::new(RuledTuns { - tuns: tuns.clone(), - rules: rules.clone(), - }), + Arc::new(tuns.clone().with_host_rules(Arc::new(rules.clone()))), tag, 1280, ) diff --git a/crates/tsunagi-wireguard/src/transport.rs b/crates/tsunagi-wireguard/src/transport.rs index 31a26a5..818fab6 100644 --- a/crates/tsunagi-wireguard/src/transport.rs +++ b/crates/tsunagi-wireguard/src/transport.rs @@ -81,6 +81,7 @@ struct Inner { bind: Ipv4Addr, stun: Option, excluded_interface: Mutex>, + underlay: OnceLock>>, busy: Mutex>, control: OnceLock>, allowed: Mutex>, @@ -134,9 +135,14 @@ async fn addresses(inner: &Inner, socket: &UdpSocket) -> Result, let mut candidates = if inner.bind.is_loopback() { vec![local] } else { - crate::addresses::local_ip_candidates_excluding(lock(&inner.excluded_interface).as_deref()) - .into_iter() - .filter(|ip| ip.is_ipv4()) + let ips = match inner.underlay.get() { + Some(source) => source.borrow().clone(), + None => crate::addresses::local_ip_candidates_excluding( + lock(&inner.excluded_interface).as_deref(), + ), + }; + ips.into_iter() + .filter(|ip| matches!(ip, std::net::IpAddr::V4(v4) if crate::addresses::is_candidate_ipv4(*v4))) .take(31) .map(|ip| SocketAddr::new(ip, local.port())) .collect() @@ -207,6 +213,10 @@ impl AwgTransport { pub fn exclude_interface(&self, name: String) { *lock(&self.inner.excluded_interface) = Some(name); } + /// Use the OS-selected physical network on platforms with policy routing. + pub fn set_underlay(&self, source: watch::Receiver>) { + let _ = self.inner.underlay.set(source); + } /// Wire version of this carrier's private negotiation and framing. pub fn wire_version(&self) -> u16 { if self.inner.protocol == "wg" { @@ -237,6 +247,7 @@ impl AwgTransport { bind, stun, excluded_interface: Mutex::new(None), + underlay: OnceLock::new(), busy: Mutex::default(), control: OnceLock::new(), allowed: Mutex::default(), diff --git a/crates/tsunagi/Cargo.toml b/crates/tsunagi/Cargo.toml index 39e0890..d9562af 100644 --- a/crates/tsunagi/Cargo.toml +++ b/crates/tsunagi/Cargo.toml @@ -12,9 +12,9 @@ name = "tsng" path = "src/main.rs" [dependencies] +tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.0" } tsunagi-core = { path = "../tsunagi-core", version = "1.0.0", features = ["tun-device", "dns-publish"] } tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.0" } -tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.0" } tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.0" } tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.0" } iroh.workspace = true diff --git a/crates/tsunagi/src/main.rs b/crates/tsunagi/src/main.rs index 8534998..6af9d73 100644 --- a/crates/tsunagi/src/main.rs +++ b/crates/tsunagi/src/main.rs @@ -26,8 +26,7 @@ use tsunagi::iroh_types::{EndpointAddr, EndpointId}; use tsunagi::overlay::{MemoryTunFactory, TunFactory}; use tsunagi::state::Ipv4Range; use tsunagi::{Agent, NetworkId}; -use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport}; -use tsunagi_tcp_tls::{TCP_TLS_PROTOCOL, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport}; +use tsunagi_runtime::{Carriers, PROTOCOLS, ProtocolSpec}; use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin}; use tsunagi_wireguard::WG_PROTOCOL; @@ -1227,7 +1226,7 @@ fn dns_publisher() -> Arc { /// Every network the agent is in becomes a zone named after it, so joining /// or leaving one changes what resolves without restarting anything. fn spawn_dns(agent: Agent, port: u16) -> DnsService { - use tsunagi::dns::{DnsServer, SharedZone, Zone, ZoneName, Zones, listen_plan}; + use tsunagi::dns::{DnsServer, RosterZones, SharedZone, listen_plan}; let state = Arc::new(std::sync::Mutex::new(DnsState::default())); let publisher = dns_publisher(); @@ -1293,37 +1292,11 @@ fn spawn_dns(agent: Agent, port: u16) -> DnsService { // One zone per network, named after it. A name that cannot // be a zone is said once and skipped: the network works, // it just has no names. - let mut zones = Vec::new(); - let mut labels = Vec::new(); - let mut warnings = Vec::new(); - for network in &status.networks { - let zone = match ZoneName::new(network.name.as_str()) { - Ok(zone) => zone, - Err(err) => { - warnings.push(format!( - "`{}` cannot be a zone, so its members have no names: {err}", - network.name - )); - continue; - } - }; - if let Some(warning) = zone.collision() { - warnings.push(warning); - } - labels.push(zone.as_str().to_string()); - // Names come from signed state, so a member that is - // away is in here too. - let members = network.members.iter().filter_map(|member| { - Some((member.hostname.clone()?, member.overlay_address_v4?)) - }); - let services = network - .vips - .iter() - .filter(|v| v.error.is_none()) - .filter_map(|v| Some((v.config.name.clone(), v.address?))); - zones.push(Zone::new(zone, members.chain(services))); - } - let zones = Zones::new(zones); + let RosterZones { + zones, + labels, + warnings, + } = RosterZones::from_networks(&status.networks); let names = zones.names() as u32; shared.set(zones); update(&state, |state| { @@ -1438,58 +1411,6 @@ fn update(state: &Arc>, edit: impl FnOnce(&mut DnsSta } } -/// What a protocol is called, what it speaks, and what it takes. -/// -/// A registry rather than a lookup on the plugins themselves, because -/// `tsng protocols` has to answer before anything is constructed, and -/// because this is the list `--protocol` resolves against. -struct ProtocolSpec { - /// The name on the wire, which is what peers compare. - name: &'static str, - /// The wire version. Not the software version: two peers on different - /// builds carry traffic for each other as long as this matches. - version: u16, - /// One line about what it is. - summary: &'static str, - /// The settings it accepts. - options: &'static [tsunagi::dataplane::ProtocolOption], -} - -const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption { - key: "port", - value: "PORT", - help: "preferred local UDP port; additional pairs use dynamic ports", - default: Some("51820"), -}]; - -/// Every protocol this build has. -const PROTOCOLS: &[ProtocolSpec] = &[ - ProtocolSpec { - name: WG_PROTOCOL, - version: tsunagi_wireguard::WG_WIRE_VERSION, - summary: "Pure WireGuard direct UDP transport", - options: WG_OPTIONS, - }, - ProtocolSpec { - name: AWG_PROTOCOL, - version: AWG_WIRE_VERSION, - summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt", - options: AwgPlugin::OPTIONS, - }, - ProtocolSpec { - name: "wg-quic", - version: 1, - summary: "iroh QUIC datagram carrier with NAT traversal and relays", - options: &[], - }, - ProtocolSpec { - name: TCP_TLS_PROTOCOL, - version: 2, - summary: "TCP TLS 1.3 carrier", - options: TcpTlsConfig::OPTIONS, - }, -]; - /// One `-o` setting, and the protocol it was aimed at. #[derive(Clone)] struct Setting { @@ -1737,12 +1658,12 @@ impl tsunagi::ipc::ReportSource for AgentControl { fn network_secret(&self, network_id: String) -> tsunagi::BoxFuture<'_, Result> { Box::pin(async move { - let networks = stored_networks(&self.paths); - let network = networks - .iter() - .find(|network| network.network_id.to_string() == network_id) - .ok_or_else(|| format!("no configured network with id {network_id}"))?; - Ok(network.secret.encode().as_str().to_owned()) + let id = network_id.parse::().map_err(|e| e.to_string())?; + self.agent + .network_secret(id) + .await + .map(|secret| secret.encode().as_str().to_owned()) + .map_err(|err| err.to_string()) }) } @@ -4710,9 +4631,6 @@ async fn up(args: UpArgs) -> Result<(), Box> { // The interface belongs to the agent, so it is configured once whatever // was selected to carry traffic over it. - let mut awg_transport = None; - let mut tcp_tls_transport = None; - let mut pure_wg_transport: Option> = None; if !PROTOCOLS.is_empty() { let tun_factory: Arc = if args.no_tun { Arc::new(MemoryTunFactory::new()) @@ -4736,15 +4654,7 @@ async fn up(args: UpArgs) -> Result<(), Box> { config = config.with_tunnel(tunnel.clone()); let wireguard = Some(tunnel); - let identity_db = paths.state_db(); - let identity = tokio::task::spawn_blocking(move || { - tsunagi::storage::StateStore::open(identity_db)?.load_or_create_device_identity() - }) - .await??; - - for spec in PROTOCOLS { - // Unqualified options keep targeting the initial selection; explicitly - // scoped options also configure protocols that will be enabled later. + let (config, carriers) = Carriers::configure(config, &bootstrap, None, |spec| { let scoped: Vec<_> = settings .iter() .filter(|setting| { @@ -4752,97 +4662,9 @@ async fn up(args: UpArgs) -> Result<(), Box> { }) .cloned() .collect(); - let options = settings_for(spec, &scoped); - match spec.name { - AWG_PROTOCOL => { - let server = options - .iter() - .find(|(key, _)| key == "stun") - .map(|(_, value)| value.as_str()) - .unwrap_or("stun.l.google.com:19302"); - if server.len() > 255 || (server != "off" && !server.contains(':')) { - return Err("awg:stun must be HOST:PORT or off".into()); - } - let stun = (!matches!(args.reach, Reach::Local) && server != "off") - .then(|| server.to_owned()); - let transport = AwgTransport::new_with_stun( - identity.endpoint_id(), - std::net::Ipv4Addr::UNSPECIFIED, - stun, - ); - transport.exclude_interface(args.interface.clone()); - let plugin = AwgPlugin::new(transport.clone()); - config = config - .with_carrier( - plugin.clone() as Arc - ) - .with_custom_transport( - AWG_PROTOCOL, - transport.clone() - as Arc, - ); - awg_transport = Some(transport); - } - "wg-quic" => { - config = config.with_carrier(Arc::new( - tsunagi::dataplane::transport::iroh_link::IrohCarrier, - )); - } - TCP_TLS_PROTOCOL => { - let tls_cfg = TcpTlsConfig::new(); - let tls_cfg = TcpTlsConfig::configure(tls_cfg, &options)?; - let transport = Arc::new( - TcpTlsTransport::bind(&identity, tls_cfg.port, tls_cfg.sni) - .await - .map_err(|err| err.to_string())?, - ); - for ep_addr in &bootstrap { - for ip in ep_addr.ip_addrs() { - transport.set_peer_addr(ep_addr.id, *ip); - } - } - let plugin = - TcpTlsCarrier::with_interface(transport.clone(), args.interface.clone()); - config = config - .with_carrier( - plugin.clone() as Arc - ) - .with_custom_transport( - TCP_TLS_PROTOCOL, - Arc::clone(&transport) - as Arc, - ); - tcp_tls_transport = Some(transport); - } - WG_PROTOCOL => { - let port = options - .iter() - .find(|(key, _)| key == "port") - .map(|(_, value)| value.parse::()) - .transpose()? - .unwrap_or(51820); - let transport = AwgTransport::wireguard_with_port( - identity.endpoint_id(), - std::net::Ipv4Addr::UNSPECIFIED, - (!matches!(args.reach, Reach::Local)).then(|| "stun.l.google.com:19302".into()), - port, - ); - transport.exclude_interface(args.interface.clone()); - let plugin = AwgPlugin::new(transport.clone()); - config = config - .with_carrier( - plugin.clone() as Arc - ) - .with_custom_transport( - WG_PROTOCOL, - Arc::clone(&transport) - as Arc, - ); - pure_wg_transport = Some(transport); - } - other => return Err(format!("`{other}` is listed but not built in").into()), - } - } + settings_for(spec, &scoped) + }) + .await?; let agent = match Agent::spawn(config).await { Ok(agent) => agent, @@ -4877,41 +4699,7 @@ async fn up(args: UpArgs) -> Result<(), Box> { // is never dropped without being closed. let mut events = agent.subscribe(); - if let Some(transport) = awg_transport { - let inbound_agent = agent.clone(); - tokio::spawn(async move { - while let Some(inbound) = transport.next_inbound().await { - if let Err(err) = inbound_agent.install_inbound_link(inbound).await { - tracing::debug!(%err, "failed to install inbound awg link"); - } - } - }); - } - if let Some(transport) = tcp_tls_transport { - let agent_inbound = agent.clone(); - tokio::spawn(async move { - transport - .accept_loop(move |inbound| { - let agent = agent_inbound.clone(); - tokio::spawn(async move { - if let Err(err) = agent.install_inbound_link(inbound).await { - tracing::debug!(%err, "failed to install inbound tcp-tls link"); - } - }); - }) - .await; - }); - } - if let Some(transport) = pure_wg_transport { - let inbound_agent = agent.clone(); - tokio::spawn(async move { - while let Some(inbound) = transport.next_inbound().await { - if let Err(err) = inbound_agent.install_inbound_link(inbound).await { - tracing::debug!(%err, "failed to install inbound wg link"); - } - } - }); - } + let _listeners = carriers.listen(&agent); let protocol_names: Vec<&str> = wanted.iter().map(|p| p.name).collect(); @@ -5039,9 +4827,7 @@ async fn build_report( dns: Option, paths: &StoragePaths, ) -> tsunagi::ipc::StatusReport { - use tsunagi::ipc::{ - MemberReport, NetworkReport, OverlayPeerReport, OverlayReport, PeerReport, StatusReport, - }; + use tsunagi::ipc::StatusReport; let overlay = agent.overlay(); let dns = dns.map(dns_report); @@ -5050,159 +4836,7 @@ async fn build_report( return StatusReport::default(); }; - let networks = status - .networks - .iter() - .map(|network| { - let wg_view = wireguard.and_then(|plugin| plugin.overview(network.network_id)); - let wg_overlay_addr = wg_view.as_ref().and_then(|v| v.overlay_address_v4); - let wg_prefix_len = wg_view - .as_ref() - .and_then(|v| v.ipv4_range) - .map_or(0, |r| r.prefix_len); - let has_any_plugin = wg_view.is_some(); - - let overlay = if has_any_plugin && overlay.is_some() { - let mut peers: Vec = Vec::new(); - - if let Some(view) = &wg_view { - for peer in &view.peers { - let tunnel = peer.tunnel.as_ref(); - peers.push(OverlayPeerReport { - counter_epoch: tunnel.map_or(0, |t| t.stats.counter_epoch), - endpoint_id: peer.endpoint_id.to_string(), - protocol: String::new(), - public_key: peer.public_key.to_string(), - address: peer.overlay_address_v4.map(|a| a.to_string()), - handshake_secs_ago: tunnel - .and_then(|t| t.health.since_handshake.map(|s| s.as_secs())), - tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets), - rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets), - tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes), - rx_bytes: tunnel.map_or(0, |t| t.stats.rx_bytes), - dropped: tunnel.map_or(0, |t| { - t.stats.dropped_wrong_source + t.stats.dropped_oversize - }), - protocol_errors: tunnel.map_or(0, |t| t.stats.protocol_errors), - path: tunnel.map_or_else(|| "no data path".into(), |t| t.path.clone()), - }); - } - } - - let (address, prefix_len) = if wg_overlay_addr.is_some() { - (wg_overlay_addr.map(|addr| addr.to_string()), wg_prefix_len) - } else { - ( - network - .members - .iter() - .find(|m| m.endpoint_id == status.endpoint_id) - .and_then(|m| m.overlay_address_v4) - .map(|a| a.to_string()), - network.range.map_or(0, |r| r.prefix_len), - ) - }; - - Some(OverlayReport { - interface: overlay - .as_ref() - .map_or_else(String::new, |o| o.interface.clone()), - on_host: overlay.as_ref().is_some_and(|o| o.on_host), - mtu: overlay.as_ref().map_or(0, |o| o.mtu), - address, - prefix_len, - peers, - unroutable_packets: overlay.as_ref().map_or(0, |o| o.counters.unroutable), - multicast_packets: overlay.as_ref().map_or(0, |o| o.counters.multicast), - unroutable_sample: overlay - .as_ref() - .and_then(|o| o.counters.unroutable_sample.map(|a| a.to_string())), - broadcast_rules: overlay - .as_ref() - .and_then(|o| o.broadcast_rules.as_ref()) - .map(|rules| tsunagi::ipc::HostRulesReport { - ok: rules.is_ok(), - detail: rules.summary(), - source: rules.plan.source.to_string(), - }), - }) - } else { - None - }; - - NetworkReport { - vips: network.vips.clone(), - protocols: network.protocols.clone(), - auto_start: network.auto_start, - exit: exit_report(network), - broadcast: network.broadcast, - name: network.name.to_string(), - network_id: network.network_id.to_string(), - active: matches!(network.state, tsunagi::agent::NetworkState::Active), - candidates: network.candidates.len() as u32, - relay_forwarded: network.relay.forwarded, - relay_sent_via: network.relay.sent_via, - relay_received_via: network.relay.received_via, - peers: network - .peers - .iter() - .map(|peer| PeerReport { - data_error: peer.data_error.clone(), - endpoint_id: peer.endpoint_id.to_string(), - hostname: peer.hostname.clone(), - transport: peer.transport.to_string(), - rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64), - exit_node: peer.exit_node, - path: data_path_report(&peer.data_path), - }) - .collect(), - members: network - .members - .iter() - .map(|member| MemberReport { - record_version: member.record_version, - endpoint_id: member.endpoint_id.to_string(), - overlay_address_v4: member.overlay_address_v4.map(|addr| addr.to_string()), - // What this agent is currently experiencing trying to - // reach it, so a dial-failure count can be attributed - // to the member it belongs to instead of floating - // free as a network-wide number. - failed_dials: network - .candidates - .iter() - .find(|candidate| candidate.endpoint_id == member.endpoint_id) - .map_or(0, |candidate| candidate.consecutive_failures), - hostname: member - .last_hostname - .clone() - .or_else(|| member.hostname.clone()), - online: member.online, - path: data_path_report(&member.data_path), - hostname_conflict: member.hostname_conflict.as_ref().map(conflict_report), - }) - .collect(), - range: network.range.map(|range| range.to_string()), - range_conflict: network.range_conflict.map(|range| range.to_string()), - range_conflicts: network - .range_conflicts - .iter() - .map(|c| tsunagi::ipc::RangeConflictReport { - network_id: c.network_id.to_string(), - name: c.name.to_string(), - range: c.range.to_string(), - }) - .collect(), - dial_failures: network.metrics.dial_failures, - handshake_failures: network.metrics.handshake_failures, - control_messages: ( - network.metrics.control_messages_sent, - network.metrics.control_messages_received, - ), - overlay, - hostname_conflict: network.hostname_conflict.as_ref().map(conflict_report), - } - }) - .collect(); + let networks = tsunagi_runtime::report::networks(&status, overlay.as_ref(), wireguard); StatusReport { available_protocols: PROTOCOLS @@ -5240,46 +4874,6 @@ async fn build_report( } } -fn data_path_report(path: &tsunagi::agent::DataPath) -> tsunagi::ipc::DataPathReport { - match path { - tsunagi::agent::DataPath::None => tsunagi::ipc::DataPathReport::None, - tsunagi::agent::DataPath::Direct { transport } => tsunagi::ipc::DataPathReport::Direct { - transport: transport.clone(), - }, - tsunagi::agent::DataPath::Relayed { hops, via } => tsunagi::ipc::DataPathReport::Relayed { - hops: *hops, - via: via.to_string(), - }, - } -} - -fn conflict_report( - conflict: &tsunagi::agent::HostnameConflict, -) -> tsunagi::ipc::HostnameConflictReport { - tsunagi::ipc::HostnameConflictReport { - name: conflict.name.clone(), - holder: conflict.holder.to_string(), - } -} - -/// One network's exit-node settings, as the control interface reports them. -fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitReport { - let rules = |report: &Option| { - report.as_ref().map(|report| tsunagi::ipc::RuleSetReport { - ok: report.ok, - detail: report.detail.clone(), - }) - }; - tsunagi::ipc::ExitReport { - offering: network.exit_offer, - offer_rules: rules(&network.exit_rules.offer), - forwarding: network.exit_rules.forwarding, - via: network.exit_via.map(|peer| peer.to_string()), - via_online: network.exit_via_online, - client_rules: rules(&network.exit_rules.client), - } -} - /// The status line for the host rules, saying so when they are bound to /// another network's address. fn broadcast_rules_line(