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.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-24 17:28:23 +02:00
1 parent 9dec056349
commit ef67e1c0ae
70 files changed
+6199 -1181

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
gradlew text eol=lf
gradlew.bat text eol=crlf
+5
View File
@@ -0,0 +1,5 @@
.gradle/
.kotlin/
.idea/
local.properties
**/build/
+23
View File
@@ -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 `<member>.<network>` and `<vip>.<network>`, 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)
+59
View File
@@ -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 }
}
+25
View File
@@ -0,0 +1,25 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SYSTEM_EXEMPTED" />
<uses-feature android:glEsVersion="0x00030000" android:required="true" />
<application android:label="tsunagi" android:icon="@drawable/tsunagi"
android:enableOnBackInvokedCallback="false" android:allowBackup="false" android:theme="@android:style/Theme.Material.NoActionBar">
<activity android:name=".MainActivity" android:exported="true"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
android:foregroundServiceType="systemExempted" android:exported="false">
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
</service>
</application>
</manifest>
@@ -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() }
}
@@ -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
}
}
@@ -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<ByteArray>()
val cancel = CancellationSignal()
return try {
DnsResolver.getInstance().rawQuery(network, query, DnsResolver.FLAG_EMPTY, { it.run() }, cancel,
object : DnsResolver.Callback<ByteArray> {
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)
}
}
@@ -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)
}
@@ -0,0 +1,6 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp" android:height="48dp" android:viewportWidth="128" android:viewportHeight="128">
<path android:fillColor="#2f80d8" android:pathData="M64,8a56,56 0,1 1,0 112a56,56 0,1 1,0 -112" />
<path android:strokeColor="#ffffff" android:strokeWidth="7" android:pathData="M64,34a30,30 0,1 1,0 60a30,30 0,1 1,0 -60" />
<path android:fillColor="#ffffff" android:pathData="M64,55a9,9 0,1 1,0 18a9,9 0,1 1,0 -18" />
</vector>
+2
View File
@@ -0,0 +1,2 @@
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536m -Dfile.encoding=UTF-8
Binary file not shown.
+7
View File
@@ -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
Vendored Executable
+248
View File
@@ -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" "$@"
+93
View File
@@ -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
+3
View File
@@ -0,0 +1,3 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
rootProject.name = 'tsunagi-android'
include ':app'