Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Fixes from an audit: input safety, pairing, control stream, lifecycle

Bee8fa56c94d1fa
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt b/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt
index 28d8502..f020f21 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/calls/PhoneCalls.kt
@@ -144,7 +144,7 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit
missedCheck: Boolean,
) {
val (name, photo) = if (withContact) contact(number) else null to null
- val missed = missedCheck && wasMissed()
+ val missed = missedCheck && wasMissed(id, number)
onChange(
Call(
id = id,
@@ -196,18 +196,28 @@ internal class PhoneCalls(context: Context, private val onChange: (Call) -> Unit
}
}
- /** Whether the latest call in the log is a missed one (not turned down or blocked). */
+ /** Whether the call that just ended is in the log as a missed one (not turned down or blocked). */
@SuppressLint("MissingPermission")
- private fun wasMissed(): Boolean {
+ private fun wasMissed(id: String, number: String?): Boolean {
if (!granted(context, Manifest.permission.READ_CALL_LOG)) return true
+ val started = id.toLongOrNull() ?: 0L
return runCatching {
context.contentResolver.query(
CallLog.Calls.CONTENT_URI.buildUpon().appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, "1").build(),
- arrayOf(CallLog.Calls.TYPE),
+ arrayOf(CallLog.Calls.TYPE, CallLog.Calls.DATE, CallLog.Calls.NUMBER),
null,
null,
"${CallLog.Calls.DATE} DESC",
- )?.use { if (it.moveToFirst()) it.getInt(0) == CallLog.Calls.MISSED_TYPE else true } ?: true
+ )?.use { cursor ->
+ if (!cursor.moveToFirst()) return@use true
+ val date = cursor.getLong(1)
+ val loggedNumber = cursor.getString(2)
+ if (started > 0L && date < started - 10_000L) return@use true
+ if (number != null && !loggedNumber.isNullOrBlank() && !android.telephony.PhoneNumberUtils.compare(context, number, loggedNumber)) {
+ return@use true
+ }
+ cursor.getInt(0) == CallLog.Calls.MISSED_TYPE
+ } ?: true
}.getOrDefault(true)
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 0d57937..331fef5 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -24,6 +24,7 @@ import app.nectarlink.android.mirror.AppWindows
import app.nectarlink.android.mirror.InputService
import app.nectarlink.android.mirror.MirrorRequests
import app.nectarlink.android.photos.RecentPhotos
+import app.nectarlink.android.service.ConnectionService
import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.core.Event
import app.nectarlink.core.EventListener
@@ -157,6 +158,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
node = started
val devices = runCatching { started.pairedDevices() }.getOrDefault(emptyList())
_state.update { it.withDevices(devices).copy(status = CoreStatus.Ready(started.deviceId())) }
+ if (devices.isNotEmpty()) ConnectionService.start(context)
scope.launch(Dispatchers.Main) {
battery.start()
network.start()
@@ -173,8 +175,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
scope.launch { Elevated.start() }
scope.launch(Dispatchers.Main) {
if (_state.value.photoAccess) photos.start()
- calls.start()
- sms.start()
+ if (PhoneCalls.canFollow(context)) calls.start()
+ if (PhoneSms.canRead(context)) sms.start()
}
scope.launch {
for (op in notificationOps) {
@@ -192,6 +194,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
*/
fun notificationAccessChanged(granted: Boolean, showing: List<Notification>) {
_state.update { it.copy(notificationAccess = granted) }
+ if (granted && _state.value.devices.isNotEmpty()) ConnectionService.start(context)
scope.launch(Dispatchers.Main) { if (granted) phoneMedia.start() else phoneMedia.stop() }
notificationOps.trySend { node ->
node.updatePower(powerLevel(), capabilities(granted))
@@ -219,17 +222,12 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
val callAccess = PhoneCalls.hasAll(context)
val smsAccess = PhoneSms.hasAll(context)
val inputAccess = InputService.running
- val inputChanged = inputAccess != _state.value.inputAccess
val elevated = Elevated.running
- val elevatedChanged = elevated != _state.value.elevated
val localNetwork = LocalNetwork.granted(context)
if (localNetwork && !_state.value.localNetwork) {
// Just allowed: reach the PCs now rather than at the next retry.
scope.launch { node?.networkChanged() }
}
- val photosChanged = photoAccess != _state.value.photoAccess
- val callsChanged = callAccess != _state.value.callAccess
- val smsChanged = smsAccess != _state.value.smsAccess
_state.update {
it.copy(
notificationAccess = granted,
@@ -245,10 +243,12 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
if (granted && NotificationListener.instance == null) {
NotificationListenerService.requestRebind(NotificationListener.component(context))
}
- if ((photosChanged || callsChanged || smsChanged || inputChanged || elevatedChanged) && node != null) {
- if (photoAccess) photos.start() else photos.stop()
- if (PhoneCalls.canFollow(context)) calls.start() else calls.stop()
- if (PhoneSms.canRead(context)) sms.start() else sms.stop()
+ if (node != null) {
+ scope.launch(Dispatchers.Main) {
+ if (photoAccess) photos.start() else photos.stop()
+ if (PhoneCalls.canFollow(context)) calls.start() else calls.stop()
+ if (PhoneSms.canRead(context)) sms.start() else sms.stop()
+ }
notificationOps.trySend { it.updatePower(powerLevel(), capabilities(_state.value.notificationAccess)) }
}
}
@@ -261,7 +261,12 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
// A PC that's gone isn't playing for this phone anymore; it
// sends what plays when it's back.
is Event.LinkChanged -> if (event.link is Link.Offline) pcMedia.update(event.id, "", emptyList())
- is Event.DeviceRemoved -> pcMedia.update(event.id, "", emptyList())
+ is Event.DeviceAdded -> ConnectionService.start(context)
+ is Event.DeviceRemoved -> {
+ pcMedia.update(event.id, "", emptyList())
+ if (_state.value.devices.isEmpty()) ConnectionService.stop(context)
+ }
+ is Event.Paired -> ConnectionService.start(context)
else -> {}
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
index 43fe660..74d9ee9 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/Elevated.kt
@@ -295,7 +295,7 @@ object Elevated {
is MirrorInputEvent.Key -> keys[event.key]?.let { "K $it" }
?: if (event.key == "notifications" && display == null) "C cmd statusbar expand-notifications" else return true
// One line per piece: no line breaks inside.
- is MirrorInputEvent.Text -> return event.text.split('\n').withIndex().all { (i, piece) ->
+ is MirrorInputEvent.Text -> return event.text.split(LINE_BREAK).withIndex().all { (i, piece) ->
(i == 0 || send(writer, "${to}K ${KeyEvent.KEYCODE_ENTER}")) && (piece.isEmpty() || send(writer, "${to}T $piece"))
}
}
@@ -309,6 +309,7 @@ object Elevated {
* isn't running. Write "K\n" for a keyframe; close it to close the window.
*/
fun openApp(pkg: String, width: Int, height: Int, dpi: Int, bitrate: Int, fps: Int): java.net.Socket? {
+ if (!PACKAGE.matches(pkg)) return null
val (port, token) = helper ?: return null
return runCatching {
java.net.Socket(java.net.InetAddress.getLoopbackAddress(), port).apply {
@@ -321,6 +322,7 @@ object Elevated {
}
private fun send(writer: Writer, line: String): Boolean = try {
+ require('\r' !in line && '\n' !in line)
synchronized(writer) {
writer.write(line + "\n")
writer.flush()
@@ -332,6 +334,9 @@ object Elevated {
false
}
+ private val LINE_BREAK = Regex("\r\n|\r|\n")
+ private val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+")
+
private val keys = mapOf(
"back" to KeyEvent.KEYCODE_BACK,
"home" to KeyEvent.KEYCODE_HOME,
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt
index c853738..efbd0c7 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/InputServer.kt
@@ -38,14 +38,18 @@ import java.security.MessageDigest
* connection closes the window.
*/
object InputServer {
+ private val windows = java.util.Collections.synchronizedSet(LinkedHashSet<AppDisplay>())
+ @Volatile private var serverSocket: ServerSocket? = null
+
@JvmStatic
fun main(args: Array<String>) {
val token = args.getOrNull(0) ?: return fail("no token")
val injector = runCatching { Injector() }.getOrElse { return fail("can't inject input: $it") }
val server = runCatching { ServerSocket(0, 1, InetAddress.getLoopbackAddress()) }.getOrElse { return fail("can't listen: $it") }
+ serverSocket = server
println("ready ${server.localPort}")
System.out.flush()
- while (true) {
+ while (!server.isClosed) {
val client = runCatching { server.accept() }.getOrNull() ?: continue
Thread { serve(client, token, injector) }.start()
}
@@ -55,45 +59,77 @@ object InputServer {
System.err.println(why)
}
+ private fun shutdown() {
+ runCatching { serverSocket?.close() }
+ val open = synchronized(windows) { windows.toList().also { windows.clear() } }
+ open.forEach { runCatching { it.stop() } }
+ kotlin.system.exitProcess(0)
+ }
+
private fun serve(client: Socket, token: String, injector: Injector) {
client.use {
client.tcpNoDelay = true
client.soTimeout = 0
val reader = client.inputStream.bufferedReader()
// Compared in constant time: the token is the only key.
- val given = runCatching { reader.readLine() }.getOrNull() ?: return
+ val given = runCatching { reader.nextLine() }.getOrNull() ?: return
if (!MessageDigest.isEqual(given.toByteArray(), token.toByteArray())) return
- val first = reader.readLine() ?: return
- if (first.startsWith("V ")) return appWindow(client, first, reader)
- var line: String? = first
- while (line != null) {
- val input = line
- runCatching { injector.handle(input) }.onFailure { System.err.println("input failed: $it") }
- line = reader.readLine()
+ val first = runCatching { reader.nextLine() }.getOrNull()
+ if (first != null && first.startsWith("V ")) return appWindow(client, first, reader)
+ try {
+ var line: String? = first
+ while (line != null) {
+ val input = line
+ runCatching { injector.handle(input) }.onFailure { System.err.println("input failed: $it") }
+ line = runCatching { reader.nextLine() }.getOrNull()
+ }
+ } finally {
+ shutdown()
}
}
}
+ /**
+ * Reads until `\n` (ignoring bare `\r` as a line break so embedded `\r`
+ * in typed text can never start a second command).
+ */
+ private fun java.io.Reader.nextLine(): String? {
+ val sb = StringBuilder()
+ while (true) {
+ val ch = read()
+ if (ch < 0) return if (sb.isEmpty()) null else sb.toString()
+ if (ch == '\n'.code) return sb.toString()
+ if (ch != '\r'.code) sb.append(ch.toChar())
+ }
+ }
+
/** An app window on this connection, until it closes. */
private fun appWindow(client: Socket, request: String, reader: java.io.BufferedReader) {
val parts = request.split(' ')
+ if (parts.size < 7) return
val numbers = parts.subList(1, 6).map { it.toIntOrNull() ?: return }
val (width, height, dpi, bitrate, fps) = numbers
val pkg = parts.getOrNull(6)?.takeIf { PACKAGE.matches(it) } ?: return
if (width !in 16..4096 || height !in 16..4096 || dpi !in 72..1000) return
val window = AppDisplay(width, height, dpi, bitrate.coerceIn(500_000, 40_000_000), fps.coerceIn(1, 120))
+ windows.add(window)
// Further lines: keyframe requests; the end of them closes the window.
Thread {
try {
while (true) {
- val line = reader.readLine() ?: break
+ val line = reader.nextLine() ?: break
if (line == "K") window.requestKeyframe()
}
} catch (_: java.io.IOException) {
}
window.stop()
}.start()
- runCatching { window.run(pkg, client.getOutputStream()) }.onFailure { System.err.println("app window ended: $it") }
+ try {
+ runCatching { window.run(pkg, client.getOutputStream()) }.onFailure { System.err.println("app window ended: $it") }
+ } finally {
+ windows.remove(window)
+ window.stop()
+ }
}
private val PACKAGE = Regex("[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)+")
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt b/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt
index d662997..cc1a522 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/files/ReceivedFiles.kt
@@ -34,7 +34,11 @@ internal object ReceivedFiles {
item.walkTopDown().filter { it.isFile }.mapNotNull { file ->
val folder = file.parentFile!!.relativeTo(item.parentFile!!).invariantSeparatorsPath
publishFile(context, file, folder)
- }.toList().also { item.deleteRecursively() }
+ }.toList().also {
+ item.walkBottomUp().filter { it.isDirectory }.forEach { dir ->
+ if (dir.list()?.isEmpty() == true) dir.delete()
+ }
+ }
} else {
listOfNotNull(publishFile(context, item, folder = null))
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt
index 25fe259..4e406a6 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/InputService.kt
@@ -157,10 +157,22 @@ class InputService : AccessibilityService() {
node.performAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_IME_ENTER.id)
}
}
- "backspace" -> edit { text, start, end -> if (start != end) Edit(text.removeRange(start, end), start) else if (start > 0) Edit(text.removeRange(start - 1, start), start - 1) else null }
- "delete" -> edit { text, start, end -> if (start != end) Edit(text.removeRange(start, end), start) else if (end < text.length) Edit(text.removeRange(end, end + 1), start) else null }
- "left" -> edit { text, start, _ -> Edit(text, (start - 1).coerceAtLeast(0)) }
- "right" -> edit { text, _, end -> Edit(text, (end + 1).coerceAtMost(text.length)) }
+ "backspace" -> edit { text, start, end ->
+ if (start != end) Edit(text.removeRange(start, end), start)
+ else if (start > 0) {
+ val prev = text.offsetByCodePoints(start, -1)
+ Edit(text.removeRange(prev, start), prev)
+ } else null
+ }
+ "delete" -> edit { text, start, end ->
+ if (start != end) Edit(text.removeRange(start, end), start)
+ else if (end < text.length) {
+ val next = text.offsetByCodePoints(end, 1)
+ Edit(text.removeRange(end, next), start)
+ } else null
+ }
+ "left" -> edit { text, start, _ -> Edit(text, if (start > 0) text.offsetByCodePoints(start, -1) else 0) }
+ "right" -> edit { text, _, end -> Edit(text, if (end < text.length) text.offsetByCodePoints(end, 1) else text.length) }
}
}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
index ca268be..ab06244 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/service/ConnectionService.kt
@@ -40,16 +40,25 @@ class ConnectionService : LifecycleService() {
app.nectarlink.android.media.PcMedia.createChannel(this)
app.nectarlink.android.links.LinkNotifications.createChannel(this)
val core = (application as NectarlinkApplication).core
- startInForeground(core.state.value)
+ if (!startInForeground(core.state.value)) {
+ stopSelf()
+ return
+ }
multicastLock = getSystemService(WifiManager::class.java)
?.createMulticastLock("nectarlink-discovery")
?.apply { setReferenceCounted(false); acquire() }
lifecycleScope.launch {
- core.state.map { Status.of(it) }.distinctUntilChanged().collect { status ->
- getSystemService(NotificationManager::class.java)
- .notify(ONGOING_ID, ongoingNotification(status))
- }
+ core.state.map { Status.of(it) to (it.status is app.nectarlink.android.core.CoreStatus.Ready) }
+ .distinctUntilChanged()
+ .collect { (status, ready) ->
+ if (ready && status.paired == 0) {
+ stopSelf()
+ } else {
+ getSystemService(NotificationManager::class.java)
+ .notify(ONGOING_ID, ongoingNotification(status))
+ }
+ }
}
lifecycleScope.launch {
core.state.map { it.ringingFrom }.distinctUntilChanged().collect { from ->
@@ -72,14 +81,16 @@ class ConnectionService : LifecycleService() {
super.onDestroy()
}
- private fun startInForeground(state: CoreState) {
+ private fun startInForeground(state: CoreState): Boolean = runCatching {
val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
} else {
0
}
ServiceCompat.startForeground(this, ONGOING_ID, ongoingNotification(Status.of(state)), type)
- }
+ }.onFailure {
+ android.util.Log.w("ConnectionService", "can't enter foreground", it)
+ }.isSuccess
/** What the ongoing notification says. */
private data class Status(val connected: List<String>, val paired: Int) {
@@ -141,9 +152,19 @@ class ConnectionService : LifecycleService() {
private const val CHANNEL_RINGING = "ringing"
private const val ACTION_STOP_RINGING = "app.nectarlink.action.STOP_RINGING"
- /** Starts the service (from the foreground: Android forbids it otherwise). */
+ /** Starts the service when allowed by Android's foreground-service rules. */
fun start(context: Context) {
- ContextCompat.startForegroundService(context, Intent(context, ConnectionService::class.java))
+ runCatching {
+ ContextCompat.startForegroundService(context, Intent(context, ConnectionService::class.java))
+ }.onFailure {
+ android.util.Log.w("ConnectionService", "can't start in background", it)
+ }
+ }
+
+ fun stop(context: Context) {
+ runCatching {
+ context.stopService(Intent(context, ConnectionService::class.java))
+ }
}
private fun createChannels(context: Context) {
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
index 67a2e0d..5023712 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/MainActivity.kt
@@ -77,9 +77,13 @@ class MainActivity : ComponentActivity() {
setContent {
val appearance by preferences.appearance.collectAsStateWithLifecycle()
val state by core.state.collectAsStateWithLifecycle()
- // Stay reachable in the background once a PC is paired.
- LaunchedEffect(state.devices.isNotEmpty()) {
- if (state.devices.isNotEmpty()) ConnectionService.start(this@MainActivity)
+ // Stay reachable in the background while a PC is paired.
+ LaunchedEffect(state.devices.isNotEmpty(), state.status is CoreStatus.Ready) {
+ if (state.devices.isNotEmpty()) {
+ ConnectionService.start(this@MainActivity)
+ } else if (state.status is CoreStatus.Ready) {
+ ConnectionService.stop(this@MainActivity)
+ }
}
NectarlinkTheme(appearance) {
// Every screen sits on the theme's background, not the
diff --git a/core/nectarlink-core/src/clipboard.rs b/core/nectarlink-core/src/clipboard.rs
index 1ca12e2..2b16ad6 100644
--- a/core/nectarlink-core/src/clipboard.rs
+++ b/core/nectarlink-core/src/clipboard.rs
@@ -134,8 +134,15 @@ async fn take_image(
return Err((ErrorCode::Denied, "the clipboard is off for this device"));
}
let size = usize::try_from(image.size).map_err(|_| (ErrorCode::BadMessage, "invalid image"))?;
- let mut bytes = vec![0u8; size];
- recv.read_exact(&mut bytes).await.map_err(|_| (ErrorCode::BadMessage, "the image ended early"))?;
+ let mut bytes = Vec::with_capacity(size.min(64 * 1024));
+ let mut buf = vec![0u8; 64 * 1024];
+ while bytes.len() < size {
+ let want = (size - bytes.len()).min(buf.len());
+ match recv.read(&mut buf[..want]).await {
+ Ok(Some(n)) if n > 0 => bytes.extend_from_slice(&buf[..n]),
+ _ => return Err((ErrorCode::BadMessage, "the image ended early")),
+ }
+ }
let platform = shared.platform.clone();
let mime = image.mime;
match tokio::task::spawn_blocking(move || platform.set_clipboard_image(&mime, &bytes)).await {
diff --git a/core/nectarlink-core/src/error.rs b/core/nectarlink-core/src/error.rs
index a0327a3..43d4005 100644
--- a/core/nectarlink-core/src/error.rs
+++ b/core/nectarlink-core/src/error.rs
@@ -52,7 +52,7 @@ impl From<ProtocolError> for Error {
fn from(err: ProtocolError) -> Self {
match err {
ProtocolError::Remote { code, msg } => match code {
- ErrorCode::Denied => Error::Denied,
+ ErrorCode::Denied | ErrorCode::Busy => Error::Denied,
ErrorCode::Unpaired => Error::NotPaired,
ErrorCode::Unsupported => Error::Unsupported,
ErrorCode::NotFound => Error::NotFound,
diff --git a/core/nectarlink-core/src/pairing.rs b/core/nectarlink-core/src/pairing.rs
index 87f0e12..cafb9a9 100644
--- a/core/nectarlink-core/src/pairing.rs
+++ b/core/nectarlink-core/src/pairing.rs
@@ -69,6 +69,18 @@ pub(crate) struct PairingState {
host: Mutex<Option<HostMode>>,
/// Waiting for the local user to confirm or reject the 6-digit code.
sas_decision: Mutex<Option<(DeviceId, oneshot::Sender<bool>)>>,
+ /// True while a nearby ceremony is in flight, so a second one cannot
+ /// overwrite `sas_decision`.
+ nearby_active: std::sync::atomic::AtomicBool,
+}
+
+pub(crate) struct NearbyGuard<'a>(&'a PairingState);
+
+impl Drop for NearbyGuard<'_> {
+ fn drop(&mut self) {
+ self.0.clear_decision();
+ self.0.nearby_active.store(false, std::sync::atomic::Ordering::Release);
+ }
}
impl std::fmt::Debug for PairingState {
@@ -115,6 +127,18 @@ impl PairingState {
false
}
+ fn begin_nearby(&self) -> Option<NearbyGuard<'_>> {
+ self.nearby_active
+ .compare_exchange(
+ false,
+ true,
+ std::sync::atomic::Ordering::AcqRel,
+ std::sync::atomic::Ordering::Acquire,
+ )
+ .ok()
+ .map(|_| NearbyGuard(self))
+ }
+
/// Delivers the local user's decision about the 6-digit code.
pub(crate) fn decide(&self, matches: bool) -> Result<()> {
match lock(&self.sas_decision).take() {
@@ -126,10 +150,14 @@ impl PairingState {
}
}
- fn await_decision(&self, peer: DeviceId) -> oneshot::Receiver<bool> {
+ fn await_decision(&self, peer: DeviceId) -> Result<oneshot::Receiver<bool>> {
+ let mut slot = lock(&self.sas_decision);
+ if slot.is_some() {
+ return Err(Error::Denied);
+ }
let (tx, rx) = oneshot::channel();
- *lock(&self.sas_decision) = Some((peer, tx));
- rx
+ *slot = Some((peer, tx));
+ Ok(rx)
}
fn clear_decision(&self) {
@@ -224,6 +252,7 @@ pub(crate) async fn join_qr(shared: &Arc<Shared>, uri: &PairingUri) -> Result<()
/// mode. The 6-digit code arrives as [`PairingEvent::SasCode`]; answer with
/// [`crate::Node::pairing_confirm`].
pub(crate) async fn start_nearby(shared: &Arc<Shared>, peer: DeviceId) -> Result<()> {
+ let _nearby = shared.pairing.begin_nearby().ok_or(Error::Denied)?;
let conn = dial(shared, &peer).await?;
let result = async {
let (mut send, mut recv) = conn.open_bi().await.map_err(crate::error::net)?;
@@ -295,9 +324,18 @@ pub(crate) async fn accept(shared: Arc<Shared>, conn: Connection) {
let first = recv_env(&mut recv, STEP_TIMEOUT).await?;
let device = match first.t.as_str() {
types::PAIR_REQUEST => accept_qr(&shared, peer, first, &mut send).await?,
- types::PAIR_COMMIT => accept_nearby(&shared, peer, first, &mut send, &mut recv)
- .await
- .map_err(|e| fail(&shared, e))?,
+ types::PAIR_COMMIT => match accept_nearby(&shared, peer, first, &mut send, &mut recv).await {
+ Ok(Some(device)) => device,
+ Ok(None) => return Err(Error::Denied),
+ Err(e) => {
+ let ended = shared.pairing.record_failure();
+ let err = fail(&shared, e);
+ if ended && !matches!(err, Error::Denied) {
+ shared.emit(NodeEvent::Pairing(PairingEvent::Failed(PairingFailure::Rejected)));
+ }
+ return Err(err);
+ }
+ },
other => {
let reply = Envelope::error(ErrorCode::Unsupported, format!("unexpected {other}"));
send_env(&mut send, reply).await?;
@@ -357,7 +395,15 @@ async fn accept_nearby(
env: Envelope,
send: &mut SendStream,
recv: &mut RecvStream,
-) -> Result<DeviceInfo> {
+) -> Result<Option<DeviceInfo>> {
+ if !shared.pairing.is_hosting() {
+ send_env(send, Envelope::error(ErrorCode::Denied, "pairing mode ended")).await?;
+ return Ok(None);
+ }
+ let Some(_nearby) = shared.pairing.begin_nearby() else {
+ send_env(send, Envelope::error(ErrorCode::Busy, "another pairing is in progress")).await?;
+ return Ok(None);
+ };
let commit: PairCommit = env.body()?;
let n_b: [u8; NONCE_LEN] = rand::random();
let nonce = PairNonce { device: local_device(shared), n_b: n_b.to_vec() };
@@ -372,7 +418,7 @@ async fn accept_nearby(
let code = proto::sas_code(&reveal.n_a, &n_b, &peer, &shared.id);
exchange_decisions(shared, peer, code, send, recv, Role::Host).await?;
shared.pairing.end_host();
- Ok(commit.device)
+ Ok(Some(commit.device))
}
// ---- Code comparison ----
@@ -396,7 +442,7 @@ async fn exchange_decisions(
recv: &mut RecvStream,
role: Role,
) -> Result<()> {
- let decision = shared.pairing.await_decision(peer);
+ let decision = shared.pairing.await_decision(peer)?;
shared.emit(NodeEvent::Pairing(PairingEvent::SasCode { peer, code }));
let mut decision = Box::pin(tokio::time::timeout(SAS_DECISION_TIMEOUT, decision));
@@ -493,4 +539,22 @@ mod tests {
assert_eq!(picked, ["192.168.31.121:5000", "100.64.0.1:5000", "[2409:40d2::1]:5000"]);
assert!(link_addrs(Vec::new()).is_empty());
}
+
+ #[test]
+ fn second_nearby_ceremony_is_refused_without_clobbering_decision() {
+ let state = PairingState::default();
+ let guard = state.begin_nearby().expect("first nearby starts");
+ assert!(state.begin_nearby().is_none(), "concurrent nearby is refused");
+
+ let peer_a = DeviceId([1; 32]);
+ let peer_b = DeviceId([2; 32]);
+ let mut rx = state.await_decision(peer_a).expect("first decision registered");
+ assert!(matches!(state.await_decision(peer_b), Err(Error::Denied)));
+
+ state.decide(true).expect("decision delivered to first ceremony");
+ assert_eq!(rx.try_recv(), Ok(true));
+
+ drop(guard);
+ assert!(state.begin_nearby().is_some(), "slot released after guard drops");
+ }
}
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 2cccf39..2b8da35 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -292,12 +292,38 @@ async fn reader(session: &Arc<Session>, mut recv: RecvStream, shared: &Weak<Shar
continue;
}
let Some(shared) = shared.upgrade() else { return };
- if let Err(e) = handle(&shared, session, env).await {
+ if is_background_rpc(&env.t) {
+ let session = session.clone();
+ tokio::spawn(async move {
+ if let Err(e) = handle(&shared, &session, env).await {
+ tracing::warn!(peer = %session.peer.short(), error = %e, "failed to handle message");
+ }
+ });
+ } else if let Err(e) = handle(&shared, session, env).await {
tracing::warn!(peer = %session.peer.short(), error = %e, "failed to handle message");
}
}
}
+/// Requests that can take a while (the phone's user or apps, a whole photo
+/// to send) run on a task of their own so they never stall the control
+/// stream (heartbeats, and other messages). Ones whose order matters
+/// (clipboard, media and call commands: pause after play, unmute after
+/// mute) stay in order on the stream.
+fn is_background_rpc(t: &str) -> bool {
+ matches!(
+ t,
+ types::DEVICE_RING
+ | types::NOTIFY_DISMISS
+ | types::NOTIFY_ACTION
+ | types::PC_POWER
+ | types::LINK_OPEN
+ | types::PHOTOS_GET
+ | types::MIRROR_START
+ | types::MIRROR_APPS
+ )
+}
+
/// Handles one incoming message that isn't a reply.
async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) -> Result<()> {
let peer = session.peer;
@@ -333,11 +359,16 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
}
types::DEVICE_RING => {
let ring: Ring = env.body()?;
- if ring.on {
- shared.platform.start_ringing();
- } else {
- shared.platform.stop_ringing();
- }
+ let platform = shared.platform.clone();
+ let on = ring.on;
+ let _ = tokio::task::spawn_blocking(move || {
+ if on {
+ platform.start_ringing();
+ } else {
+ platform.stop_ringing();
+ }
+ })
+ .await;
shared.emit(NodeEvent::Ring { device: peer, on: ring.on });
session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;
}
@@ -365,11 +396,20 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
Ok(())
}
+/// Concurrent incoming data streams allowed from one peer at a time.
+const MAX_INCOMING_STREAMS: usize = 32;
+
/// Streams the other device opens (file transfers), each handled on its own.
async fn streams(session: &Arc<Session>, shared: &Weak<Shared>) {
+ let limit = Arc::new(tokio::sync::Semaphore::new(MAX_INCOMING_STREAMS));
while let Ok((send, recv)) = session.conn.accept_bi().await {
let Some(shared) = shared.upgrade() else { return };
- tokio::spawn(crate::transfer::accept_stream(shared, session.clone(), send, recv));
+ let Ok(permit) = limit.clone().acquire_owned().await else { return };
+ let session = session.clone();
+ tokio::spawn(async move {
+ crate::transfer::accept_stream(shared, session, send, recv).await;
+ drop(permit);
+ });
}
}
diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rs
index e6e4802..823afb1 100644
--- a/core/nectarlink-core/src/transfer.rs
+++ b/core/nectarlink-core/src/transfer.rs
@@ -589,7 +589,7 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut
if !shared.toggle_on(&peer, TOGGLE) {
return refuse(&mut send, ErrorCode::Denied, "files are off for this device").await;
}
- let dir = shared.incoming_dir().join(&offer.id);
+ let dir = shared.incoming_dir().join(peer.to_string()).join(&offer.id);
if let Err(e) = tokio::fs::create_dir_all(&dir).await {
tracing::warn!(error = %e, "can't store incoming files");
return refuse(&mut send, ErrorCode::Internal, "can't store files").await;
@@ -638,6 +638,9 @@ async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut
Err(state) => {
if state == TransferState::Cancelled {
let _ = tokio::fs::remove_dir_all(&dir).await;
+ if let Some(parent) = dir.parent() {
+ let _ = tokio::fs::remove_dir(parent).await;
+ }
}
state
}
@@ -811,6 +814,9 @@ async fn store(
}
}
let _ = std::fs::remove_dir_all(&dir);
+ if let Some(parent) = dir.parent() {
+ let _ = std::fs::remove_dir(parent);
+ }
Ok(saved)
})
.await
@@ -819,15 +825,30 @@ async fn store(
/// Deletes partly received files nobody resumed in time.
pub(crate) fn clean_incoming(dir: &Path) {
- let Ok(entries) = std::fs::read_dir(dir) else { return };
- for entry in entries.flatten() {
- let stale = entry
+ let is_stale = |entry: &std::fs::DirEntry| {
+ entry
.metadata()
.and_then(|m| m.modified())
- .is_ok_and(|t| t.elapsed().unwrap_or_default() > KEEP_PARTIAL);
- if stale {
- let _ = std::fs::remove_dir_all(entry.path());
+ .is_ok_and(|t| t.elapsed().unwrap_or_default() > KEEP_PARTIAL)
+ };
+ let Ok(peers) = std::fs::read_dir(dir) else { return };
+ for peer in peers.flatten() {
+ let path = peer.path();
+ // Transfers from before they were kept per peer: `incoming/<offer>`.
+ if peer.file_name().to_str().and_then(|n| n.parse::<DeviceId>().ok()).is_none() {
+ if is_stale(&peer) {
+ let _ = std::fs::remove_dir_all(&path);
+ }
+ continue;
+ }
+ if let Ok(offers) = std::fs::read_dir(&path) {
+ for offer in offers.flatten() {
+ if is_stale(&offer) {
+ let _ = std::fs::remove_dir_all(offer.path());
+ }
+ }
}
+ let _ = std::fs::remove_dir(&path);
}
}
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index f8f306b..0dba41c 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -37,6 +37,8 @@ struct RecordingPlatform {
screen: Arc<ScreenSink>,
/// Photos `open_photo` finds, by ID.
photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,
+ /// Optional barrier `open_photo` waits on to simulate a slow platform call.
+ photo_barrier: Mutex<Option<Arc<std::sync::Barrier>>>,
}
impl Platform for RecordingPlatform {
@@ -168,6 +170,11 @@ impl Platform for RecordingPlatform {
Ok(())
}
fn open_photo(&self, id: &str) -> Result<OutgoingFile, String> {
+ let barrier = self.photo_barrier.lock().unwrap().clone();
+ if let Some(barrier) = barrier {
+ barrier.wait();
+ barrier.wait();
+ }
let path = self.photos.lock().unwrap().get(id).cloned().ok_or("gone")?;
let name = path.file_name().unwrap().to_string_lossy().into_owned();
Ok(OutgoingFile { name, folder: None, source: FileSource::Path(path) })
@@ -477,6 +484,52 @@ async fn nearby_pairing_fails_if_either_user_declines() {
assert!(phone.node.paired_devices().unwrap().is_empty());
}
+#[tokio::test(flavor = "multi_thread")]
+async fn second_nearby_pairing_is_refused_while_one_awaits_confirmation() {
+ let (mut pc, mut phone_a, addrs) = start_nearby_setup().await;
+ let pc_id = pc.node.device_id();
+ let phone_b = device("Other", DeviceKind::Phone).await;
+ phone_b.node.add_known_addrs(pc_id, &addrs);
+
+ let initiator_a = phone_a.node.clone();
+ let task_a = tokio::spawn(async move { initiator_a.pairing_start_nearby(pc_id).await });
+ let (code_a, code_pc) = (sas_code(&mut phone_a).await, sas_code(&mut pc).await);
+ assert_eq!(code_a, code_pc);
+
+ // A second phone tries to pair while the PC is waiting for the user to
+ // confirm the first phone's 6-digit code.
+ let second = with_timeout("second nearby", phone_b.node.pairing_start_nearby(pc_id)).await;
+ assert!(matches!(second, Err(Error::Denied)), "second ceremony is refused: {second:?}");
+
+ // The first ceremony's decision channel is untouched and still completes.
+ phone_a.node.pairing_confirm(true).unwrap();
+ pc.node.pairing_confirm(true).unwrap();
+ with_timeout("first nearby", task_a).await.unwrap().expect("first pairing succeeds");
+ assert_eq!(pc.node.paired_devices().unwrap().len(), 1);
+ assert_eq!(pc.node.paired_devices().unwrap()[0].id, phone_a.node.device_id());
+ assert!(phone_b.node.paired_devices().unwrap().is_empty());
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn too_many_failed_nearby_attempts_end_pairing_mode() {
+ let (mut pc, mut phone, _) = start_nearby_setup().await;
+ let pc_id = pc.node.device_id();
+ for _ in 0..5 {
+ let initiator = phone.node.clone();
+ let task = tokio::spawn(async move { initiator.pairing_start_nearby(pc_id).await });
+ sas_code(&mut phone).await;
+ sas_code(&mut pc).await;
+ phone.node.pairing_confirm(false).unwrap();
+ let _ = with_timeout("nearby attempt", task).await.unwrap();
+ wait_for(&mut pc, "attempt failed", |e| match e {
+ NodeEvent::Pairing(PairingEvent::Failed(_)) => Some(()),
+ _ => None,
+ })
+ .await;
+ }
+ assert!(!pc.node.is_pairing(), "pairing mode ends after 5 failed nearby attempts");
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn unpairing_is_mirrored_on_the_other_device() {
let mut pc = device("Desktop", DeviceKind::Desktop).await;
@@ -1498,7 +1551,10 @@ async fn transfers_resume_after_the_receiver_restarts() {
phone.node.shutdown().await;
let TestDevice { node, dir, .. } = phone;
drop(node);
- let interrupted = std::fs::metadata(dir.path().join("incoming").join(&id).join("0.part")).unwrap().len();
+ let interrupted =
+ std::fs::metadata(dir.path().join("incoming").join(pc_id.to_string()).join(&id).join("0.part"))
+ .unwrap()
+ .len();
assert!(interrupted >= before && interrupted < big.len() as u64, "{interrupted} of {}", big.len());
wait_transfer(&mut pc, &id, "waiting for the phone", |t| {
(t.state == TransferState::Waiting).then_some(())
@@ -1516,3 +1572,54 @@ async fn transfers_resume_after_the_receiver_restarts() {
wait_transfer(&mut pc, &id, "sent", saved).await;
let _ = pc_id;
}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn slow_rpc_does_not_block_control_stream() {
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::PHOTOS_SHOW]).await;
+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::PHOTOS_READ]).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let phone_id = phone.node.device_id();
+
+ let file = phone.dir.path().join("IMG_1.jpg");
+ let pixels = b"jpeg-bytes";
+ std::fs::write(&file, pixels).unwrap();
+ phone.platform.photos.lock().unwrap().insert("media:1".into(), file);
+ let photo = nectarlink_core::Photo {
+ id: "media:1".into(),
+ name: "IMG_1.jpg".into(),
+ size: pixels.len() as u64,
+ taken: 1_790_000_000,
+ screenshot: true,
+ thumb: vec![0xff, 0xd8, 0xff],
+ };
+ phone.node.photo_taken(photo).await.unwrap();
+ wait_for(&mut pc, "the photo", |e| match e {
+ NodeEvent::PhotoAdded { device, .. } if *device == phone_id => Some(()),
+ _ => None,
+ })
+ .await;
+
+ let barrier = Arc::new(std::sync::Barrier::new(2));
+ *phone.platform.photo_barrier.lock().unwrap() = Some(barrier.clone());
+
+ let pc_node = pc.node.clone();
+ let get_task = tokio::spawn(async move { pc_node.fetch_photo(phone_id, "media:1".into()).await });
+
+ // Wait until the phone's `open_photo` is blocked inside `photos.get`.
+ tokio::task::spawn_blocking({
+ let barrier = barrier.clone();
+ move || barrier.wait()
+ })
+ .await
+ .unwrap();
+
+ // While `photos.get` is stuck, another control-stream RPC still completes.
+ with_timeout("ring while photos.get is blocked", pc.node.ring(phone_id, true))
+ .await
+ .expect("ring succeeds without waiting for photos.get");
+
+ // Release `open_photo` so `photos.get` finishes cleanly.
+ tokio::task::spawn_blocking(move || barrier.wait()).await.unwrap();
+ let transfer_id = with_timeout("photos.get finishes", get_task).await.unwrap().expect("photo sent");
+ wait_transfer(&mut pc, &transfer_id, "photo received", saved).await;
+}
diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cpp
index 36ebabb..1f6ee78 100644
--- a/desktop/app/cpp/native_window.cpp
+++ b/desktop/app/cpp/native_window.cpp
@@ -239,6 +239,7 @@ bool NativeWindow::nativeEvent(const QByteArray &eventType, void *message, qintp
*result = 0;
return true;
}
+ setMaximizeState(false, false);
break;
default:
break;
diff --git a/desktop/app/qml/MirrorWindow.qml b/desktop/app/qml/MirrorWindow.qml
index 1fc5742..22cf17c 100644
--- a/desktop/app/qml/MirrorWindow.qml
+++ b/desktop/app/qml/MirrorWindow.qml
@@ -234,12 +234,7 @@ Window {
visible: win.phase === "ended" && !win.info.app
variant: "tonal"
text: qsTr("Try again")
- // A new window takes this one's place.
- onClicked: {
- const device = win.info.device
- Mirror.stop(win.mirrorKey)
- Mirror.start(device)
- }
+ onClicked: Mirror.start(win.info.device)
}
}
}
diff --git a/desktop/app/qml/components/LockChip.qml b/desktop/app/qml/components/LockChip.qml
index 0fd0dcd..f5df06b 100644
--- a/desktop/app/qml/components/LockChip.qml
+++ b/desktop/app/qml/components/LockChip.qml
@@ -7,33 +7,48 @@ import app.nectarlink
Rectangle {
id: chip
property var feature: ({})
+ property real maxWidth: parent ? parent.width : 0
- readonly property string label: {
+ readonly property string shortLabel: {
const s = feature || {}
- let what = ""
switch (s.action) {
- case "raisePower": what = s.target === "elevated" ? qsTr("Elevated") : qsTr("Assist"); break
+ case "raisePower": return s.target === "elevated" ? qsTr("Elevated") : qsTr("Assist")
case "grantPermission":
- what = feature.target === "notification_access" ? qsTr("Allow notification access on the phone")
- : qsTr("Allow it on the phone")
- break
- case "enableAddon": what = qsTr("Add-on"); break
- case "enablePath": what = qsTr("Away mode"); break
- case "enableToggle": what = qsTr("Turned off"); break
- case "updateApp": what = qsTr("Update app"); break
- default: what = s.state === "unsupported" ? qsTr("Not available") : ""
+ return s.target === "notification_access" ? qsTr("Allow notification access on the phone")
+ : qsTr("Allow it on the phone")
+ case "enableAddon": return qsTr("Add-on")
+ case "enablePath": return qsTr("Away mode")
+ case "enableToggle": return qsTr("Turned off")
+ case "updateApp": return qsTr("Update app")
+ default: return s.state === "unsupported" ? qsTr("Not available") : ""
}
- return s.minutes > 0 ? qsTr("%1 · ~%2 min").arg(what).arg(s.minutes) : what
}
+ readonly property string label: {
+ const s = feature || {}
+ return shortLabel.length > 0 && s.minutes > 0
+ ? qsTr("%1 · ~%2 min").arg(shortLabel).arg(s.minutes)
+ : shortLabel
+ }
+ readonly property string shownLabel: maxWidth > 0 && fullMeasure.implicitWidth + 34 > maxWidth
+ ? shortLabel
+ : label
visible: label.length > 0
implicitHeight: 22
- implicitWidth: row.implicitWidth + 16
+ implicitWidth: textItem.implicitWidth + 34
+ width: maxWidth > 0 ? Math.min(implicitWidth, maxWidth) : implicitWidth
radius: Theme.pill(height)
color: "transparent"
border.width: 1
border.color: Theme.outlineVariant
+ Txt {
+ id: fullMeasure
+ visible: false
+ text: chip.label
+ role: "caption"
+ }
+
Row {
id: row
anchors.centerIn: parent
@@ -45,10 +60,13 @@ Rectangle {
color: Theme.surfaceContentVariant
}
Txt {
+ id: textItem
anchors.verticalCenter: parent.verticalCenter
- text: chip.label
+ width: Math.min(implicitWidth, Math.max(0, chip.width - 34))
+ text: chip.shownLabel
role: "caption"
muted: true
+ elide: Text.ElideRight
}
}
}
diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rs
index e7e68b0..cdb5fb0 100644
--- a/desktop/app/src/messages.rs
+++ b/desktop/app/src/messages.rs
@@ -440,15 +440,17 @@ pub fn send(body: String) {
/// Sends a text to a number (a new conversation), then opens it.
pub fn send_to(to: Vec<String>, body: String) {
+ static NEXT_LOCAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
+ let now = now_ms();
+ let local_id = format!("local:{now}:{}", NEXT_LOCAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let Some(device) = state(|s| {
s.sending = true;
// Shown at once as "Sending…"; the phone's copy replaces it.
if let Some(thread) = s.thread.clone() {
- let now = now_ms();
s.messages.insert(
0,
SmsMessage {
- id: format!("local:{now}"),
+ id: local_id.clone(),
thread,
address: to.join(", "),
body: body.clone(),
@@ -471,7 +473,7 @@ pub fn send_to(to: Vec<String>, body: String) {
s.sending = false;
if result.is_err() {
// Not sent: say so on it.
- for m in s.messages.iter_mut().filter(|m| m.id.starts_with("local:")) {
+ if let Some(m) = s.messages.iter_mut().find(|m| m.id == local_id) {
m.status = Some("failed".into());
}
}
diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rs
index 8b1bfa9..c3da0b6 100644
--- a/desktop/app/src/mirror.rs
+++ b/desktop/app/src/mirror.rs
@@ -167,6 +167,7 @@ pub fn windows() -> Vec<(Window, Shown)> {
/// Asks the phone for its screen.
pub fn start(device: DeviceId) {
let window = Window::screen(device);
+ ffi::video_clear(&window.key());
state(|s| s.windows.insert(window, Shown { phase: Phase::Asking, app: None, pkg: None }));
request(window, OPTIONS);
}
diff --git a/desktop/app/src/send_to.rs b/desktop/app/src/send_to.rs
index 0891418..47e3f89 100644
--- a/desktop/app/src/send_to.rs
+++ b/desktop/app/src/send_to.rs
@@ -51,7 +51,8 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
static MANAGED: AtomicBool = AtomicBool::new(false);
/// The "Show your phones in Send to" preference.
static ENABLED: AtomicBool = AtomicBool::new(true);
-/// The devices the shortcuts were last made for.
+/// The devices the shortcuts should currently be made for, and what was last applied.
+static DESIRED: Mutex<Option<Vec<(DeviceId, String)>>> = Mutex::new(None);
static APPLIED: Mutex<Option<Vec<(DeviceId, String)>>> = Mutex::new(None);
/// One update of the folder at a time.
static UPDATING: Mutex<()> = Mutex::new(());
@@ -85,19 +86,29 @@ fn sync() {
desired.clear();
}
{
- let mut applied = lock(&APPLIED);
- if applied.as_ref() == Some(&desired) {
+ let mut target = lock(&DESIRED);
+ if target.as_ref() == Some(&desired) && lock(&APPLIED).as_ref() == Some(&desired) {
return;
}
- *applied = Some(desired.clone());
+ *target = Some(desired);
}
- let spawned = std::thread::Builder::new().name("send-to".into()).spawn(move || {
+ let spawned = std::thread::Builder::new().name("send-to".into()).spawn(|| {
let _one = lock(&UPDATING);
let (Some(dir), Ok(exe)) = (shortcut::send_to_dir(), std::env::current_exe()) else { return };
- if let Err(e) = reconcile(&dir, &desired, &exe) {
- tracing::warn!(error = %e, "can't update the Send to menu");
- // Try again on the next change.
- *lock(&APPLIED) = None;
+ loop {
+ let next = lock(&DESIRED).clone();
+ let Some(desired) = next else { return };
+ if lock(&APPLIED).as_ref() == Some(&desired) {
+ return;
+ }
+ match reconcile(&dir, &desired, &exe) {
+ Ok(()) => *lock(&APPLIED) = Some(desired),
+ Err(e) => {
+ tracing::warn!(error = %e, "can't update the Send to menu");
+ *lock(&APPLIED) = None;
+ return;
+ }
+ }
}
});
if let Err(e) = spawned {
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index ea44727..4d81cbf 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -616,7 +616,7 @@ impl AppState {
/// refresh on the Qt thread and returns false once the object is gone.
struct Listener {
interest: Changes,
- notify: Box<dyn Fn() -> bool + Send + Sync>,
+ notify: Arc<dyn Fn() -> bool + Send + Sync>,
}
/// The shared state plus the listeners to tell about changes.
@@ -656,7 +656,7 @@ impl Hub {
/// Registers a listener; it is called right away so it starts in sync.
pub fn subscribe(&self, interest: Changes, notify: impl Fn() -> bool + Send + Sync + 'static) {
if notify() {
- lock(&self.listeners).push(Listener { interest, notify: Box::new(notify) });
+ lock(&self.listeners).push(Listener { interest, notify: Arc::new(notify) });
}
}
@@ -666,7 +666,20 @@ impl Hub {
}
fn notify(&self, changes: Changes) {
- lock(&self.listeners).retain(|l| !l.interest.intersects(changes) || (l.notify)());
+ let active: Vec<_> = lock(&self.listeners)
+ .iter()
+ .filter(|l| l.interest.intersects(changes))
+ .map(|l| l.notify.clone())
+ .collect();
+ let mut gone = Vec::new();
+ for f in active {
+ if !f() {
+ gone.push(Arc::as_ptr(&f) as *const () as usize);
+ }
+ }
+ if !gone.is_empty() {
+ lock(&self.listeners).retain(|l| !gone.contains(&(Arc::as_ptr(&l.notify) as *const () as usize)));
+ }
}
}
diff --git a/desktop/app/src/updater.rs b/desktop/app/src/updater.rs
index 7f91ff2..f76e88c 100644
--- a/desktop/app/src/updater.rs
+++ b/desktop/app/src/updater.rs
@@ -149,9 +149,16 @@ fn latest() -> Result<Option<Update>, String> {
Ok(newer_release(release, env!("CARGO_PKG_VERSION")))
}
-/// The release as an update, if it's a newer published one with an x64
-/// installer and its sums.
+const INSTALLER_SUFFIX: &str =
+ if cfg!(target_arch = "aarch64") { "-arm64-setup.exe" } else { "-x64-setup.exe" };
+
+/// The release as an update, if it's a newer published one with an
+/// installer for this architecture and its sums.
fn newer_release(release: Release, current: &str) -> Option<Update> {
+ newer_release_for(release, current, INSTALLER_SUFFIX)
+}
+
+fn newer_release_for(release: Release, current: &str, suffix: &str) -> Option<Update> {
if release.draft || release.prerelease {
return None;
}
@@ -159,7 +166,7 @@ fn newer_release(release: Release, current: &str) -> Option<Update> {
if !is_newer(&version, current) {
return None;
}
- let installer = release.assets.iter().find(|a| a.name.ends_with("-x64-setup.exe"))?;
+ let installer = release.assets.iter().find(|a| a.name.ends_with(suffix))?;
let sums = release.assets.iter().find(|a| a.name == "SHA256SUMS.txt")?;
Some(Update {
version,
@@ -259,6 +266,10 @@ mod tests {
name: "Nectarlink-9.0.0-x64-setup.exe".into(),
browser_download_url: "https://x/setup".into(),
},
+ Asset {
+ name: "Nectarlink-9.0.0-arm64-setup.exe".into(),
+ browser_download_url: "https://x/setup-arm64".into(),
+ },
Asset { name: "SHA256SUMS.txt".into(), browser_download_url: "https://x/sums".into() },
],
}
@@ -266,8 +277,13 @@ mod tests {
#[test]
fn releases_become_updates_when_newer_and_complete() {
- let update = newer_release(release("v9.0.0"), "0.0.1").unwrap();
- assert_eq!((update.version.as_str(), update.installer_url.as_str()), ("9.0.0", "https://x/setup"));
+ let x64 = newer_release_for(release("v9.0.0"), "0.0.1", "-x64-setup.exe").unwrap();
+ assert_eq!((x64.version.as_str(), x64.installer_url.as_str()), ("9.0.0", "https://x/setup"));
+ let arm64 = newer_release_for(release("v9.0.0"), "0.0.1", "-arm64-setup.exe").unwrap();
+ assert_eq!(
+ (arm64.installer_name.as_str(), arm64.installer_url.as_str()),
+ ("Nectarlink-9.0.0-arm64-setup.exe", "https://x/setup-arm64")
+ );
assert!(newer_release(release("v0.0.1"), "0.0.1").is_none());
let mut draft = release("v9.0.0");
draft.prerelease = true;
diff --git a/desktop/app/src/win/h264.rs b/desktop/app/src/win/h264.rs
index cbabeae..4bee853 100644
--- a/desktop/app/src/win/h264.rs
+++ b/desktop/app/src/win/h264.rs
@@ -12,9 +12,10 @@ use windows::{
MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE, MF_LOW_LATENCY, MF_MT_FRAME_SIZE,
MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE, MF_MT_VIDEO_NOMINAL_RANGE, MF_MT_YUV_MATRIX, MF_VERSION,
MFCreateMediaType, MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFNominalRange_0_255,
- MFSTARTUP_NOSOCKET, MFStartup, MFT_MESSAGE_COMMAND_FLUSH, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,
- MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER, MFT_OUTPUT_STREAM_PROVIDES_SAMPLES,
- MFVideoFormat_H264, MFVideoFormat_NV12, MFVideoTransferMatrix_BT601,
+ MFSTARTUP_NOSOCKET, MFShutdown, MFStartup, MFT_MESSAGE_COMMAND_FLUSH,
+ MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER,
+ MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFVideoFormat_H264, MFVideoFormat_NV12,
+ MFVideoTransferMatrix_BT601,
},
System::Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx},
},
@@ -56,6 +57,26 @@ impl Colors {
}
}
+/// Media Foundation, started for as long as a decoder lives.
+struct MfGuard;
+
+impl MfGuard {
+ fn start() -> windows::core::Result<Self> {
+ // SAFETY: plain Media Foundation startup call.
+ unsafe { MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET)? };
+ Ok(Self)
+ }
+}
+
+impl Drop for MfGuard {
+ fn drop(&mut self) {
+ // SAFETY: paired with the `MFStartup` in `MfGuard::start`.
+ unsafe {
+ let _ = MFShutdown();
+ }
+ }
+}
+
pub struct Decoder {
transform: IMFTransform,
/// The decoded size, as the output type says (padded).
@@ -63,6 +84,7 @@ pub struct Decoder {
provides_samples: bool,
output_size: u32,
colors: Colors,
+ _mf: MfGuard,
}
impl std::fmt::Debug for Decoder {
@@ -77,7 +99,7 @@ impl Decoder {
// SAFETY: plain COM and Media Foundation calls with owned values.
unsafe {
let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
- MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET)?;
+ let mf = MfGuard::start()?;
let transform: IMFTransform =
CoCreateInstance(&CLSID_MSH264DecoderMFT, None, CLSCTX_INPROC_SERVER)?;
// One picture in, one out: no reordering delay.
@@ -94,6 +116,7 @@ impl Decoder {
provides_samples: false,
output_size: 0,
colors: Colors::default(),
+ _mf: mf,
};
decoder.choose_output()?;
decoder.transform.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)?;
@@ -243,7 +266,9 @@ fn sample_of(data: &[u8], time_us: u64) -> windows::core::Result<IMFSample> {
}
/// NV12 (in the picture's own colors) to 32-bit BGRX, the
-/// visible `width` x `height`, across a few threads.
+/// visible `width` x `height`, across a few threads. A 1080p picture
+/// takes about 16 ms on one core, too long at 60 frames a second; scoped
+/// threads cost microseconds next to that.
pub fn to_bgrx(picture: &Picture, width: u32, height: u32) -> Vec<u8> {
let (w, h) = (width.min(picture.width) as usize, height.min(picture.height) as usize);
let mut out = vec![0u8; w * h * 4];