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:
1 parent
9dec056349
commit
ef67e1c0ae
70 files changed
+6199
-1181
No files matched your search
@@ -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>
|
||||
Reference in new issue
Block a user