From 3cc9565fab907fc1c8d81b465e689ae1df6472ad Mon Sep 17 00:00:00 2001 From: bit9992 <84845600+bit9992@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:03:35 +0300 Subject: [PATCH] Fix Android file lock portability and NativeActivity window insets --- Cargo.lock | 1 + core/Cargo.toml | 3 ++ core/src/file_lock.rs | 51 +++++++++++++++++++ core/src/lib.rs | 1 + core/src/locks.rs | 2 +- core/src/profile.rs | 8 +-- docs/mobile-port-assessment.md | 14 +++-- docs/mobile-port-progress.md | 22 ++++++++ native/src/services/prefs.rs | 5 +- native/src/services/profile.rs | 5 +- native/src/services/profile_import.rs | 7 ++- native/src/services/secrets/transaction.rs | 2 +- .../teamspeach/mobile/TeamsPeachActivity.java | 23 ++++----- 13 files changed, 119 insertions(+), 25 deletions(-) create mode 100644 core/src/file_lock.rs diff --git a/Cargo.lock b/Cargo.lock index 5b686d2..4d526d0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7475,6 +7475,7 @@ dependencies = [ "base64 0.22.1", "dbus", "earshot", + "fs2", "futures", "md-5", "num-traits", diff --git a/core/Cargo.toml b/core/Cargo.toml index fb5b8b1..29ef619 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -34,6 +34,9 @@ tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync" tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] } +[target.'cfg(target_os = "android")'.dependencies] +fs2 = "=0.4.3" + [target.'cfg(windows)'.dependencies] windows-core = "0.62.2" windows = { version = "0.62.2", features = [ diff --git a/core/src/file_lock.rs b/core/src/file_lock.rs new file mode 100644 index 0000000..815b80d --- /dev/null +++ b/core/src/file_lock.rs @@ -0,0 +1,51 @@ +//! Descriptor-owned advisory locks. Rust 1.96 std lacks Android flock support. +//! Other platforms keep std semantics; dropping the File releases the lock. +use std::{fs::{File, TryLockError}, io}; + +pub fn lock(file: &File, shared: bool) -> io::Result<()> { + #[cfg(target_os = "android")] + { if shared { fs2::FileExt::lock_shared(file) } else { fs2::FileExt::lock_exclusive(file) } } + #[cfg(not(target_os = "android"))] + { if shared { file.lock_shared() } else { file.lock() } } +} + +pub fn try_lock(file: &File, shared: bool) -> Result<(), TryLockError> { + #[cfg(target_os = "android")] + { + let result = if shared { fs2::FileExt::try_lock_shared(file) } else { fs2::FileExt::try_lock_exclusive(file) }; + result.map_err(|error| if error.kind() == io::ErrorKind::WouldBlock { + TryLockError::WouldBlock + } else { TryLockError::Error(error) }) + } + #[cfg(not(target_os = "android"))] + { if shared { file.try_lock_shared() } else { file.try_lock() } } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{fs::{self, OpenOptions}, sync::atomic::{AtomicU64, Ordering}}; + + #[test] + fn owners_exclude_writers_share_readers_and_release_on_drop() { + static NEXT: AtomicU64 = AtomicU64::new(0); + let path = std::env::temp_dir().join(format!("teamspeach-lock-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed))); + let open = || OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path).unwrap(); + let writer = open(); + try_lock(&writer, false).unwrap(); + let contender = open(); + assert!(matches!(try_lock(&contender, false), Err(TryLockError::WouldBlock))); + assert!(matches!(try_lock(&contender, true), Err(TryLockError::WouldBlock))); + drop(writer); + lock(&contender, true).unwrap(); + let reader = open(); + try_lock(&reader, true).unwrap(); + let next_writer = open(); + assert!(matches!(try_lock(&next_writer, false), Err(TryLockError::WouldBlock))); + drop(reader); + drop(contender); + try_lock(&next_writer, false).unwrap(); + drop(next_writer); + fs::remove_file(path).unwrap(); + } +} diff --git a/core/src/lib.rs b/core/src/lib.rs index ac28d3e..6771e08 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -3,6 +3,7 @@ pub mod admin; pub mod app_audio; pub mod audio; mod events; +pub mod file_lock; pub mod file_transfer; pub mod hotkeys; mod keyfmt; diff --git a/core/src/locks.rs b/core/src/locks.rs index 4270bfb..600b094 100644 --- a/core/src/locks.rs +++ b/core/src/locks.rs @@ -8,7 +8,7 @@ pub fn lock_dir(dir: &Path, shared: bool) -> Result { let path = dir.join("core.lock"); let file = OpenOptions::new().create(true).truncate(false).write(true).open(&path) .map_err(|e| format!("cannot open {}: {e}", path.display()))?; - match if shared { file.try_lock_shared() } else { file.try_lock() } { + match crate::file_lock::try_lock(&file, shared) { Ok(()) => Ok(file), Err(TryLockError::WouldBlock) => Err(format!("data dir {} is in use by another teamspeach-core", dir.display())), Err(TryLockError::Error(e)) => Err(format!("cannot lock {}: {e}", path.display())), diff --git a/core/src/profile.rs b/core/src/profile.rs index 3020afd..ba2303f 100644 --- a/core/src/profile.rs +++ b/core/src/profile.rs @@ -561,7 +561,7 @@ impl Store { .write(true) .open(&path) .map_err(io_err(format!("opening {}", path.display())))?; - file.lock().map_err(io_err(format!("locking {}", path.display())))?; + crate::file_lock::lock(&file, false).map_err(io_err(format!("locking {}", path.display())))?; Ok(file) } @@ -584,7 +584,7 @@ impl Store { /// True while a connection core holds the identity (informational; delete re-checks). fn in_use(&self, uid: &str) -> bool { let Ok(file) = fs::OpenOptions::new().write(true).open(self.use_path(uid)) else { return false }; - match file.try_lock() { + match crate::file_lock::try_lock(&file, false) { Ok(()) => false, Err(TryLockError::WouldBlock) => true, Err(TryLockError::Error(_)) => false, @@ -674,7 +674,7 @@ impl Store { }; let lock = self.open_use_file(&uid)?; // Blocks only while a delete of this identity holds it exclusively (a few file operations). - lock.lock_shared().map_err(io_err(format!("locking {}", self.use_path(&uid).display())))?; + crate::file_lock::lock(&lock, true).map_err(io_err(format!("locking {}", self.use_path(&uid).display())))?; // A delete that finished while we waited has removed it. let vault = self.load_vault()?; let e = vault.find(&uid).ok_or_else(|| StoreError::NotFound(uid.clone()))?; @@ -833,7 +833,7 @@ impl Store { return Err(StoreError::DeleteRefused("the default identity cannot be deleted; choose another default first".into())); } let guard = self.open_use_file(uid)?; - match guard.try_lock() { + match crate::file_lock::try_lock(&guard, false) { Ok(()) => {} Err(TryLockError::WouldBlock) => return Err(StoreError::InUse), Err(TryLockError::Error(e)) => return Err(io_err(format!("locking {}", self.use_path(uid).display()))(e)), diff --git a/docs/mobile-port-assessment.md b/docs/mobile-port-assessment.md index b18ce48..3973999 100644 --- a/docs/mobile-port-assessment.md +++ b/docs/mobile-port-assessment.md @@ -495,7 +495,15 @@ No Windows/Apple permission policy was relaxed. Added an Android search-only-anc its unit execution and the new APK's runtime result are not yet verified. [TeamsPeachActivity](../platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java) -projects system/IME insets onto the actual rendering surface to avoid consumed child insets and double -subtraction after adjustResize. Slint uses the maximum bottom obstruction. Gesture/three-button and IME -acceptance still require the new phone build; host geometry reasoning is not device acceptance. +must observe the NativeActivity Window, not search for a SurfaceView: run4865 device hierarchy proved +none exists. Slint reads ANativeWindow buffer dimensions; the resized NativeContentView is not that +buffer. Insets now project to decor/native-window coordinates; Slint reserves maximum bottom obstruction. +Keyboard and navigation acceptance require the corrected APK, not the earlier SurfaceView-based build. + +Pinned Rust1.96 [std Unix lock cfg](https://github.com/rust-lang/rust/blob/1.96.0/library/std/src/sys/fs/unix.rs) +omits Android: Unsupported was incorrectly reported as profile contention. The shared +[file_lock boundary](../core/src/file_lock.rs) uses fs2 flock only on Android and unchanged std calls on +other targets; all std file-lock callsites in core/native services migrate through it. Existing secret-store +fs2 locking remains compatible. Windows real contention/shared-reader/drop-release regression passed; +Android runtime proof remains pending. This is platform compatibility, not a phone-specific exception. diff --git a/docs/mobile-port-progress.md b/docs/mobile-port-progress.md index c1ba4c0..92572df 100644 --- a/docs/mobile-port-progress.md +++ b/docs/mobile-port-progress.md @@ -149,6 +149,28 @@ Updated **2026-11-11**. Windows baseline remains `05e8d34bcf0e24a44f76e65220293c matching restores only unchanged input timestamps after mandatory dependency verification. Python syntax, YAML ordering and temporary content/change/directory/clock fixtures passed; Windows fixtures adapted only unsupported no-follow utime, so Linux syscall/cache-service behavior awaits CI. +- Fixes committed/pushed as `fd41389d63ddf059c3e077cd1c1081789233f536`; automatic + [run4865](https://git.eeee.moe/TeamsPeach/client/actions/runs/4865), job5461, started successfully. + Normal release optimization and4 CI jobs retained. New cache-key families need their first completed + checkpoint before a subsequent build can reuse them; existing WebRTC cache remains unchanged. +- Owner explicitly reinforced: fix underlying technical causes and platform contracts, never hardcode + behavior for this phone, resolution, profile or test. Device results are evidence, not the scope of a fix. +- **Run4865 SUCCESS:** normal optimized Android build/package verification, application-cache snapshot/save + and artifact uploads completed. Full download hashes matched; APK SHA256 + `6ffd7feda9c526b8ec4103fdd6f8eb78b6bac4f87b368120f5b0e7bd14471bad` installed after signature mismatch. +- Owner granted standing permission to remove/reinstall this disposable Android test app and its data + when test signatures differ; this does not authorize deleting real profiles or changing other apps. + Also authorized temporary three-button navigation testing with restoration to the original gestures. +- Run4865 device **not accepted**: PermissionDenied was resolved, but Create returned misleading + `The native profile is already open`; pinned Rust1.96 std file locks omit Android and return Unsupported. + `core::file_lock` now uses the already pinned fs2 flock implementation on Android, std elsewhere. + Migrated profile/vault/core/prefs/import/recovery locks, distinguishing actual contention from OS errors. + Real descriptor contention/shared-reader/drop-release regression passed on Windows under5GiB Job Object, + below-normal priority and7/2GiB start/reserve checks; no full Windows rebuild or Android unit execution. +- Run4865 IME still covered actions. Actual NativeActivity hierarchy has NO SurfaceView; Slint uses the + Window's ANativeWindow, while NativeContentView only reports unobscured content. The SurfaceView guard + suppressed all inset updates. Corrected observation/projection to decor/native-window coordinates. + New APK still required to prove keyboard actions, creation and navigation modes end to end. ## First Android APK build diff --git a/native/src/services/prefs.rs b/native/src/services/prefs.rs index ec7df8c..5139787 100644 --- a/native/src/services/prefs.rs +++ b/native/src/services/prefs.rs @@ -154,7 +154,10 @@ impl Prefs { let path=path.as_ref().to_path_buf();let parent=path.parent().filter(|p|!p.as_os_str().is_empty()).ok_or_else(||err("invalid_path","Preference path needs a parent directory"))?; secure_fs::ensure_private_dir(parent)?; let lock=path.with_extension("json.lock");let owner=OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&lock)?; - owner.try_lock().map_err(|_|err("profile_busy","Preferences are already owned by another service"))?; + teamspeach_core::file_lock::try_lock(&owner, false).map_err(|error| match error { + std::fs::TryLockError::WouldBlock => err("profile_busy", "Preferences are already owned by another service"), + std::fs::TryLockError::Error(error) => error.into(), + })?; #[cfg(windows)] secure_fs::win::set_owner_only(&lock)?; #[cfg(unix)] {use std::os::unix::fs::PermissionsExt;fs::set_permissions(&lock,fs::Permissions::from_mode(0o600))?;} require_recovered_bookmark_transaction(&path)?; diff --git a/native/src/services/profile.rs b/native/src/services/profile.rs index 3b02a20..374b450 100644 --- a/native/src/services/profile.rs +++ b/native/src/services/profile.rs @@ -27,7 +27,10 @@ impl ProfileServices { } let path = root.join("native-owner.lock"); let owner = OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&path)?; - owner.try_lock().map_err(|_| ServiceError::new("profile_busy", "The native profile is already open"))?; + teamspeach_core::file_lock::try_lock(&owner, false).map_err(|error| match error { + std::fs::TryLockError::WouldBlock => ServiceError::new("profile_busy", "The native profile is already open"), + std::fs::TryLockError::Error(error) => error.into(), + })?; #[cfg(windows)] teamspeach_core::secure_fs::win::set_owner_only(&path)?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; diff --git a/native/src/services/profile_import.rs b/native/src/services/profile_import.rs index 3098e25..cfa588b 100644 --- a/native/src/services/profile_import.rs +++ b/native/src/services/profile_import.rs @@ -204,7 +204,7 @@ pub fn save_migration(root: &Path, state: &MigrationState) -> Result<()> { /// Caller persists the OS secret first. Failure leaves the re-entry requirement in place. pub fn clear_required_password(root: &Path, bookmark_id: &str, purpose: &str, address: &str) -> Result<()> { let file = OpenOptions::new().write(true).create(true).truncate(false).open(root.join("migration.lock"))?; - file.lock()?; + teamspeach_core::file_lock::lock(&file, false)?; if let Some(mut state) = load_migration(root)? { let before = state.required_passwords.len(); state.required_passwords.retain(|m| !(m.bookmark_id == bookmark_id && m.purpose == purpose && m.address == address.trim())); @@ -420,7 +420,10 @@ impl ConfinedSource { let relative = Path::new(name); if self.metadata(relative)?.is_none() { continue; } let file = self.open_file(relative)?; - file.try_lock().map_err(|_| err("profile_occupied", "Close the legacy client before importing its profile"))?; + teamspeach_core::file_lock::try_lock(&file, false).map_err(|error| match error { + std::fs::TryLockError::WouldBlock => err("profile_occupied", "Close the legacy client before importing its profile"), + std::fs::TryLockError::Error(error) => error.into(), + })?; locks.push(file); } Ok(locks) diff --git a/native/src/services/secrets/transaction.rs b/native/src/services/secrets/transaction.rs index a551ef7..4c107c0 100644 --- a/native/src/services/secrets/transaction.rs +++ b/native/src/services/secrets/transaction.rs @@ -126,7 +126,7 @@ pub(super) fn recover(root: &Path) -> Result<()> { #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } let owner = options.open(&lock_path).map_err(|_| recovery_error())?; - owner.try_lock().map_err(|_| recovery_error())?; + teamspeach_core::file_lock::try_lock(&owner, false).map_err(|_| recovery_error())?; #[cfg(windows)] secure_fs::win::set_owner_only(&lock_path).map_err(|_| recovery_error())?; let bytes = read_bounded(&root.join(JOURNAL), JOURNAL_LIMIT)?.ok_or_else(recovery_error)?; diff --git a/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java b/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java index ceeaf05..0673447 100644 --- a/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java +++ b/platform/android/src/main/java/dev/teamspeach/mobile/TeamsPeachActivity.java @@ -22,9 +22,8 @@ public final class TeamsPeachActivity extends NativeActivity { private SafGrant sharedGrant; private android.net.Uri installerUri; private int requestedPermission; - private SurfaceView renderSurface; private final Rect insetWindow = new Rect(), visibleWindow = new Rect(); - private final int[] decorLocation = new int[2], surfaceLocation = new int[2]; + private final int[] decorLocation = new int[2]; private final ViewTreeObserver.OnGlobalLayoutListener insetLayout = this::reportInsets; private int insetTop, insetRight, insetBottom, insetLeft, insetKeyboard; private float insetScale; @@ -46,9 +45,9 @@ public final class TeamsPeachActivity extends NativeActivity { getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(insetLayout); } private void reportInsets() { - if (generation == 0 || renderSurface == null || !renderSurface.isAttachedToWindow() - || renderSurface.getWidth() == 0 || renderSurface.getHeight() == 0) return; View decor = getWindow().getDecorView(); + if (generation == 0 || !decor.isAttachedToWindow() + || decor.getWidth() == 0 || decor.getHeight() == 0) return; // A child receives consumed insets on some ROMs. The root retains the IME state. WindowInsets insets = decor.getRootWindowInsets(); if (insets == null) return; @@ -75,13 +74,13 @@ public final class TeamsPeachActivity extends NativeActivity { int obscured = Math.max(insets.getSystemWindowInsetBottom(), insetWindow.bottom - visibleWindow.bottom); if (obscured > bottom + 100 * scale) keyboard = obscured; } - renderSurface.getLocationOnScreen(surfaceLocation); - // adjustResize / non-edge-to-edge windows already exclude some bars or the IME. - // Send only the overlap with Slint's actual surface, never the full window inset twice. - int excludedTop = Math.max(0, surfaceLocation[1] - insetWindow.top); - int excludedLeft = Math.max(0, surfaceLocation[0] - insetWindow.left); - int excludedRight = Math.max(0, insetWindow.right - surfaceLocation[0] - renderSurface.getWidth()); - int excludedBottom = Math.max(0, insetWindow.bottom - surfaceLocation[1] - renderSurface.getHeight()); + // NativeActivity renders into the Window's native surface, not a child SurfaceView. + // Its resized NativeContentView describes unobscured content, NOT render-buffer size. + // Project onto decor coordinates; subtract only space outside the actual window. + int excludedTop = Math.max(0, decorLocation[1] - insetWindow.top); + int excludedLeft = Math.max(0, decorLocation[0] - insetWindow.left); + int excludedRight = Math.max(0, insetWindow.right - decorLocation[0] - decor.getWidth()); + int excludedBottom = Math.max(0, insetWindow.bottom - decorLocation[1] - decor.getHeight()); top = Math.max(0, top - excludedTop); right = Math.max(0, right - excludedRight); bottom = Math.max(0, bottom - excludedBottom); left = Math.max(0, left - excludedLeft); keyboard = Math.max(0, keyboard - excludedBottom); @@ -126,7 +125,7 @@ public final class TeamsPeachActivity extends NativeActivity { // Keep its invisible IME proxy out of TalkBack without changing its input connection. java.util.ArrayDeque views=new java.util.ArrayDeque<>();views.add(getWindow().getDecorView()); int visited=0; - while(!views.isEmpty() && visited++<256){View view=views.removeFirst();if(view instanceof SurfaceView)renderSurface=(SurfaceView)view;if("SlintInputView".equals(view.getClass().getSimpleName()))view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);if(view instanceof ViewGroup){ViewGroup group=(ViewGroup)view;for(int i=0;i