Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
Phone storage in File Explorer
Bee0b34c9836d16
diff --git a/README.md b/README.mdindex 4721aa4..c65ea29 100644--- a/README.md+++ b/README.md@@ -130,6 +130,14 @@ tests; there are no releases yet.clipboard, or save one or many to a folder you pick (`Downloads\Nectarlink`by default). New photos and screenshots from the phone also pop up on the PCwith a preview, ready to save or copy.+- **Phone storage in File Explorer**: mount the phone's storage under+ `%USERPROFILE%\Nectarlink\<Phone name>` using the Windows Cloud Files API+ (placeholders, on-demand download with progress when a file is opened, native+ sync icons). Browse folders, open files, drop new files in to upload them to+ the phone, rename, create folders, and delete (media files move to the+ phone's trash on Android 11+). Works with All files access or only the+ folders you pick on the phone, and is off by default on both sides with a+ clear prompt on the phone.- **Touchpad, air mouse, keyboard, voice typing and presentation remote**:control the PC from the phone — a touchpad with one-finger move, tap toclick, two-finger tap for right-click, two-finger scroll,diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 342fa9c..ee411ee 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -73,6 +73,15 @@<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"android:maxSdkVersion="32" />+ <!-- Phone storage in File Explorer on paired PCs (off by default, asked in+ context; users can also pick specific folders with the Storage Access+ Framework instead). -->+ <uses-permission+ android:name="android.permission.WRITE_EXTERNAL_STORAGE"+ android:maxSdkVersion="29" />+ <uses-permission+ android:name="android.permission.MANAGE_EXTERNAL_STORAGE"+ tools:ignore="ScopedStorage" /><!-- Names and icons of the apps whose notifications are mirrored, and thephone's speech recognizer for voice typing: Android hides other appsdiff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.ktindex 33a6600..18d4205 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@@ -30,6 +30,7 @@ import app.nectarlink.android.recorder.RecordingsStoreimport app.nectarlink.android.recorder.SavedRecordingimport app.nectarlink.android.service.ConnectionServiceimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.storage.PhoneStorageimport app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.core.Eventimport app.nectarlink.core.EventListener@@ -83,11 +84,15 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenercontacts = { contacts },sms = { sms },toggles = { toggles },+ storage = { storage },onMirror = { pc, request ->MirrorRequests.show(this.context, request, _state.value.nameOf(pc).orEmpty())},appWindows = AppWindows(this.context, scope, open = { pc -> mirrorOpen(pc) }, nameOf = { pc -> _state.value.nameOf(pc).orEmpty() }),)+ private val storage = PhoneStorage(this.context) { path ->+ notificationOps.trySend { it.storageChanged(path) }+ }private val toggles = PhoneToggles(this.context,onChanged = { state ->@@ -197,7 +202,13 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}node = startedval devices = runCatching { started.pairedDevices() }.getOrDefault(emptyList())- _state.update { it.withDevices(devices).copy(status = CoreStatus.Ready(started.deviceId())) }+ val storageAllowed = devices.mapNotNull { dev ->+ val toggles = runCatching { started.deviceToggles(dev.id) }.getOrDefault(emptyList())+ if (toggles.any { it.name == PhoneStorage.TOGGLE_NAME && it.enabled }) dev.id else null+ }.toSet()+ _state.update {+ it.withDevices(devices, storageAllowed).copy(status = CoreStatus.Ready(started.deviceId()))+ }if (devices.isNotEmpty()) ConnectionService.start(context)scope.launch(Dispatchers.Main) {battery.start()@@ -212,6 +223,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenersmsAccess = PhoneSms.hasAll(context),dndAccess = PhoneToggles.hasDndAccess(context),writeSettingsAccess = PhoneToggles.hasWriteSettings(context),+ storageAllFilesAccess = PhoneStorage.hasAllFilesAccess(context),+ storageSafFolders = PhoneStorage.safFolders(context).map { f -> f.name },)}started.updatePower(powerLevel(), capabilities(NotificationListener.hasAccess(context)))@@ -278,12 +291,24 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerval elevated = Elevated.runningval dndAccess = PhoneToggles.hasDndAccess(context)val writeSettingsAccess = PhoneToggles.hasWriteSettings(context)+ val storageAllFilesAccess = PhoneStorage.hasAllFilesAccess(context)+ val storageSafFolders = PhoneStorage.safFolders(context).map { it.name }+ if (!storageAllFilesAccess) storage.stopWatching()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 prevPhotos = _state.value.photoAccess+ val currentNode = node+ val storageAllowed = if (currentNode != null) {+ _state.value.devices.mapNotNull { dev ->+ val devToggles = runCatching { currentNode.deviceToggles(dev.id) }.getOrDefault(emptyList())+ if (devToggles.any { it.name == PhoneStorage.TOGGLE_NAME && it.enabled }) dev.id else null+ }.toSet()+ } else {+ emptySet()+ }_state.update {it.copy(notificationAccess = granted,@@ -297,7 +322,14 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListenerelevated = elevated,dndAccess = dndAccess,writeSettingsAccess = writeSettingsAccess,+ storageAllFilesAccess = storageAllFilesAccess,+ storageSafFolders = storageSafFolders,localNetwork = localNetwork,+ devices = if (currentNode != null) {+ it.devices.map { d -> d.copy(storageEnabled = d.id in storageAllowed) }+ } else {+ it.devices+ },)}if (granted && NotificationListener.instance == null) {@@ -570,6 +602,7 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener(if (PhoneContacts.canRead(context)) listOf("contacts.read") else emptyList()) +(if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +(if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList()) ++ PhoneStorage.capabilities(context) +(if (InputService.running || Elevated.running) listOf("mirror.input") else emptyList()) +// Apps in windows of their own run on displays the Elevated helper makes.(if (Elevated.running && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) listOf("mirror.virtual_display") else emptyList()) +@@ -814,6 +847,32 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener}}+ // ---- Phone storage (File Explorer on PC) ----++ /** Turns phone storage access in File Explorer on or off for `pcId` (off by default). */+ fun setStorageEnabled(pcId: String, enabled: Boolean) {+ val currentNode = node ?: return+ runCatching { currentNode.setDeviceToggle(pcId, PhoneStorage.TOGGLE_NAME, enabled) }+ _state.update { it.withStorageEnabled(pcId, enabled) }+ notificationOps.trySend {+ it.updatePower(powerLevel(), capabilities(_state.value.notificationAccess))+ }+ }++ fun dismissStorageRequest() {+ _state.update { it.copy(storageRequestedFrom = null) }+ }++ fun addSafFolder(treeUri: Uri) {+ PhoneStorage.addSafFolder(context, treeUri)+ refreshNotificationAccess()+ }++ fun removeSafFolder(name: String) {+ PhoneStorage.removeSafFolder(context, name)+ refreshNotificationAccess()+ }+/** Reconnects to PCs that aren't connected and syncs connected ones. */fun refresh() {refreshNotificationAccess()diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.ktindex b420ef8..d16c667 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt@@ -56,6 +56,8 @@ data class Device(val features: List<Feature> = emptyList(),val deckLayout: app.nectarlink.core.DeckLayout? = null,val deckState: app.nectarlink.core.DeckState? = null,+ /** Whether this PC is allowed to browse this phone's storage in File Explorer (off by default). */+ val storageEnabled: Boolean = false,) {val online: Boolean get() = link is Link.Online@@ -97,6 +99,12 @@ data class CoreState(val dndAccess: Boolean = false,/** Whether the user allowed screen brightness changes from a PC. */val writeSettingsAccess: Boolean = false,+ /** Whether Android "All files access" (`MANAGE_EXTERNAL_STORAGE`) is granted. */+ val storageAllFilesAccess: Boolean = false,+ /** Names of folders picked with the Storage Access Framework (when All files access is off). */+ val storageSafFolders: List<String> = emptyList(),+ /** ID of a paired PC that asked to browse this phone's storage while `storage` is off. */+ val storageRequestedFrom: String? = null,/** File transfers, newest first (running ones and the latest finished). */val transfers: List<Transfer> = emptyList(),) {@@ -105,7 +113,7 @@ data class CoreState(fun nameOf(id: String): String? =device(id)?.name ?: discovered.firstOrNull { it.id == id }?.name- fun withDevices(paired: List<PairedDevice>): CoreState {+ fun withDevices(paired: List<PairedDevice>, storageAllowed: Set<String> = emptySet()): CoreState {val prevById = devices.associateBy { it.id }return copy(devices = paired.map { p ->@@ -113,6 +121,7 @@ data class CoreState(p.toDevice().copy(deckLayout = prev?.deckLayout,deckState = prev?.deckState,+ storageEnabled = if (p.id in storageAllowed) true else prev?.storageEnabled ?: false,)}.sortedBy { it.pairedAt },)@@ -121,6 +130,11 @@ data class CoreState(fun withWakeState(id: String, state: WakeState): CoreState =update(id) { it.copy(wakeState = state) }+ fun withStorageEnabled(id: String, enabled: Boolean): CoreState =+ update(id) { it.copy(storageEnabled = enabled) }.copy(+ storageRequestedFrom = if (enabled && storageRequestedFrom == id) null else storageRequestedFrom,+ )+/** Folds one core event into the state. */fun reduce(event: Event): CoreState = when (event) {is Event.DeviceAdded -> {@@ -130,6 +144,7 @@ data class CoreState(is Event.DeviceRemoved -> copy(devices = devices.filterNot { it.id == event.id },ringingFrom = if (ringingFrom == nameOf(event.id)) null else ringingFrom,+ storageRequestedFrom = if (storageRequestedFrom == event.id) null else storageRequestedFrom,)is Event.LinkChanged -> update(event.id) {it.copy(@@ -167,7 +182,8 @@ data class CoreState(is Event.Transfer -> copy(transfers = withTransfer(event.transfer))// Shown in Android's media controls (see media/PcMedia).is Event.MediaChanged -> this- // PCs only: phones announce their own photos, calls, contacts, texts, toggles and screen.+ is Event.StorageRequested -> copy(storageRequestedFrom = event.id)+ // PCs only: phones announce their own photos, calls, contacts, texts, toggles, storage and screen.is Event.PhotoAdded,is Event.PhotosChanged,is Event.CallChanged,@@ -177,6 +193,7 @@ data class CoreState(is Event.PhoneToggles,is Event.Mirroring,is Event.RemoteInputRequested,+ is Event.StorageChanged,-> this}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.ktindex 4a07fa6..b52a857 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt@@ -21,6 +21,7 @@ import app.nectarlink.android.mirror.MirrorRequestimport app.nectarlink.android.mirror.MirrorRequestsimport app.nectarlink.android.mirror.MirrorServiceimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.storage.PhoneStorageimport app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.core.CallCommandimport app.nectarlink.core.CallLogEntry@@ -39,6 +40,9 @@ import app.nectarlink.core.PhotoItemimport app.nectarlink.core.PhotoThumbimport app.nectarlink.core.NotificationFailureimport app.nectarlink.core.Platform+import app.nectarlink.core.StorageEntry+import app.nectarlink.core.StorageReadFile+import app.nectarlink.core.StorageWriteDone/*** What the core asks of the phone: ring it, and act on its notifications@@ -58,6 +62,8 @@ internal class PhonePlatform(private val sms: () -> PhoneSms,/** The phone's quick settings (created after this). */private val toggles: () -> PhoneToggles,+ /** The phone's shared storage (created after this). */+ private val storage: () -> PhoneStorage,/** Asks the user to share the screen with a PC: (PC's ID, request) → asked. */private val onMirror: (String, MirrorRequest) -> Boolean,/** Apps in windows of their own on PCs (Elevated). */@@ -139,6 +145,19 @@ internal class PhonePlatform(override fun setPhoneToggle(id: String, value: PhoneToggleValue): Boolean =toggles().set(id, value)+ override fun storageList(path: String): List<StorageEntry> = storage().list(path)++ override fun storageOpenRead(path: String): StorageReadFile = storage().openRead(path)++ override fun storageWrite(path: String, stagedPath: String, modified: Long?): StorageWriteDone =+ storage().write(path, stagedPath, modified)++ override fun storageMkdir(path: String) = storage().mkdir(path)++ override fun storageRename(from: String, to: String) = storage().rename(from, to)++ override fun storageDelete(path: String, confirmed: Boolean) = storage().delete(path, confirmed)+override fun dismissNotification(key: String) {val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()listener.dismiss(key)diff --git a/android/app/src/main/kotlin/app/nectarlink/android/storage/PhoneStorage.kt b/android/app/src/main/kotlin/app/nectarlink/android/storage/PhoneStorage.ktnew file mode 100644index 0000000..d1fe368--- /dev/null+++ b/android/app/src/main/kotlin/app/nectarlink/android/storage/PhoneStorage.kt@@ -0,0 +1,750 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.storage++import android.Manifest+import android.content.ContentUris+import android.content.ContentValues+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.media.MediaScannerConnection+import android.net.Uri+import android.os.Build+import android.os.Environment+import android.os.FileObserver+import android.provider.DocumentsContract+import android.provider.MediaStore+import android.provider.Settings+import androidx.core.content.ContextCompat+import app.nectarlink.core.FileToSend+import app.nectarlink.core.StorageEntry+import app.nectarlink.core.StorageFailure+import app.nectarlink.core.StorageReadFile+import app.nectarlink.core.StorageWriteDone+import java.io.File+import java.io.FileInputStream+import java.io.FileOutputStream+import java.nio.file.Files++/**+ * Exposes this phone's shared storage (or user-picked SAF folders when full+ * storage access is not granted) to paired PCs for browsing in File Explorer+ * (`docs/protocol/storage.md`).+ *+ * Security invariants:+ * - Paths are relative to the shared root; `..`, `.`, leading/trailing `/`,+ * `\`, NUL, and control characters are rejected.+ * - Never exposes `/data`, `Android/data`, `Android/obb`, or Nectarlink's own+ * private directories.+ * - Symlinks resolving outside the canonical storage root (or into a blocked+ * directory) are rejected.+ */+class PhoneStorage(+ context: Context,+ private val onChanged: (String) -> Unit = {},+) {+ private val context = context.applicationContext+ private val observers = LinkedHashMap<String, FileObserver>()++ /** Lists entries in `path` (`""` for the root). */+ fun list(path: String): List<StorageEntry> {+ if (!isValidDirPath(path)) {+ throw StorageFailure.Invalid("invalid directory path")+ }+ if (hasAllFilesAccess(context)) {+ val root = sharedRoot()+ val dir = resolveExistingInRoot(root, blockedDirs(context, root), path, allowRoot = true)+ if (!dir.isDirectory) throw StorageFailure.NotFound()+ watchDirectory(path, dir)+ val children = dir.listFiles() ?: throw StorageFailure.Denied()+ val canonRoot = runCatching { root.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ val blocked = blockedDirs(context, root)+ val out = ArrayList<StorageEntry>(children.size)+ for (child in children) {+ val name = child.name+ if (!isValidName(name) || name.startsWith(".nectarlink")) continue+ val canon = runCatching { child.canonicalFile }.getOrNull() ?: continue+ if (!isInsideRoot(canonRoot, blocked, canon)) continue+ val isDir = canon.isDirectory+ if (!isDir && !canon.isFile) continue+ out.add(+ StorageEntry(+ name = name,+ size = if (isDir) 0uL else canon.length().coerceAtLeast(0L).toULong(),+ modified = canon.lastModified(),+ isDir = isDir,+ ),+ )+ }+ return out+ }+ val folders = safFolders(context)+ if (folders.isEmpty()) throw StorageFailure.Unsupported()+ return listSaf(folders, path)+ }++ /** Opens `path` for ranged reading (`storage.read`). */+ fun openRead(path: String): StorageReadFile {+ if (!isValidPath(path)) {+ throw StorageFailure.Invalid("invalid file path")+ }+ if (hasAllFilesAccess(context)) {+ val root = sharedRoot()+ val file = resolveExistingInRoot(root, blockedDirs(context, root), path, allowRoot = false)+ if (!file.isFile) throw StorageFailure.NotFound()+ return StorageReadFile(+ source = FileToSend.Path(+ path = file.absolutePath,+ name = file.name,+ folder = null,+ ),+ size = file.length().coerceAtLeast(0L).toULong(),+ modified = file.lastModified(),+ )+ }+ val folders = safFolders(context)+ if (folders.isEmpty()) throw StorageFailure.Unsupported()+ return openReadSaf(folders, path)+ }++ /** Commits a staged upload at `stagedPath` into `path` (`storage.write`). */+ fun write(path: String, stagedPath: String, modified: Long?): StorageWriteDone {+ if (!isValidPath(path)) {+ throw StorageFailure.Invalid("invalid destination path")+ }+ val staged = File(stagedPath)+ if (!staged.isFile) {+ throw StorageFailure.Failed("missing staged file")+ }+ if (hasAllFilesAccess(context)) {+ val root = sharedRoot()+ val blocked = blockedDirs(context, root)+ val dest = resolveTargetInRoot(root, blocked, path)+ val parent = dest.parentFile ?: throw StorageFailure.Denied()+ if (!parent.exists() && !parent.mkdirs() && !parent.isDirectory) {+ throw StorageFailure.Failed("cannot create parent folder")+ }+ val canonRoot = runCatching { root.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ val canonParent = runCatching { parent.canonicalFile }.getOrElse { throw StorageFailure.Denied() }+ if (!isInsideRoot(canonRoot, blocked, canonParent)) {+ throw StorageFailure.Denied()+ }+ moveOrCopy(staged, dest)+ if (modified != null && modified >= 0L) {+ dest.setLastModified(modified)+ }+ MediaScannerConnection.scanFile(context, arrayOf(dest.absolutePath), null, null)+ return StorageWriteDone(+ size = dest.length().coerceAtLeast(0L).toULong(),+ modified = modified ?: dest.lastModified(),+ )+ }+ val folders = safFolders(context)+ if (folders.isEmpty()) throw StorageFailure.Unsupported()+ return writeSaf(folders, path, staged, modified)+ }++ /** Creates a directory (and any missing parents) at `path` (`storage.mkdir`). */+ fun mkdir(path: String) {+ if (!isValidPath(path)) {+ throw StorageFailure.Invalid("invalid folder path")+ }+ if (hasAllFilesAccess(context)) {+ val root = sharedRoot()+ val blocked = blockedDirs(context, root)+ val dest = resolveTargetInRoot(root, blocked, path)+ if (!dest.exists() && !dest.mkdirs() && !dest.isDirectory) {+ throw StorageFailure.Failed("cannot create folder")+ }+ val canonRoot = runCatching { root.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ val canon = runCatching { dest.canonicalFile }.getOrElse { throw StorageFailure.Denied() }+ if (!isInsideRoot(canonRoot, blocked, canon)) {+ throw StorageFailure.Denied()+ }+ return+ }+ val folders = safFolders(context)+ if (folders.isEmpty()) throw StorageFailure.Unsupported()+ mkdirSaf(folders, path)+ }++ /** Renames or moves `from` to `to` (`storage.rename`). */+ fun rename(from: String, to: String) {+ if (!isValidPath(from) || !isValidPath(to)) {+ throw StorageFailure.Invalid("invalid rename path")+ }+ if (hasAllFilesAccess(context)) {+ val root = sharedRoot()+ val blocked = blockedDirs(context, root)+ val src = resolveExistingInRoot(root, blocked, from, allowRoot = false)+ val dst = resolveTargetInRoot(root, blocked, to)+ val parent = dst.parentFile ?: throw StorageFailure.Denied()+ if (!parent.exists() && !parent.mkdirs() && !parent.isDirectory) {+ throw StorageFailure.Failed("cannot create destination parent")+ }+ val canonRoot = runCatching { root.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ val canonParent = runCatching { parent.canonicalFile }.getOrElse { throw StorageFailure.Denied() }+ if (!isInsideRoot(canonRoot, blocked, canonParent)) {+ throw StorageFailure.Denied()+ }+ if (!src.renameTo(dst)) {+ throw StorageFailure.Failed("rename failed")+ }+ MediaScannerConnection.scanFile(+ context,+ arrayOf(src.absolutePath, dst.absolutePath),+ null,+ null,+ )+ return+ }+ val folders = safFolders(context)+ if (folders.isEmpty()) throw StorageFailure.Unsupported()+ renameSaf(folders, from, to)+ }++ /**+ * Deletes `path` (`storage.delete`).+ *+ * Media files indexed by Android's `MediaStore` on Android 11+ are moved to+ * the system trash (`IS_TRASHED = 1`) when possible; otherwise deletion+ * requires `confirmed = true` from the PC.+ */+ fun delete(path: String, confirmed: Boolean) {+ if (!isValidPath(path)) {+ throw StorageFailure.Invalid("invalid delete path")+ }+ if (hasAllFilesAccess(context)) {+ val root = sharedRoot()+ val blocked = blockedDirs(context, root)+ val target = resolveExistingInRoot(root, blocked, path, allowRoot = false)+ if (target.isFile && isMediaFile(target) && moveToMediaStoreTrash(target)) {+ return+ }+ if (!confirmed) {+ throw StorageFailure.Denied()+ }+ if (!target.deleteRecursively()) {+ throw StorageFailure.Failed("delete failed")+ }+ MediaScannerConnection.scanFile(context, arrayOf(target.absolutePath), null, null)+ return+ }+ val folders = safFolders(context)+ if (folders.isEmpty()) throw StorageFailure.Unsupported()+ if (!confirmed) throw StorageFailure.Denied()+ deleteSaf(folders, path)+ }++ @Synchronized+ fun stopWatching() {+ for (obs in observers.values) {+ obs.stopWatching()+ }+ observers.clear()+ }++ @Synchronized+ private fun watchDirectory(relPath: String, dir: File) {+ if (observers.containsKey(relPath)) return+ if (observers.size >= MAX_WATCHED_DIRS) {+ val eldest = observers.entries.iterator().next()+ eldest.value.stopWatching()+ observers.remove(eldest.key)+ }+ val mask = FileObserver.CREATE or+ FileObserver.DELETE or+ FileObserver.MOVED_FROM or+ FileObserver.MOVED_TO or+ FileObserver.CLOSE_WRITE+ @Suppress("DEPRECATION")+ val observer = object : FileObserver(dir.absolutePath, mask) {+ override fun onEvent(event: Int, file: String?) {+ if (file != null && file.startsWith(".nectarlink")) return+ onChanged(relPath)+ }+ }+ runCatching {+ observer.startWatching()+ observers[relPath] = observer+ }+ }++ private fun moveToMediaStoreTrash(file: File): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return false+ return runCatching {+ val volume = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL)+ val projection = arrayOf(MediaStore.Files.FileColumns._ID)+ @Suppress("DEPRECATION")+ val selection = "${MediaStore.MediaColumns.DATA} = ?"+ val args = arrayOf(file.absolutePath)+ val id = context.contentResolver.query(volume, projection, selection, args, null)?.use { c ->+ if (c.moveToFirst()) c.getLong(0) else null+ } ?: return false+ val itemUri = ContentUris.withAppendedId(volume, id)+ val values = ContentValues().apply {+ put(MediaStore.MediaColumns.IS_TRASHED, 1)+ }+ context.contentResolver.update(itemUri, values, null, null) > 0+ }.getOrDefault(false)+ }++ private fun moveOrCopy(staged: File, dest: File) {+ if (dest.exists() && dest.isDirectory) {+ throw StorageFailure.Invalid("destination is a directory")+ }+ if (staged.renameTo(dest)) return+ try {+ FileInputStream(staged).use { input ->+ FileOutputStream(dest).use { output ->+ input.copyTo(output)+ output.fd.sync()+ }+ }+ staged.delete()+ } catch (e: Exception) {+ throw StorageFailure.Failed(e.message ?: "write failed")+ }+ }++ // ---- SAF (Storage Access Framework) fallback ----++ private fun splitSafPath(folders: List<SafFolder>, path: String): Pair<SafFolder, List<String>> {+ val parts = path.split('/')+ val rootName = parts.first()+ val folder = folders.firstOrNull { it.name == rootName } ?: throw StorageFailure.NotFound()+ return folder to parts.drop(1)+ }++ private fun resolveSafDocId(treeUri: Uri, segments: List<String>): String {+ var currentDocId = DocumentsContract.getTreeDocumentId(treeUri)+ for (seg in segments) {+ currentDocId = findChildSafDoc(treeUri, currentDocId, seg)?.docId+ ?: throw StorageFailure.NotFound()+ }+ return currentDocId+ }++ private data class SafDocMeta(+ val docId: String,+ val name: String,+ val mime: String,+ val size: Long,+ val modified: Long,+ ) {+ val isDir: Boolean get() = mime == DocumentsContract.Document.MIME_TYPE_DIR+ }++ private fun listSafChildren(treeUri: Uri, parentDocId: String): List<SafDocMeta> {+ val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, parentDocId)+ val projection = arrayOf(+ DocumentsContract.Document.COLUMN_DOCUMENT_ID,+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,+ DocumentsContract.Document.COLUMN_MIME_TYPE,+ DocumentsContract.Document.COLUMN_SIZE,+ DocumentsContract.Document.COLUMN_LAST_MODIFIED,+ )+ val result = ArrayList<SafDocMeta>()+ context.contentResolver.query(childrenUri, projection, null, null, null)?.use { c ->+ while (c.moveToNext()) {+ val id = c.getString(0) ?: continue+ val name = c.getString(1) ?: continue+ val mime = c.getString(2) ?: "application/octet-stream"+ val size = if (c.isNull(3)) 0L else c.getLong(3)+ val modified = if (c.isNull(4)) 0L else c.getLong(4)+ if (isValidName(name) && !name.startsWith(".nectarlink")) {+ result.add(SafDocMeta(id, name, mime, size, modified))+ }+ }+ } ?: throw StorageFailure.Denied()+ return result+ }++ private fun findChildSafDoc(treeUri: Uri, parentDocId: String, name: String): SafDocMeta? =+ listSafChildren(treeUri, parentDocId).firstOrNull { it.name == name }++ private fun querySafDocMeta(treeUri: Uri, docId: String): SafDocMeta {+ val docUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, docId)+ val projection = arrayOf(+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,+ DocumentsContract.Document.COLUMN_MIME_TYPE,+ DocumentsContract.Document.COLUMN_SIZE,+ DocumentsContract.Document.COLUMN_LAST_MODIFIED,+ )+ context.contentResolver.query(docUri, projection, null, null, null)?.use { c ->+ if (c.moveToFirst()) {+ val name = c.getString(0) ?: ""+ val mime = c.getString(1) ?: "application/octet-stream"+ val size = if (c.isNull(2)) 0L else c.getLong(2)+ val modified = if (c.isNull(3)) 0L else c.getLong(3)+ return SafDocMeta(docId, name, mime, size, modified)+ }+ }+ throw StorageFailure.NotFound()+ }++ private fun listSaf(folders: List<SafFolder>, path: String): List<StorageEntry> {+ if (path.isEmpty()) {+ return folders.map {+ StorageEntry(name = it.name, size = 0uL, modified = 0L, isDir = true)+ }+ }+ val (folder, sub) = splitSafPath(folders, path)+ val docId = resolveSafDocId(folder.uri, sub)+ return listSafChildren(folder.uri, docId).map {+ StorageEntry(+ name = it.name,+ size = if (it.isDir) 0uL else it.size.coerceAtLeast(0L).toULong(),+ modified = it.modified,+ isDir = it.isDir,+ )+ }+ }++ private fun openReadSaf(folders: List<SafFolder>, path: String): StorageReadFile {+ val (folder, sub) = splitSafPath(folders, path)+ if (sub.isEmpty()) throw StorageFailure.NotFound()+ val docId = resolveSafDocId(folder.uri, sub)+ val meta = querySafDocMeta(folder.uri, docId)+ if (meta.isDir) throw StorageFailure.NotFound()+ val docUri = DocumentsContract.buildDocumentUriUsingTree(folder.uri, docId)+ val pfd = context.contentResolver.openFileDescriptor(docUri, "r")+ ?: throw StorageFailure.NotFound()+ val fd = pfd.detachFd()+ return StorageReadFile(+ source = FileToSend.Fd(fd = fd, name = meta.name, folder = null),+ size = meta.size.coerceAtLeast(0L).toULong(),+ modified = meta.modified,+ )+ }++ private fun ensureSafDir(treeUri: Uri, segments: List<String>): String {+ var currentDocId = DocumentsContract.getTreeDocumentId(treeUri)+ for (seg in segments) {+ val existing = findChildSafDoc(treeUri, currentDocId, seg)+ currentDocId = if (existing != null) {+ if (!existing.isDir) throw StorageFailure.Invalid("path component is a file")+ existing.docId+ } else {+ val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, currentDocId)+ val created = DocumentsContract.createDocument(+ context.contentResolver,+ parentUri,+ DocumentsContract.Document.MIME_TYPE_DIR,+ seg,+ ) ?: throw StorageFailure.Failed("cannot create SAF directory")+ DocumentsContract.getDocumentId(created)+ }+ }+ return currentDocId+ }++ private fun writeSaf(+ folders: List<SafFolder>,+ path: String,+ staged: File,+ modified: Long?,+ ): StorageWriteDone {+ val (folder, sub) = splitSafPath(folders, path)+ if (sub.isEmpty()) throw StorageFailure.Invalid("cannot overwrite root folder")+ val parentDocId = ensureSafDir(folder.uri, sub.dropLast(1))+ val fileName = sub.last()+ val existing = findChildSafDoc(folder.uri, parentDocId, fileName)+ val targetUri = if (existing != null) {+ if (existing.isDir) throw StorageFailure.Invalid("destination is a directory")+ DocumentsContract.buildDocumentUriUsingTree(folder.uri, existing.docId)+ } else {+ val parentUri = DocumentsContract.buildDocumentUriUsingTree(folder.uri, parentDocId)+ DocumentsContract.createDocument(+ context.contentResolver,+ parentUri,+ "application/octet-stream",+ fileName,+ ) ?: throw StorageFailure.Failed("cannot create SAF file")+ }+ try {+ FileInputStream(staged).use { input ->+ context.contentResolver.openOutputStream(targetUri, "wt")?.use { output ->+ input.copyTo(output)+ output.flush()+ } ?: throw StorageFailure.Failed("cannot open SAF output stream")+ }+ } catch (e: StorageFailure) {+ throw e+ } catch (e: Exception) {+ throw StorageFailure.Failed(e.message ?: "SAF write failed")+ }+ val size = staged.length().coerceAtLeast(0L).toULong()+ return StorageWriteDone(+ size = size,+ modified = modified ?: System.currentTimeMillis(),+ )+ }++ private fun mkdirSaf(folders: List<SafFolder>, path: String) {+ val (folder, sub) = splitSafPath(folders, path)+ if (sub.isEmpty()) return+ ensureSafDir(folder.uri, sub)+ }++ private fun renameSaf(folders: List<SafFolder>, from: String, to: String) {+ val (srcFolder, srcSub) = splitSafPath(folders, from)+ val (dstFolder, dstSub) = splitSafPath(folders, to)+ if (srcFolder.uri != dstFolder.uri || srcSub.isEmpty() || dstSub.isEmpty()) {+ throw StorageFailure.Unsupported()+ }+ if (srcSub.dropLast(1) != dstSub.dropLast(1)) {+ throw StorageFailure.Unsupported()+ }+ val docId = resolveSafDocId(srcFolder.uri, srcSub)+ val docUri = DocumentsContract.buildDocumentUriUsingTree(srcFolder.uri, docId)+ DocumentsContract.renameDocument(context.contentResolver, docUri, dstSub.last())+ ?: throw StorageFailure.Failed("SAF rename failed")+ }++ private fun deleteSaf(folders: List<SafFolder>, path: String) {+ val (folder, sub) = splitSafPath(folders, path)+ if (sub.isEmpty()) throw StorageFailure.Denied()+ val docId = resolveSafDocId(folder.uri, sub)+ val docUri = DocumentsContract.buildDocumentUriUsingTree(folder.uri, docId)+ if (!DocumentsContract.deleteDocument(context.contentResolver, docUri)) {+ throw StorageFailure.Failed("SAF delete failed")+ }+ }++ data class SafFolder(val name: String, val uri: Uri)++ companion object {+ private const val PREFS_NAME = "nectarlink_storage_saf"+ private const val KEY_TREES = "trees"+ private const val MAX_WATCHED_DIRS = 16+ const val TOGGLE_NAME = "storage"++ private val MEDIA_EXTENSIONS = setOf(+ "jpg", "jpeg", "png", "webp", "gif", "heic", "heif",+ "mp4", "mov", "mkv", "webm", "avi",+ "mp3", "m4a", "aac", "wav", "flac", "ogg", "opus",+ )++ fun sharedRoot(): File = Environment.getExternalStorageDirectory()++ /** Whether full shared-storage access (`MANAGE_EXTERNAL_STORAGE` on Android 11+) is granted. */+ fun hasAllFilesAccess(context: Context): Boolean =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ Environment.isExternalStorageManager()+ } else {+ ContextCompat.checkSelfPermission(+ context,+ Manifest.permission.READ_EXTERNAL_STORAGE,+ ) == PackageManager.PERMISSION_GRANTED &&+ ContextCompat.checkSelfPermission(+ context,+ Manifest.permission.WRITE_EXTERNAL_STORAGE,+ ) == PackageManager.PERMISSION_GRANTED+ }++ /** Whether this phone can serve storage right now (All files access or at least one SAF folder). */+ fun hasAnyAccess(context: Context): Boolean =+ hasAllFilesAccess(context) || safFolders(context).isNotEmpty()++ /** Capabilities offered by this phone's storage service when access is granted. */+ fun capabilities(context: Context): List<String> =+ if (hasAnyAccess(context)) listOf("storage.read", "storage.write") else emptyList()++ /** Intent to open Android's "All files access" settings screen for Nectarlink. */+ fun allFilesAccessIntent(context: Context): Intent {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val perApp = Intent(+ Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION,+ Uri.fromParts("package", context.packageName, null),+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ if (perApp.resolveActivity(context.packageManager) != null) {+ return perApp+ }+ return Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ return Intent(+ Settings.ACTION_APPLICATION_DETAILS_SETTINGS,+ Uri.fromParts("package", context.packageName, null),+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ }++ /** Persists a folder picked via `ACTION_OPEN_DOCUMENT_TREE`. */+ fun addSafFolder(context: Context, treeUri: Uri) {+ val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ runCatching { context.contentResolver.takePersistableUriPermission(treeUri, flags) }+ val rawName = runCatching {+ val docId = DocumentsContract.getTreeDocumentId(treeUri)+ docId.substringAfterLast(':').substringAfterLast('/').ifEmpty { "Folder" }+ }.getOrDefault("Folder")+ val cleanName = rawName.filter { it != '/' && it != '\\' && it >= ' ' }.trim().ifEmpty { "Folder" }+ val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ val current = prefs.getStringSet(KEY_TREES, emptySet()).orEmpty().toMutableSet()+ current.removeAll { it.substringAfter('|') == treeUri.toString() }+ var uniqueName = cleanName+ var suffix = 2+ val existingNames = current.map { it.substringBefore('|') }.toSet()+ while (uniqueName in existingNames) {+ uniqueName = "$cleanName ($suffix)"+ suffix+++ }+ current.add("$uniqueName|$treeUri")+ prefs.edit().putStringSet(KEY_TREES, current).apply()+ }++ /** Removes a previously picked SAF folder. */+ fun removeSafFolder(context: Context, name: String) {+ val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ val current = prefs.getStringSet(KEY_TREES, emptySet()).orEmpty().toMutableSet()+ val removed = current.filter { it.substringBefore('|') == name }+ for (entry in removed) {+ val uri = runCatching { Uri.parse(entry.substringAfter('|')) }.getOrNull()+ if (uri != null) {+ val flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ runCatching { context.contentResolver.releasePersistableUriPermission(uri, flags) }+ }+ }+ current.removeAll(removed.toSet())+ prefs.edit().putStringSet(KEY_TREES, current).apply()+ }++ /** Lists currently persisted SAF folders. */+ fun safFolders(context: Context): List<SafFolder> {+ val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)+ val persisted = runCatching {+ context.contentResolver.persistedUriPermissions+ .filter { it.isReadPermission }+ .map { it.uri }+ .toSet()+ }.getOrDefault(emptySet())+ return prefs.getStringSet(KEY_TREES, emptySet()).orEmpty()+ .mapNotNull { entry ->+ val idx = entry.indexOf('|')+ if (idx <= 0) return@mapNotNull null+ val name = entry.substring(0, idx)+ val uri = runCatching { Uri.parse(entry.substring(idx + 1)) }.getOrNull()+ ?: return@mapNotNull null+ if (persisted.isNotEmpty() && uri !in persisted) return@mapNotNull null+ SafFolder(name, uri)+ }+ .sortedBy { it.name.lowercase() }+ }++ internal fun blockedDirs(context: Context, root: File): List<File> = buildList {+ add(File("/data"))+ add(File(root, "Android/data"))+ add(File(root, "Android/obb"))+ context.dataDir?.let { add(it) }+ context.filesDir?.let { add(it) }+ context.noBackupFilesDir?.let { add(it) }+ context.cacheDir?.let { add(it) }+ context.externalCacheDir?.let { add(it) }+ context.getExternalFilesDir(null)?.let { add(it) }+ }++ internal fun isMediaFile(file: File): Boolean =+ file.extension.lowercase() in MEDIA_EXTENSIONS++ /** Validates a single path segment (no `/`, `\`, `..`, `.`, NUL, or control chars). */+ internal fun isValidName(name: String): Boolean {+ if (name.isEmpty() || name.length > 255 || name == "." || name == "..") return false+ return name.all { c -> c != '/' && c != '\\' && c != '\u0000' && !c.isISOControl() }+ }++ /** Validates a non-empty relative path (`a/b/c`). */+ internal fun isValidPath(path: String): Boolean {+ if (path.isEmpty() || path.length > 1024 || path.startsWith('/') || path.endsWith('/')) {+ return false+ }+ return path.split('/').all(::isValidName)+ }++ /** Validates a directory path (`""` for the root or a valid relative path). */+ internal fun isValidDirPath(path: String): Boolean =+ path.isEmpty() || isValidPath(path)++ internal fun isInsideRoot(canonRoot: File, blocked: List<File>, candidate: File): Boolean {+ val rootPath = canonRoot.path+ val candPath = candidate.path+ val underRoot = candPath == rootPath ||+ candPath.startsWith(if (rootPath.endsWith(File.separator)) rootPath else "$rootPath${File.separator}")+ if (!underRoot) return false+ for (b in blocked) {+ val bp = runCatching { b.canonicalPath }.getOrDefault(b.absolutePath)+ if (candPath == bp || candPath.startsWith("$bp${File.separator}")) {+ return false+ }+ }+ return true+ }++ internal fun isSymlink(file: File): Boolean =+ runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)++ /**+ * Resolves an existing path inside `root`, rejecting `..`, absolute+ * paths, blocked directories, and symlinks pointing outside `root`.+ */+ internal fun resolveExistingInRoot(+ root: File,+ blocked: List<File>,+ rel: String,+ allowRoot: Boolean,+ ): File {+ val valid = if (allowRoot) isValidDirPath(rel) else isValidPath(rel)+ if (!valid) throw StorageFailure.Invalid("invalid storage path")+ val canonRoot = runCatching { root.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ if (!isInsideRoot(canonRoot, blocked, canonRoot)) throw StorageFailure.Denied()+ if (rel.isEmpty()) return canonRoot++ var cur = canonRoot+ for (seg in rel.split('/')) {+ cur = File(cur, seg)+ if (!cur.exists() && !isSymlink(cur)) {+ throw StorageFailure.NotFound()+ }+ val target = runCatching { cur.canonicalFile }.getOrElse { throw StorageFailure.Denied() }+ if (!isInsideRoot(canonRoot, blocked, target)) {+ throw StorageFailure.Denied()+ }+ }+ val finalCanon = runCatching { cur.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ if (!finalCanon.exists()) throw StorageFailure.NotFound()+ if (!isInsideRoot(canonRoot, blocked, finalCanon)) throw StorageFailure.Denied()+ return finalCanon+ }++ /**+ * Resolves a target path (which may not exist yet) inside `root`,+ * verifying that every existing ancestor stays inside `root` and is+ * not a symlink escaping `root` or entering a blocked directory.+ */+ internal fun resolveTargetInRoot(+ root: File,+ blocked: List<File>,+ rel: String,+ ): File {+ if (!isValidPath(rel)) throw StorageFailure.Invalid("invalid storage path")+ val canonRoot = runCatching { root.canonicalFile }.getOrElse { throw StorageFailure.NotFound() }+ if (!isInsideRoot(canonRoot, blocked, canonRoot)) throw StorageFailure.Denied()++ var cur = canonRoot+ for (seg in rel.split('/')) {+ cur = File(cur, seg)+ if (cur.exists() || isSymlink(cur)) {+ val target = runCatching { cur.canonicalFile }.getOrElse { throw StorageFailure.Denied() }+ if (!isInsideRoot(canonRoot, blocked, target)) {+ throw StorageFailure.Denied()+ }+ } else {+ val absCheck = File(cur.absolutePath)+ if (!isInsideRoot(canonRoot, blocked, absCheck)) {+ throw StorageFailure.Denied()+ }+ }+ }+ return cur+ }+ }+}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.ktindex 4d66e56..5375962 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@@ -382,6 +382,8 @@ private fun App(onSendFolder = core::sendFolder,onAccessChanged = core::refreshNotificationAccess,onCancelTransfer = core::cancelTransfer,+ onAllowStorage = { pcId -> core.setStorageEnabled(pcId, true) },+ onDismissStorageRequest = core::dismissStorageRequest,modifier = modifier,)Tab.Settings -> SettingsScreen(@@ -394,6 +396,9 @@ private fun App(onPairNew = { pairing = true },onAccessChanged = core::refreshNotificationAccess,updater = (LocalContext.current.applicationContext as NectarlinkApplication).updater,+ onSetStorageEnabled = core::setStorageEnabled,+ onAddSafFolder = core::addSafFolder,+ onRemoveSafFolder = core::removeSafFolder,modifier = modifier,)}diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.ktindex 63405bb..bca9d8c 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt@@ -91,6 +91,8 @@ fun HomeScreen(onSendFolder: (pcId: String, tree: Uri) -> Unit,onAccessChanged: () -> Unit,onCancelTransfer: (id: String) -> Unit,+ onAllowStorage: (pcId: String) -> Unit = {},+ onDismissStorageRequest: () -> Unit = {},modifier: Modifier = Modifier,) {LazyColumn(@@ -129,6 +131,41 @@ fun HomeScreen(state.ringingFrom?.let { from ->item { RingingBanner(from, onStopRinging) }}+ state.storageRequestedFrom?.let { pcId ->+ item {+ val pcName = state.nameOf(pcId) ?: stringResource(R.string.your_pc)+ val context = LocalContext.current+ Surface(shape = MaterialTheme.shapes.extraLarge, color = MaterialTheme.colorScheme.secondaryContainer) {+ Column(Modifier.fillMaxWidth().padding(20.dp)) {+ Text(+ stringResource(R.string.storage_request_title, pcName),+ style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.onSecondaryContainer,+ )+ Spacer(Modifier.height(4.dp))+ Text(+ stringResource(R.string.storage_request_text, pcName),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSecondaryContainer,+ )+ Spacer(Modifier.height(12.dp))+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Button(onClick = {+ onAllowStorage(pcId)+ if (!state.storageAllFilesAccess && state.storageSafFolders.isEmpty()) {+ context.startActivity(+ app.nectarlink.android.storage.PhoneStorage.allFilesAccessIntent(context),+ )+ }+ }) { Text(stringResource(R.string.action_allow)) }+ OutlinedButton(onClick = onDismissStorageRequest) {+ Text(stringResource(R.string.action_not_now))+ }+ }+ }+ }+ }+ }item { UpdateCard(updater) }if (!state.localNetwork) {item {diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.ktindex 83a2c15..f60f672 100644--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/settings/SettingsScreen.kt@@ -56,6 +56,7 @@ import app.nectarlink.android.elevated.PairingNotificationimport app.nectarlink.android.mirror.InputServiceimport app.nectarlink.android.photos.RecentPhotosimport app.nectarlink.android.sms.PhoneSms+import app.nectarlink.android.storage.PhoneStorageimport app.nectarlink.android.toggles.PhoneTogglesimport app.nectarlink.android.update.AppUpdaterimport app.nectarlink.android.update.CheckForUpdates@@ -78,6 +79,9 @@ fun SettingsScreen(onPairNew: () -> Unit,onAccessChanged: () -> Unit,updater: AppUpdater,+ onSetStorageEnabled: (pcId: String, enabled: Boolean) -> Unit = { _, _ -> },+ onAddSafFolder: (Uri) -> Unit = {},+ onRemoveSafFolder: (String) -> Unit = {},modifier: Modifier = Modifier,) {var confirmUnpair by remember { mutableStateOf<Device?>(null) }@@ -131,6 +135,15 @@ fun SettingsScreen()}+ Section(stringResource(R.string.settings_storage)) {+ StorageAccess(+ allFiles = state.storageAllFilesAccess,+ safFolders = state.storageSafFolders,+ onAddSafFolder = onAddSafFolder,+ onRemoveSafFolder = onRemoveSafFolder,+ )+ }+Section(stringResource(R.string.settings_control)) {DndAccess(state.dndAccess)WriteSettingsAccess(state.writeSettingsAccess || state.elevated)@@ -210,17 +223,39 @@ fun SettingsScreen(}Section(stringResource(R.string.settings_devices)) {+ val context = LocalContext.currentstate.devices.forEach { device ->- Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {- Column(Modifier.weight(1f)) {- Text(device.name, style = MaterialTheme.typography.titleSmall)- Text(- stringResource(if (device.online) R.string.connected else R.string.not_connected),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,+ Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f)) {+ Text(device.name, style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(if (device.online) R.string.connected else R.string.not_connected),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ OutlinedButton(onClick = { confirmUnpair = device }) { Text(stringResource(R.string.action_unpair)) }+ }+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.storage_pc_toggle), style = MaterialTheme.typography.bodyMedium)+ Text(+ stringResource(R.string.storage_pc_toggle_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ Switch(+ checked = device.storageEnabled,+ onCheckedChange = { enabled ->+ onSetStorageEnabled(device.id, enabled)+ if (enabled && !state.storageAllFilesAccess && state.storageSafFolders.isEmpty()) {+ context.startActivity(PhoneStorage.allFilesAccessIntent(context))+ }+ },)}- OutlinedButton(onClick = { confirmUnpair = device }) { Text(stringResource(R.string.action_unpair)) }}}FilledTonalButton(onClick = onPairNew) { Text(stringResource(R.string.action_pair_new)) }@@ -502,6 +537,58 @@ private fun PhotosAccess(}}+@Composable+private fun StorageAccess(+ allFiles: Boolean,+ safFolders: List<String>,+ onAddSafFolder: (Uri) -> Unit,+ onRemoveSafFolder: (String) -> Unit,+) {+ val context = LocalContext.current+ val pickFolder = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocumentTree()) { uri ->+ if (uri != null) onAddSafFolder(uri)+ }+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.storage_all_files_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(if (allFiles) R.string.storage_all_files_on else R.string.storage_all_files_off),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ val open = { context.startActivity(PhoneStorage.allFilesAccessIntent(context)) }+ if (allFiles) {+ OutlinedButton(onClick = open) { Text(stringResource(R.string.action_manage)) }+ } else {+ Button(onClick = open) { Text(stringResource(R.string.action_allow)) }+ }+ }+ if (!allFiles) {+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Column(Modifier.weight(1f).padding(end = 12.dp)) {+ Text(stringResource(R.string.storage_saf_title), style = MaterialTheme.typography.titleSmall)+ Text(+ stringResource(R.string.storage_saf_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ OutlinedButton(onClick = { pickFolder.launch(null) }) {+ Text(stringResource(R.string.storage_add_folder))+ }+ }+ safFolders.forEach { name ->+ Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {+ Text(name, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))+ TextButton(onClick = { onRemoveSafFolder(name) }) {+ Text(stringResource(R.string.storage_remove_folder))+ }+ }+ }+ }+}+@Composableprivate fun Section(title: String, content: @Composable () -> Unit) {Text(diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xmlindex a663927..ed89cbb 100644--- a/android/app/src/main/res/values/strings.xml+++ b/android/app/src/main/res/values/strings.xml@@ -315,4 +315,19 @@<string name="deck_commands_denied_title">Allow commands on %1$s</string><string name="deck_commands_denied_text">To run shell commands from this phone, turn on “Run Deck commands” for this phone in Nectarlink › Settings › Devices on %1$s.</string><string name="deck_hint">Configure pages and tiles in Nectarlink › Deck on %1$s.</string>++ <!-- Phone storage in File Explorer -->+ <string name="settings_storage">Storage in File Explorer</string>+ <string name="storage_all_files_title">All files access</string>+ <string name="storage_all_files_on">On. Paired PCs you allow can browse this phone’s shared storage in File Explorer, open files on demand, and copy files in or out.</string>+ <string name="storage_all_files_off">Browse this phone’s folders in File Explorer on your PC, open files on demand, and copy files in or out. Because Google Play restricts full storage access, Nectarlink is distributed directly and asks for All files access only when you turn this on — or you can pick specific folders below instead.</string>+ <string name="storage_saf_title">Selected folders only</string>+ <string name="storage_saf_hint">Share only folders you pick with Android’s folder picker instead of your whole storage.</string>+ <string name="storage_add_folder">Add folder</string>+ <string name="storage_remove_folder">Remove</string>+ <string name="storage_pc_toggle">Browse this phone’s storage in File Explorer</string>+ <string name="storage_pc_toggle_hint">Off by default. Lets this PC list, open, upload, rename and delete files in your shared storage.</string>+ <string name="storage_request_title">%1$s wants to browse this phone’s storage</string>+ <string name="storage_request_text">Allow %1$s to browse your shared storage (or selected folders) in File Explorer?</string>+ <string name="action_not_now">Not now</string></resources>diff --git a/android/app/src/test/kotlin/app/nectarlink/android/storage/PhoneStorageTest.kt b/android/app/src/test/kotlin/app/nectarlink/android/storage/PhoneStorageTest.ktnew file mode 100644index 0000000..d9464b3--- /dev/null+++ b/android/app/src/test/kotlin/app/nectarlink/android/storage/PhoneStorageTest.kt@@ -0,0 +1,117 @@+// SPDX-License-Identifier: GPL-3.0-or-later+package app.nectarlink.android.storage++import app.nectarlink.core.StorageFailure+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test+import java.io.File+import java.nio.file.Files++class PhoneStorageTest {+ @Test+ fun validatesRelativeNamesAndPaths() {+ assertTrue(PhoneStorage.isValidName("notes.txt"))+ assertTrue(PhoneStorage.isValidName(".hidden"))+ assertFalse(PhoneStorage.isValidName(""))+ assertFalse(PhoneStorage.isValidName("."))+ assertFalse(PhoneStorage.isValidName(".."))+ assertFalse(PhoneStorage.isValidName("a/b"))+ assertFalse(PhoneStorage.isValidName("a\\b"))+ assertFalse(PhoneStorage.isValidName("bad\u0000name"))++ assertTrue(PhoneStorage.isValidDirPath(""))+ assertTrue(PhoneStorage.isValidDirPath("DCIM/Camera"))+ assertFalse(PhoneStorage.isValidPath(""))+ assertTrue(PhoneStorage.isValidPath("DCIM/Camera/IMG_001.jpg"))+ assertFalse(PhoneStorage.isValidPath("/etc/passwd"))+ assertFalse(PhoneStorage.isValidPath("DCIM/../secret"))+ assertFalse(PhoneStorage.isValidPath("DCIM/Camera/"))+ assertFalse(PhoneStorage.isValidPath("DCIM//Camera"))+ }++ @Test+ fun resolvesInsideRootAndBlocksPrivateAndTraversalPaths() {+ val temp = Files.createTempDirectory("nectarlink-storage-test").toFile()+ try {+ val root = File(temp, "shared").apply { mkdirs() }+ val outside = File(temp, "outside").apply { mkdirs() }+ val outsideSecret = File(outside, "secret.txt").apply { writeText("secret") }+ val androidData = File(root, "Android/data/app.nectarlink").apply { mkdirs() }+ File(androidData, "private.db").writeText("private")+ val docs = File(root, "Documents").apply { mkdirs() }+ val note = File(docs, "note.txt").apply { writeText("hello") }++ val blocked = listOf(+ File("/data"),+ File(root, "Android/data"),+ File(root, "Android/obb"),+ )++ val resolvedRoot = PhoneStorage.resolveExistingInRoot(root, blocked, "", allowRoot = true)+ assertEquals(root.canonicalFile, resolvedRoot)++ val resolvedNote = PhoneStorage.resolveExistingInRoot(+ root,+ blocked,+ "Documents/note.txt",+ allowRoot = false,+ )+ assertEquals(note.canonicalFile, resolvedNote)++ // Reject traversal & absolute paths+ for (bad in listOf("../outside/secret.txt", "/data/system", "Documents/../../outside/secret.txt")) {+ try {+ PhoneStorage.resolveExistingInRoot(root, blocked, bad, allowRoot = false)+ fail("expected Invalid for $bad")+ } catch (_: StorageFailure.Invalid) {+ }+ }++ // Reject blocked Android/data directory+ try {+ PhoneStorage.resolveExistingInRoot(+ root,+ blocked,+ "Android/data/app.nectarlink/private.db",+ allowRoot = false,+ )+ fail("expected Denied for Android/data")+ } catch (_: StorageFailure.Denied) {+ }++ try {+ PhoneStorage.resolveTargetInRoot(+ root,+ blocked,+ "Android/data/app.nectarlink/new.db",+ )+ fail("expected Denied for target in Android/data")+ } catch (_: StorageFailure.Denied) {+ }++ // If the OS allows creating a symlink, verify symlink escape is rejected+ val linkFile = File(docs, "escape.txt")+ val symlinkCreated = runCatching {+ Files.createSymbolicLink(linkFile.toPath(), outsideSecret.toPath())+ true+ }.getOrDefault(false)+ if (symlinkCreated) {+ try {+ PhoneStorage.resolveExistingInRoot(+ root,+ blocked,+ "Documents/escape.txt",+ allowRoot = false,+ )+ fail("expected Denied for symlink escaping root")+ } catch (_: StorageFailure.Denied) {+ }+ }+ } finally {+ temp.deleteRecursively()+ }+ }+}diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rsindex dac12c3..ee6bc83 100644--- a/core/nectarlink-cli/src/main.rs+++ b/core/nectarlink-cli/src/main.rs@@ -52,6 +52,10 @@ struct Cli {/// Extra capability to announce, e.g. clip.read.auto (repeatable).#[arg(long = "offer", global = true, value_name = "CAPABILITY")]offers: Vec<String>,+ /// Directory to serve as phone storage with --as-phone (defaults to a+ /// generated sample folder tree in the data directory).+ #[arg(long, global = true)]+ storage_root: Option<PathBuf>,/// Log verbosity (error, warn, info, debug, trace).#[arg(long, global = true, default_value = "warn")]log: String,@@ -249,6 +253,16 @@ enum Command {#[command(subcommand)]action: Option<DeckArg>,},+ /// Browse and edit a paired phone's shared storage (`ls`, `get`, `put`,+ /// `mkdir`, `rm`, `mv`).+ Storage {+ device: String,+ /// Where to reach the phone, when discovery can't.+ #[arg(long, global = true)]+ at: Vec<std::net::SocketAddr>,+ #[command(subcommand)]+ action: StorageArg,+ },/// Act as a phone sharing its screen (use with --as-phone): when a PC/// asks, streams an H.264 file (Annex B, with access unit delimiters) in/// a loop at `fps`. Stays online.@@ -591,6 +605,57 @@ enum DeckArg {Press { tile: String },}+#[derive(Debug, Subcommand)]+enum StorageArg {+ /// List a folder on the phone's shared storage (omit `path` for the root).+ Ls {+ #[arg(default_value = "")]+ path: String,+ },+ /// Download a file (or a byte range of a file) from the phone's storage.+ Get {+ /// Relative path on the phone (e.g. `Documents/notes.txt`).+ remote: String,+ /// Local file to write (defaults to the file's name in the current directory).+ local: Option<PathBuf>,+ /// Start byte offset (0-based).+ #[arg(long, default_value_t = 0)]+ offset: u64,+ /// Number of bytes to read (omit for until end of file).+ #[arg(long)]+ length: Option<u64>,+ },+ /// Upload a local file into the phone's shared storage.+ Put {+ /// Local file to upload.+ local: PathBuf,+ /// Destination relative path on the phone (e.g. `Download/hello.txt`).+ remote: String,+ },+ /// Create a folder (and any missing parents) on the phone's storage.+ Mkdir {+ /// Relative folder path to create.+ path: String,+ },+ /// Delete a file or folder on the phone's storage.+ Rm {+ /// Relative path to delete.+ path: String,+ /// Ask the phone to use its trash without PC confirmation (fails with+ /// `confirm_required` for non-trashed items).+ #[arg(long)]+ unconfirmed: bool,+ },+ /// Rename or move a file or folder on the phone's storage.+ #[command(visible_alias = "rename")]+ Mv {+ /// Existing relative path on the phone.+ from: String,+ /// New relative path on the phone.+ to: String,+ },+}+/// Where `mirror` saves the video, and what arrived.static RECORDING: std::sync::OnceLock<std::sync::Arc<Recording>> = std::sync::OnceLock::new();@@ -1301,6 +1366,38 @@ fn sample_photos() {];}+static PHONE_STORAGE: std::sync::OnceLock<nectarlink_core::FolderStorage> = std::sync::OnceLock::new();++fn sample_storage_tree(root: &std::path::Path) {+ let is_empty = std::fs::read_dir(root).map(|mut d| d.next().is_none()).unwrap_or(true);+ if !is_empty {+ return;+ }+ let files: &[(&str, &[u8])] = &[+ ("Documents/notes.txt", b"Shopping list:\n- Coffee beans\n- Oats\n- Sparkling water\n"),+ (+ "Documents/project-plan.md",+ b"# Nectarlink Storage\n\nBrowse phone files directly in File Explorer.\n",+ ),+ (+ "Download/guide.txt",+ b"Welcome to Nectarlink Phone Storage.\nOpen any file to stream it on demand.\n",+ ),+ (+ "DCIM/Camera/IMG_20260406_184210.jpg",+ &sample_jpeg(640, 480, (58, 124, 165), (22, 48, 72), (242, 193, 78)),+ ),+ ("Music/README.txt", b"Drop audio tracks here to copy them to the phone.\n"),+ ];+ for (rel, data) in files {+ let path = root.join(rel);+ if let Some(parent) = path.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ let _ = std::fs::write(path, data);+ }+}+/// Rings by printing to the terminal (the CLI has no speaker access).#[derive(Debug)]struct TerminalPlatform;@@ -1747,6 +1844,53 @@ impl Platform for TerminalPlatform {println!("A paired device pressed deck tile {tile}");Ok(())}+ fn storage_list(+ &self,+ path: &str,+ ) -> std::result::Result<Vec<nectarlink_core::StorageEntry>, nectarlink_core::StorageError> {+ let s = PHONE_STORAGE.get().ok_or(nectarlink_core::StorageError::Unsupported)?;+ s.list(path)+ }+ fn storage_open_read(+ &self,+ path: &str,+ ) -> std::result::Result<nectarlink_core::StorageReadFile, nectarlink_core::StorageError> {+ let s = PHONE_STORAGE.get().ok_or(nectarlink_core::StorageError::Unsupported)?;+ s.open_read(path)+ }+ fn storage_write(+ &self,+ path: &str,+ staged: &std::path::Path,+ modified: Option<i64>,+ ) -> std::result::Result<nectarlink_core::StorageWriteDone, nectarlink_core::StorageError> {+ let s = PHONE_STORAGE.get().ok_or(nectarlink_core::StorageError::Unsupported)?;+ let done = s.write(path, staged, modified)?;+ println!("Saved {path} ({} bytes) to phone storage.", done.size);+ Ok(done)+ }+ fn storage_mkdir(&self, path: &str) -> std::result::Result<(), nectarlink_core::StorageError> {+ let s = PHONE_STORAGE.get().ok_or(nectarlink_core::StorageError::Unsupported)?;+ s.mkdir(path)?;+ println!("Created folder {path} in phone storage.");+ Ok(())+ }+ fn storage_rename(&self, from: &str, to: &str) -> std::result::Result<(), nectarlink_core::StorageError> {+ let s = PHONE_STORAGE.get().ok_or(nectarlink_core::StorageError::Unsupported)?;+ s.rename(from, to)?;+ println!("Renamed {from} -> {to} in phone storage.");+ Ok(())+ }+ fn storage_delete(+ &self,+ path: &str,+ confirmed: bool,+ ) -> std::result::Result<(), nectarlink_core::StorageError> {+ let s = PHONE_STORAGE.get().ok_or(nectarlink_core::StorageError::Unsupported)?;+ s.delete(path, confirmed)?;+ println!("Deleted {path} from phone storage.");+ Ok(())+ }}fn main() -> Result<()> {@@ -1788,17 +1932,27 @@ async fn start_node(cli: &Cli) -> Result<Node> {};let device = DeviceInfo { name, kind, os, os_ver, model: None, accent: None };let power = node_power(cli);- let mut config = NodeConfig::new(data_dir, device, env!("CARGO_PKG_VERSION"));+ let mut config = NodeConfig::new(data_dir.clone(), device, env!("CARGO_PKG_VERSION"));config.downloads_dir = cli.downloads_dir.clone();config.port = cli.port;config.lan_discovery = !cli.no_lan;config.away_mode = cli.away;config.power = power;- if !cli.as_phone {+ if cli.as_phone {+ let storage_root = cli.storage_root.clone().unwrap_or_else(|| data_dir.join("sample-storage"));+ let _ = std::fs::create_dir_all(&storage_root);+ sample_storage_tree(&storage_root);+ let trash_dir = data_dir.join("storage-trash");+ let _ =+ PHONE_STORAGE.set(nectarlink_core::FolderStorage::new(storage_root).with_trash_dir(trash_dir));+ config.capabilities.push(nectarlink_core::STORAGE_READ.into());+ config.capabilities.push(nectarlink_core::STORAGE_WRITE.into());+ } else {config.capabilities.push(nectarlink_core::RECORDER.into());config.capabilities.push(nectarlink_core::TOGGLES_SHOW.into());config.capabilities.push(nectarlink_core::PC_WAKE.into());config.capabilities.push(nectarlink_core::DECK_ACTIONS.into());+ config.capabilities.push(nectarlink_core::STORAGE_MOUNT.into());}let extra_caps = config.capabilities.clone();let node = Node::start(config, Arc::new(TerminalPlatform)).await.context("failed to start")?;@@ -2258,6 +2412,75 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {.with_context(|| format!("the PC refused deck tile {tile:?}"))?;println!("Pressed {tile}.");}+ Command::Storage { device, at, action } => {+ let id = resolve(node, device)?;+ if !at.is_empty() {+ node.add_known_addrs(id, at);+ }+ wait_until_online(node, id).await?;+ match action {+ StorageArg::Ls { path } => {+ let entries = node+ .storage_list(id, path.clone())+ .await+ .with_context(|| format!("failed to list {path:?}"))?;+ if entries.is_empty() {+ println!("(empty)");+ }+ for e in entries {+ if e.is_dir {+ println!("dir {:>10} {}/", "-", e.name);+ } else {+ println!("file {:>10} B {}", e.size, e.name);+ }+ }+ }+ StorageArg::Get { remote, local, offset, length } => {+ let out = match local {+ Some(p) => p.clone(),+ None => {+ let file_name = remote.rsplit('/').next().unwrap_or(remote.as_str());+ if file_name.is_empty() {+ bail!("specify a file path on the phone");+ }+ PathBuf::from(file_name)+ }+ };+ let (_meta, bytes) = node+ .storage_read(id, remote.clone(), *offset, *length)+ .await+ .with_context(|| format!("failed to read {remote:?}"))?;+ std::fs::write(&out, &bytes)+ .with_context(|| format!("failed to write {}", out.display()))?;+ println!("Saved {} ({} bytes).", out.display(), bytes.len());+ }+ StorageArg::Put { local, remote } => {+ let done = node+ .storage_write(id, remote.clone(), local)+ .await+ .with_context(|| format!("failed to upload {} -> {remote}", local.display()))?;+ println!("Uploaded {remote} ({} bytes).", done.size);+ }+ StorageArg::Mkdir { path } => {+ node.storage_mkdir(id, path.clone())+ .await+ .with_context(|| format!("failed to create folder {path:?}"))?;+ println!("Created {path}/");+ }+ StorageArg::Rm { path, unconfirmed } => {+ node.storage_delete(id, path.clone(), !*unconfirmed)+ .await+ .with_context(|| format!("failed to delete {path:?}"))?;+ println!("Deleted {path}");+ }+ StorageArg::Mv { from, to } => {+ node.storage_rename(id, from.clone(), to.clone())+ .await+ .with_context(|| format!("failed to rename {from:?} -> {to:?}"))?;+ println!("Renamed {from} -> {to}");+ }+ }+ }Command::Apps { device, at } => {let id = resolve(node, device)?;if !at.is_empty() {@@ -2534,6 +2757,8 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {nectarlink_core::TOGGLES_FLASHLIGHT,nectarlink_core::TOGGLES_DND,nectarlink_core::TOGGLES_BRIGHTNESS,+ nectarlink_core::STORAGE_READ,+ nectarlink_core::STORAGE_WRITE,].map(str::to_owned),);@@ -3477,6 +3702,16 @@ fn print_event(node: &Node, event: &NodeEvent) {name(device),device.short()),+ NodeEvent::StorageRequested { device } => println!(+ "{}: asked to browse phone storage (allow with: nectarlink toggle {} storage on)",+ name(device),+ device.short()+ ),+ NodeEvent::StorageChanged { device, path } => println!(+ "{}: storage folder {} changed",+ name(device),+ if path.is_empty() { "/" } else { path.as_str() }+ ),NodeEvent::PhotoAdded { device, photo } => println!("{}: new {} {} ({} bytes, preview {} bytes)",name(device),diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rsindex f8c379c..5327b28 100644--- a/core/nectarlink-core/src/config.rs+++ b/core/nectarlink-core/src/config.rs@@ -293,6 +293,45 @@ pub trait Platform: Send + Sync + 'static {fn deck_press(&self, _from: &nectarlink_protocol::DeviceId, _tile: &str) -> Result<(), String> {Err("this device has no deck actions".into())}++ /// List immediate children of `path` (`""` for the shared storage root) on+ /// this phone (`storage.list`, `docs/protocol/storage.md`).+ fn storage_list(&self, _path: &str) -> Result<Vec<crate::StorageEntry>, crate::StorageError> {+ Err(crate::StorageError::Unsupported)+ }++ /// Open a file in this phone's shared storage for ranged reading (`storage.read`).+ fn storage_open_read(&self, _path: &str) -> Result<crate::StorageReadFile, crate::StorageError> {+ Err(crate::StorageError::Unsupported)+ }++ /// Commit a fully staged upload (`staged`) to `path` in this phone's shared+ /// storage (`storage.write`).+ fn storage_write(+ &self,+ _path: &str,+ _staged: &std::path::Path,+ _modified: Option<i64>,+ ) -> Result<crate::StorageWriteDone, crate::StorageError> {+ Err(crate::StorageError::Unsupported)+ }++ /// Create directory `path` in this phone's shared storage (`storage.mkdir`).+ fn storage_mkdir(&self, _path: &str) -> Result<(), crate::StorageError> {+ Err(crate::StorageError::Unsupported)+ }++ /// Rename or move `from` to `to` in this phone's shared storage (`storage.rename`).+ fn storage_rename(&self, _from: &str, _to: &str) -> Result<(), crate::StorageError> {+ Err(crate::StorageError::Unsupported)+ }++ /// Delete `path` in this phone's shared storage (`storage.delete`). Media+ /// items move to the phone's trash where supported; otherwise deletion+ /// requires `confirmed == true`.+ fn storage_delete(&self, _path: &str, _confirmed: bool) -> Result<(), crate::StorageError> {+ Err(crate::StorageError::Unsupported)+ }}/// A platform that does nothing; useful for tests and headless tools.diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rsindex 015d195..437e115 100644--- a/core/nectarlink-core/src/events.rs+++ b/core/nectarlink-core/src/events.rs@@ -192,4 +192,14 @@ pub enum NodeEvent {device: DeviceId,state: crate::DeckState,},+ /// A paired PC asked to access this phone's storage while its `storage`+ /// toggle is off (emitted once per PC so the phone UI can prompt the user).+ StorageRequested {+ device: DeviceId,+ },+ /// A folder in a paired phone's shared storage changed (`docs/protocol/storage.md`).+ StorageChanged {+ device: DeviceId,+ path: String,+ },}diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rsindex 322bb32..978843b 100644--- a/core/nectarlink-core/src/features.rs+++ b/core/nectarlink-core/src/features.rs@@ -34,6 +34,7 @@ pub enum Permission {Phone,Contacts,Photos,+ Storage,Camera,Microphone,}@@ -48,6 +49,7 @@ impl Permission {Permission::Phone => "phone",Permission::Contacts => "contacts",Permission::Photos => "photos",+ Permission::Storage => "storage",Permission::Camera => "camera",Permission::Microphone => "microphone",}@@ -341,6 +343,8 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[("toggles", true),("pc_actions", true),("mirroring", true),+ // Browsing the phone's storage on a PC is opt-in.+ ("storage", false),// Controlling this PC's mouse and keyboard is opt-in.("remote_input", false),// Running custom Deck commands on this PC is opt-in.@@ -760,6 +764,17 @@ pub const FEATURES: &[FeatureDef] = &[requires: &[phone("files.transfer", UPDATE), desktop("recorder", UPDATE), DeviceToggle("recordings")],partial: None,},+ FeatureDef {+ id: "files.storage",+ group: FeatureGroup::Files,+ requires: &[+ phone("storage.read", Unlock::Permission(Permission::Storage)),+ phone("storage.write", Unlock::Permission(Permission::Storage)),+ desktop("storage.mount", UPDATE),+ DeviceToggle("storage"),+ ],+ partial: None,+ },// MirroringFeatureDef {id: "mirroring.view",diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rsindex 30e4599..ab272d3 100644--- a/core/nectarlink-core/src/lib.rs+++ b/core/nectarlink-core/src/lib.rs@@ -25,6 +25,7 @@ mod photos;pub mod remote;mod session;mod sms;+pub mod storage;mod store;pub mod toggles;mod transfer;@@ -57,13 +58,16 @@ pub use nectarlink_protocol::{DeviceKind, MediaPlayer, MirrorAudioConfig, MirrorConfig, MirrorInput, MirrorResize, MirrorStart,Notification, NotificationAction, PcWakeInfo, PhoneApp, PhoneToggleSet, PhoneToggleValue,PhoneToggles, PhotoAlbum, PhotoItem, PhotoNew as Photo, PhotoThumb, PowerLevel, SmsMessage, SmsPart,- SmsThread, TouchAction,+ SmsThread, StorageChanged, StorageDelete, StorageEntries, StorageEntry, StorageList, StorageMkdir,+ StorageRead, StorageReadMeta, StorageRename, StorageWriteAccept, StorageWriteDone, StorageWriteOffer,+ TouchAction,calls::{CONTROL as CALLS_CONTROL, DIAL as CALLS_DIAL, IN_CALL as CALLS_IN_CALL, LOG as CALLS_LOG,SHOW as CALLS_SHOW, STATE as CALLS_STATE,},contacts::{READ as CONTACTS_READ, SHOW as CONTACTS_SHOW},- format_mac, ipv4_broadcast, is_package_name, magic_packet,+ format_mac, ipv4_broadcast, is_package_name, is_valid_storage_dir_path, is_valid_storage_id,+ is_valid_storage_name, is_valid_storage_path, magic_packet,mirror::{AUDIO as MIRROR_AUDIO, AUDIO_PLAYBACK as MIRROR_AUDIO_PLAYBACK, CAPTURE as MIRROR_CAPTURE,INPUT as MIRROR_INPUT, LISTEN as MIRROR_LISTEN, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES,@@ -78,6 +82,7 @@ pub use nectarlink_protocol::{},ringer_modes,sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},+ storage::{MOUNT as STORAGE_MOUNT, READ as STORAGE_READ, WRITE as STORAGE_WRITE},toggle_ids,toggles::{BLUETOOTH as TOGGLES_BLUETOOTH, BRIGHTNESS as TOGGLES_BRIGHTNESS, DND as TOGGLES_DND,@@ -90,6 +95,7 @@ pub use nectarlink_protocol::{pub use node::Node;pub use notifications::NotificationError;pub use remote::{ButtonAction, INPUT_INJECT, KeyMod, MouseButton, RemoteInput, SlideAction, remote_keys};+pub use storage::{FolderStorage, StorageError, StorageReadFile, TOGGLE as STORAGE_TOGGLE};pub use transfer::{Direction, FileSource, OutgoingFile, RECORDER, RecordingMarker, Transfer, TransferFailure, TransferState,outgoing_paths, safe_file_name,diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rsindex e2602e3..0ec58b8 100644--- a/core/nectarlink-core/src/node.rs+++ b/core/nectarlink-core/src/node.rs@@ -130,6 +130,8 @@ pub(crate) struct Shared {pub(crate) mirror_stops: Mutex<HashMap<MirrorStop, Arc<tokio::sync::Notify>>>,/// Per-peer rate limiters and prompt state for remote input.pub(crate) remote: Mutex<crate::remote::RemoteState>,+ /// Per-peer prompt state and open folders for the storage service.+ pub(crate) storage: Mutex<crate::storage::StorageState>,pub data_dir: std::path::PathBuf,/// Where received files go.pub downloads_dir: std::path::PathBuf,@@ -315,6 +317,7 @@ impl Shared {lock(&self.links).remove(peer);lock(&self.matrices).remove(peer);lock(&self.remote).remove_peer(peer);+ lock(&self.storage).remove_peer(peer);self.toggles.remove_peer(peer);self.deck.remove_peer(peer);if existed {@@ -398,6 +401,7 @@ impl Shared {let current = sessions.get(&ended.peer).is_some_and(|current| Arc::ptr_eq(current, ended));if current {sessions.remove(&ended.peer);+ lock(&self.storage).remove_peer(&ended.peer);self.toggles.remove_peer(&ended.peer);self.deck.remove_peer(&ended.peer);if paired {@@ -651,6 +655,7 @@ impl Node {deck: Default::default(),mirror_stops: Mutex::new(HashMap::new()),remote: Mutex::new(Default::default()),+ storage: Mutex::new(Default::default()),data_dir: config.data_dir.clone(),downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),transfers: Mutex::new(HashMap::new()),@@ -889,6 +894,14 @@ impl Node {crate::actions::send_wake_info(&shared, &session).await;});}+ if toggle == crate::storage::TOGGLE {+ let mut st = self.shared.storage.lock().unwrap_or_else(|e| e.into_inner());+ if enabled {+ st.clear_prompted(&peer);+ } else {+ st.remove_peer(&peer);+ }+ }Ok(())}@@ -1402,6 +1415,128 @@ impl Node {crate::deck::press(&self.shared, &session, tile).await}+ // ---- Phone storage (PC File Explorer) ----++ /// Lists a directory on a connected phone (`storage.list`).+ pub async fn storage_list(+ &self,+ peer: DeviceId,+ path: impl Into<String>,+ ) -> Result<Vec<crate::StorageEntry>> {+ let session = self.connected(&peer)?;+ crate::storage::list(&self.shared, &session, path.into()).await+ }++ /// Reads a byte range `[offset, offset + length)` (or to end of file if+ /// `length` is `None`) from `path` on a connected phone (`storage.read`).+ pub async fn storage_read(+ &self,+ peer: DeviceId,+ path: impl Into<String>,+ offset: u64,+ length: Option<u64>,+ ) -> Result<(crate::StorageReadMeta, Vec<u8>)> {+ let (meta, mut recv) = self.storage_read_stream(peer, path, offset, length).await?;+ let mut buf = Vec::with_capacity((meta.length.min(16 * 1024 * 1024)) as usize);+ while let Some(chunk) = recv.read_chunk(64 * 1024).await.map_err(|_| crate::Error::Offline)? {+ if (buf.len() + chunk.len()) as u64 > meta.length {+ return Err(crate::Error::Protocol("phone sent more bytes than length".into()));+ }+ buf.extend_from_slice(&chunk);+ }+ if buf.len() as u64 != meta.length {+ return Err(crate::Error::Offline);+ }+ Ok((meta, buf))+ }++ /// Opens a ranged read stream from `path` on a connected phone+ /// (`storage.read`), returning the metadata and raw QUIC receive stream.+ pub async fn storage_read_stream(+ &self,+ peer: DeviceId,+ path: impl Into<String>,+ offset: u64,+ length: Option<u64>,+ ) -> Result<(crate::StorageReadMeta, iroh::endpoint::RecvStream)> {+ let session = self.connected(&peer)?;+ crate::storage::open_read_stream(&self.shared, &session, path.into(), offset, length).await+ }++ /// Uploads a local file to `path` on a connected phone (`storage.write`).+ pub async fn storage_write(+ &self,+ peer: DeviceId,+ path: impl Into<String>,+ source: &std::path::Path,+ ) -> Result<crate::StorageWriteDone> {+ self.storage_write_with_id(peer, path, source, None, None).await+ }++ /// Uploads a local file to `path` on a connected phone (`storage.write`),+ /// reusing `id` when resuming an interrupted upload.+ pub async fn storage_write_with_id(+ &self,+ peer: DeviceId,+ path: impl Into<String>,+ source: &std::path::Path,+ id: Option<String>,+ stop_after: Option<u64>,+ ) -> Result<crate::StorageWriteDone> {+ let session = self.connected(&peer)?;+ let id = id.unwrap_or_else(crate::storage::new_upload_id);+ crate::storage::write_with_id(+ &self.shared,+ &session,+ id,+ path.into(),+ crate::FileSource::Path(source.to_path_buf()),+ None,+ stop_after,+ )+ .await+ }++ /// Creates a directory at `path` on a connected phone (`storage.mkdir`).+ pub async fn storage_mkdir(&self, peer: DeviceId, path: impl Into<String>) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::storage::mkdir(&self.shared, &session, path.into()).await+ }++ /// Renames or moves `from` to `to` on a connected phone (`storage.rename`).+ pub async fn storage_rename(+ &self,+ peer: DeviceId,+ from: impl Into<String>,+ to: impl Into<String>,+ ) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::storage::rename(&self.shared, &session, from.into(), to.into()).await+ }++ /// Deletes `path` on a connected phone (`storage.delete`).+ pub async fn storage_delete(+ &self,+ peer: DeviceId,+ path: impl Into<String>,+ confirmed: bool,+ ) -> Result<()> {+ let session = self.connected(&peer)?;+ crate::storage::delete(&self.shared, &session, path.into(), confirmed).await+ }++ /// Notifies connected PCs that have `path` open in File Explorer that its+ /// contents changed (`storage.changed`, debounced to at most once per second).+ pub async fn storage_changed(&self, path: impl Into<String>) {+ crate::storage::notify_changed(&self.shared, path.into()).await;+ }++ /// Directory paths currently watched by any connected PC (most recently+ /// listed folders).+ pub fn storage_open_folders(&self) -> Vec<String> {+ self.shared.storage.lock().unwrap_or_else(|e| e.into_inner()).open_folders_all()+ }+// ---- Local state reported by the app ----/// Reports this device's battery; forwarded to connected devices.diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rsindex 3954526..7630c9f 100644--- a/core/nectarlink-core/src/session.rs+++ b/core/nectarlink-core/src/session.rs@@ -335,6 +335,10 @@ fn is_background_rpc(t: &str) -> bool {| types::PHOTOS_GET| types::MIRROR_START| types::MIRROR_APPS+ | types::STORAGE_LIST+ | types::STORAGE_MKDIR+ | types::STORAGE_RENAME+ | types::STORAGE_DELETE)}@@ -407,6 +411,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->t if t.starts_with("remote.") && crate::remote::handle(shared, session, &env).await? => {}t if t.starts_with("phone.toggle") && crate::toggles::handle(shared, session, &env).await? => {}t if t.starts_with("deck.") && crate::deck::handle(shared, session, &env).await? => {}+ t if t.starts_with("storage.") && crate::storage::handle(shared, session, &env).await? => {}other => {if env.id.is_some() {let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));diff --git a/core/nectarlink-core/src/storage.rs b/core/nectarlink-core/src/storage.rsnew file mode 100644index 0000000..d545eef--- /dev/null+++ b/core/nectarlink-core/src/storage.rs@@ -0,0 +1,1204 @@+// SPDX-License-Identifier: MPL-2.0+//! Phone storage in File Explorer (`docs/protocol/storage.md`).+//!+//! A phone that offers `storage.read` / `storage.write` lets a paired PC+//! (while the `storage` per-device toggle is on) list directories, read file+//! ranges on a dedicated stream, upload files with resume on a dedicated+//! stream, and create folders, rename and delete entries.++use std::{+ collections::{HashMap, HashSet},+ io::{Read, Seek, SeekFrom},+ path::{Path, PathBuf},+ sync::Arc,+ time::{Duration, Instant, SystemTime, UNIX_EPOCH},+};++use bytes::Bytes;+use iroh::endpoint::{RecvStream, SendStream};+pub use nectarlink_protocol::messages::{+ StorageChanged, StorageDelete, StorageEntries, StorageEntry, StorageList, StorageMkdir, StorageRead,+ StorageReadMeta, StorageRename, StorageWriteAccept, StorageWriteDone, StorageWriteOffer,+ is_valid_storage_dir_path, is_valid_storage_id, is_valid_storage_name, is_valid_storage_path,+ storage::{MOUNT as STORAGE_MOUNT, READ as STORAGE_READ, WRITE as STORAGE_WRITE},+};+use nectarlink_protocol::{+ DeviceId, Envelope, ErrorCode, MAX_FRAME_LEN,+ messages::{StreamHeader, storage, types},+ read_frame, write_frame,+};+use tokio::io::{AsyncSeekExt, AsyncWriteExt};++use crate::{+ Error, NodeEvent, Result,+ node::Shared,+ session::{REQUEST_TIMEOUT, Session},+ transfer::FileSource,+};++/// Per-device toggle name (off by default on the phone).+pub const TOGGLE: &str = "storage";++const STREAM_TIMEOUT: Duration = Duration::from_secs(30);+const CHUNK_SIZE: usize = 64 * 1024;+const MAX_OPEN_FOLDERS_PER_PEER: usize = 256;+const CHANGED_DEBOUNCE: Duration = Duration::from_millis(250);++/// Why a phone storage operation failed on the platform side.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum StorageError {+ NotFound,+ Denied,+ Invalid(String),+ NoSpace,+ Unsupported,+ Failed(String),+}++impl StorageError {+ pub fn into_code_and_msg(self) -> (ErrorCode, String) {+ match self {+ StorageError::NotFound => (ErrorCode::NotFound, "not found".into()),+ StorageError::Denied => (ErrorCode::Denied, "access denied".into()),+ StorageError::Invalid(m) => (ErrorCode::BadMessage, m),+ StorageError::NoSpace => (ErrorCode::Busy, "not enough space".into()),+ StorageError::Unsupported => (ErrorCode::Unsupported, "storage not available".into()),+ StorageError::Failed(m) => (ErrorCode::Internal, m),+ }+ }+}++/// An opened file on the phone ready for ranged reading (`storage.read`).+#[derive(Debug)]+pub struct StorageReadFile {+ pub source: FileSource,+ pub size: u64,+ /// Last-modified time in Unix milliseconds.+ pub modified: i64,+}++/// Per-node state for the storage service: one-time prompt tracking, folders+/// each connected PC has listed, and debounce timestamps for `storage.changed`.+#[derive(Debug, Default)]+pub(crate) struct StorageState {+ prompted: HashSet<DeviceId>,+ open_folders: HashMap<DeviceId, HashSet<String>>,+ last_changed: HashMap<(DeviceId, String), Instant>,+}++impl StorageState {+ pub fn mark_prompted(&mut self, peer: DeviceId) -> bool {+ self.prompted.insert(peer)+ }++ pub fn clear_prompted(&mut self, peer: &DeviceId) {+ self.prompted.remove(peer);+ }++ pub fn record_open_folder(&mut self, peer: DeviceId, path: &str) {+ let set = self.open_folders.entry(peer).or_default();+ if set.len() >= MAX_OPEN_FOLDERS_PER_PEER && !set.contains(path) {+ set.clear();+ }+ set.insert(path.to_owned());+ }++ pub fn open_folders_all(&self) -> Vec<String> {+ let mut out: HashSet<String> = HashSet::new();+ for set in self.open_folders.values() {+ for p in set {+ out.insert(p.clone());+ }+ }+ let mut v: Vec<String> = out.into_iter().collect();+ v.sort();+ v+ }++ pub fn peers_watching(&mut self, path: &str, now: Instant) -> Vec<DeviceId> {+ let mut peers = Vec::new();+ for (peer, folders) in &self.open_folders {+ if folders.contains(path) {+ let key = (*peer, path.to_owned());+ let should_send = self+ .last_changed+ .get(&key)+ .is_none_or(|prev| now.saturating_duration_since(*prev) >= CHANGED_DEBOUNCE);+ if should_send {+ self.last_changed.insert(key, now);+ peers.push(*peer);+ }+ }+ }+ peers+ }++ pub fn remove_peer(&mut self, peer: &DeviceId) {+ self.prompted.remove(peer);+ self.open_folders.remove(peer);+ self.last_changed.retain(|(p, _), _| p != peer);+ }+}++fn peer_offers(shared: &Shared, peer: &DeviceId, cap: &str) -> Result<bool> {+ Ok(shared.store.get_peer(peer)?.is_some_and(|p| p.caps.contains(cap)))+}++fn we_offer(shared: &Shared, cap: &str) -> bool {+ shared.local_capabilities().iter().any(|c| c == cap)+}++/// Checks if the PC user explicitly turned `storage` off for `peer`.+fn pc_allows(shared: &Shared, peer: &DeviceId) -> Result<bool> {+ Ok(shared.store.toggles(peer)?.get(TOGGLE).copied().unwrap_or(true))+}++fn check_phone_allowed(+ shared: &Shared,+ peer: &DeviceId,+ cap: &str,+) -> std::result::Result<(), (ErrorCode, String)> {+ if !we_offer(shared, cap) {+ return Err((ErrorCode::Unsupported, format!("{cap} is not offered by this device")));+ }+ if !shared.toggle_on(peer, TOGGLE) {+ let first_time = shared.storage.lock().unwrap_or_else(|e| e.into_inner()).mark_prompted(*peer);+ if first_time {+ shared.emit(NodeEvent::StorageRequested { device: *peer });+ }+ return Err((ErrorCode::Denied, "storage access is turned off for this device".into()));+ }+ Ok(())+}++fn parent_dir_of(path: &str) -> &str {+ match path.rfind('/') {+ Some(idx) => &path[..idx],+ None => "",+ }+}++/// Notifies connected PCs that have `path` open that its contents changed.+pub(crate) async fn notify_changed(shared: &Arc<Shared>, path: String) {+ if !is_valid_storage_dir_path(&path) {+ return;+ }+ let peers = {+ let mut st = shared.storage.lock().unwrap_or_else(|e| e.into_inner());+ st.peers_watching(&path, Instant::now())+ };+ if peers.is_empty() {+ return;+ }+ let Ok(env) = Envelope::new(types::STORAGE_CHANGED, &StorageChanged { path }) else {+ return;+ };+ for peer in peers {+ if shared.toggle_on(&peer, TOGGLE)+ && let Some(session) = shared.session(&peer)+ {+ let _ = session.send(env.clone()).await;+ }+ }+}++async fn notify_parent_changed(shared: &Arc<Shared>, path: &str) {+ notify_changed(shared, parent_dir_of(path).to_owned()).await;+}++/// Handles incoming `storage.*` messages on the control stream.+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {+ let peer = session.peer;+ match env.t.as_str() {+ types::STORAGE_LIST => {+ let req = match env.body::<StorageList>() {+ Ok(r) if r.is_valid() => r,+ _ => {+ let reply =+ Envelope::error(ErrorCode::BadMessage, "invalid storage.list path").reply_to(env.id);+ session.send(reply).await?;+ return Ok(true);+ }+ };+ if let Err((code, msg)) = check_phone_allowed(shared, &peer, STORAGE_READ) {+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ return Ok(true);+ }+ shared.storage.lock().unwrap_or_else(|e| e.into_inner()).record_open_folder(peer, &req.path);+ let platform = shared.platform.clone();+ let path = req.path;+ let res = tokio::task::spawn_blocking(move || platform.storage_list(&path))+ .await+ .unwrap_or_else(|e| Err(StorageError::Failed(e.to_string())));+ match res {+ Ok(raw_entries) => {+ let mut entries: Vec<StorageEntry> =+ raw_entries.into_iter().filter_map(StorageEntry::sanitized).collect();+ // Sort directories first, then case-insensitively by name.+ entries.sort_by(|a, b| {+ b.is_dir+ .cmp(&a.is_dir)+ .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))+ .then_with(|| a.name.cmp(&b.name))+ });+ // Ensure the frame fits within MAX_FRAME_LEN.+ let reply = loop {+ let body = StorageEntries { entries: entries.clone() };+ let candidate = Envelope::new(types::STORAGE_ENTRIES, &body)?.reply_to(env.id);+ if candidate.to_cbor().len() <= MAX_FRAME_LEN || entries.is_empty() {+ break candidate;+ }+ let new_len = (entries.len() * 3 / 4).max(entries.len().saturating_sub(1));+ entries.truncate(new_len);+ };+ session.send(reply).await?;+ }+ Err(err) => {+ let (code, msg) = err.into_code_and_msg();+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ }+ }+ Ok(true)+ }+ types::STORAGE_MKDIR => {+ let req = match env.body::<StorageMkdir>() {+ Ok(r) if r.is_valid() => r,+ _ => {+ let reply =+ Envelope::error(ErrorCode::BadMessage, "invalid storage.mkdir path").reply_to(env.id);+ session.send(reply).await?;+ return Ok(true);+ }+ };+ if let Err((code, msg)) = check_phone_allowed(shared, &peer, STORAGE_WRITE) {+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ return Ok(true);+ }+ let platform = shared.platform.clone();+ let path = req.path.clone();+ let res = tokio::task::spawn_blocking(move || platform.storage_mkdir(&path))+ .await+ .unwrap_or_else(|e| Err(StorageError::Failed(e.to_string())));+ match res {+ Ok(()) => {+ session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;+ notify_parent_changed(shared, &req.path).await;+ }+ Err(err) => {+ let (code, msg) = err.into_code_and_msg();+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ }+ }+ Ok(true)+ }+ types::STORAGE_RENAME => {+ let req = match env.body::<StorageRename>() {+ Ok(r) if r.is_valid() => r,+ _ => {+ let reply = Envelope::error(ErrorCode::BadMessage, "invalid storage.rename paths")+ .reply_to(env.id);+ session.send(reply).await?;+ return Ok(true);+ }+ };+ if let Err((code, msg)) = check_phone_allowed(shared, &peer, STORAGE_WRITE) {+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ return Ok(true);+ }+ let platform = shared.platform.clone();+ let from = req.from.clone();+ let to = req.to.clone();+ let res = tokio::task::spawn_blocking(move || platform.storage_rename(&from, &to))+ .await+ .unwrap_or_else(|e| Err(StorageError::Failed(e.to_string())));+ match res {+ Ok(()) => {+ session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;+ notify_parent_changed(shared, &req.from).await;+ if parent_dir_of(&req.from) != parent_dir_of(&req.to) {+ notify_parent_changed(shared, &req.to).await;+ }+ }+ Err(err) => {+ let (code, msg) = err.into_code_and_msg();+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ }+ }+ Ok(true)+ }+ types::STORAGE_DELETE => {+ let req = match env.body::<StorageDelete>() {+ Ok(r) if r.is_valid() => r,+ _ => {+ let reply = Envelope::error(ErrorCode::BadMessage, "invalid storage.delete path")+ .reply_to(env.id);+ session.send(reply).await?;+ return Ok(true);+ }+ };+ if let Err((code, msg)) = check_phone_allowed(shared, &peer, STORAGE_WRITE) {+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ return Ok(true);+ }+ let platform = shared.platform.clone();+ let path = req.path.clone();+ let confirmed = req.confirmed;+ let res = tokio::task::spawn_blocking(move || platform.storage_delete(&path, confirmed))+ .await+ .unwrap_or_else(|e| Err(StorageError::Failed(e.to_string())));+ match res {+ Ok(()) => {+ session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;+ notify_parent_changed(shared, &req.path).await;+ }+ Err(err) => {+ let (code, msg) = err.into_code_and_msg();+ session.send(Envelope::error(code, msg).reply_to(env.id)).await?;+ }+ }+ Ok(true)+ }+ types::STORAGE_CHANGED => {+ if let Ok(changed) = env.body::<StorageChanged>()+ && changed.is_valid()+ && pc_allows(shared, &peer).unwrap_or(true)+ {+ shared.emit(NodeEvent::StorageChanged { device: peer, path: changed.path });+ }+ Ok(true)+ }+ _ => Ok(false),+ }+}++/// Serves an incoming `storage/read` stream on the phone (`docs/protocol/storage.md` §4.1).+pub(crate) async fn serve_read(+ shared: Arc<Shared>,+ peer: DeviceId,+ mut send: SendStream,+ mut recv: RecvStream,+) {+ let Ok(Ok(Some(bytes))) = tokio::time::timeout(STREAM_TIMEOUT, read_frame(&mut recv)).await else {+ return;+ };+ let Ok(env) = Envelope::from_cbor(&bytes) else {+ return;+ };+ let req = match env.expect_body::<StorageRead>(types::STORAGE_READ) {+ Ok(r) if r.is_valid() => r,+ _ => {+ let reply = Envelope::error(ErrorCode::BadMessage, "invalid storage.read").reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }+ };+ if let Err((code, msg)) = check_phone_allowed(&shared, &peer, STORAGE_READ) {+ let reply = Envelope::error(code, msg).reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }++ let platform = shared.platform.clone();+ let path = req.path.clone();+ let opened = tokio::task::spawn_blocking(move || platform.storage_open_read(&path))+ .await+ .unwrap_or_else(|e| Err(StorageError::Failed(e.to_string())));++ let file = match opened {+ Ok(f) => f,+ Err(err) => {+ let (code, msg) = err.into_code_and_msg();+ let reply = Envelope::error(code, msg).reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }+ };++ let avail = file.size.saturating_sub(req.offset);+ let to_send = req.length.map_or(avail, |l| l.min(avail));+ let meta = StorageReadMeta { size: file.size, modified: file.modified.max(0), length: to_send };+ let Ok(reply) = Envelope::new(types::STORAGE_READ_META, &meta).map(|e| e.reply_to(env.id)) else {+ return;+ };+ if write_frame(&mut send, &reply.to_cbor()).await.is_err() {+ return;+ }+ if to_send == 0 {+ let _ = send.finish();+ return;+ }++ let offset = req.offset;+ let source = file.source;+ let (tx, mut rx) = tokio::sync::mpsc::channel::<std::result::Result<Bytes, String>>(8);+ tokio::task::spawn_blocking(move || {+ let mut std_file: std::fs::File = match source {+ FileSource::Path(p) => match std::fs::File::open(p) {+ Ok(f) => f,+ Err(e) => {+ let _ = tx.blocking_send(Err(e.to_string()));+ return;+ }+ },+ FileSource::File(f) => f,+ };+ if offset > 0 && std_file.seek(SeekFrom::Start(offset)).is_err() {+ let _ = tx.blocking_send(Err("seek failed".into()));+ return;+ }+ let mut remaining = to_send;+ while remaining > 0 {+ let want = (remaining as usize).min(CHUNK_SIZE);+ let mut buf = vec![0u8; want];+ match std_file.read(&mut buf) {+ Ok(0) => break,+ Ok(n) => {+ buf.truncate(n);+ remaining -= n as u64;+ if tx.blocking_send(Ok(Bytes::from(buf))).is_err() {+ return;+ }+ }+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,+ Err(e) => {+ let _ = tx.blocking_send(Err(e.to_string()));+ return;+ }+ }+ }+ });++ while let Some(chunk) = rx.recv().await {+ match chunk {+ Ok(bytes) => {+ if send.write_chunk(bytes).await.is_err() {+ return;+ }+ }+ Err(_) => return,+ }+ }+ let _ = send.finish();+}++fn staging_file_path(shared: &Shared, peer: &DeviceId, offer: &StorageWriteOffer) -> PathBuf {+ use std::hash::{Hash, Hasher};+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ offer.path.hash(&mut hasher);+ offer.size.hash(&mut hasher);+ let path_hash = hasher.finish();+ shared+ .incoming_dir()+ .join("storage")+ .join(peer.to_string())+ .join(format!("{}-{path_hash:016x}.part", offer.id))+}++/// Serves an incoming `storage/write` stream on the phone (`docs/protocol/storage.md` §4.2).+pub(crate) async fn serve_write(+ shared: Arc<Shared>,+ peer: DeviceId,+ mut send: SendStream,+ mut recv: RecvStream,+) {+ let Ok(Ok(Some(bytes))) = tokio::time::timeout(STREAM_TIMEOUT, read_frame(&mut recv)).await else {+ return;+ };+ let Ok(env) = Envelope::from_cbor(&bytes) else {+ return;+ };+ let offer = match env.expect_body::<StorageWriteOffer>(types::STORAGE_WRITE) {+ Ok(o) if o.is_valid() => o,+ _ => {+ let reply = Envelope::error(ErrorCode::BadMessage, "invalid storage.write").reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }+ };+ if let Err((code, msg)) = check_phone_allowed(&shared, &peer, STORAGE_WRITE) {+ let reply = Envelope::error(code, msg).reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }++ let part_path = staging_file_path(&shared, &peer, &offer);+ if let Some(parent) = part_path.parent()+ && tokio::fs::create_dir_all(parent).await.is_err()+ {+ let reply = Envelope::error(ErrorCode::Internal, "cannot create staging directory").reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }++ let existing_len = tokio::fs::metadata(&part_path).await.map(|m| m.len()).unwrap_or(0);+ let have = if existing_len <= offer.size { existing_len } else { 0 };++ let mut file = match tokio::fs::OpenOptions::new()+ .create(true)+ .write(true)+ .truncate(have == 0)+ .open(&part_path)+ .await+ {+ Ok(f) => f,+ Err(_) => {+ let reply = Envelope::error(ErrorCode::Internal, "cannot open staging file").reply_to(env.id);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }+ };+ if have > 0 && file.seek(SeekFrom::Start(have)).await.is_err() {+ let _ = tokio::fs::remove_file(&part_path).await;+ return;+ }++ let Ok(accept) =+ Envelope::new(types::STORAGE_WRITE_ACCEPT, &StorageWriteAccept { have }).map(|e| e.reply_to(env.id))+ else {+ return;+ };+ if write_frame(&mut send, &accept.to_cbor()).await.is_err() {+ return;+ }++ let mut received = have;+ while received < offer.size {+ match tokio::time::timeout(STREAM_TIMEOUT, recv.read_chunk(CHUNK_SIZE)).await {+ Ok(Ok(Some(chunk))) => {+ if chunk.is_empty() {+ break;+ }+ let next = received.saturating_add(chunk.len() as u64);+ if next > offer.size {+ let _ = file.flush().await;+ drop(file);+ let _ = tokio::fs::remove_file(&part_path).await;+ let reply = Envelope::error(ErrorCode::BadMessage, "too many bytes sent");+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }+ if file.write_all(&chunk).await.is_err() {+ let _ = file.flush().await;+ let reply = Envelope::error(ErrorCode::Busy, "write failed");+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ return;+ }+ received = next;+ }+ Ok(Ok(None)) => break,+ _ => {+ let _ = file.flush().await;+ return;+ }+ }+ }++ if file.flush().await.is_err() || file.sync_all().await.is_err() {+ return;+ }+ drop(file);++ if received != offer.size {+ // Keep the partial staging file so a retry with the same `id` resumes.+ return;+ }++ let platform = shared.platform.clone();+ let dest_path = offer.path.clone();+ let staged = part_path.clone();+ let modified = offer.modified;+ let res = tokio::task::spawn_blocking(move || platform.storage_write(&dest_path, &staged, modified))+ .await+ .unwrap_or_else(|e| Err(StorageError::Failed(e.to_string())));+ let _ = tokio::fs::remove_file(&part_path).await;++ match res {+ Ok(done) => {+ if let Ok(env) = Envelope::new(types::STORAGE_WRITE_DONE, &done) {+ let _ = write_frame(&mut send, &env.to_cbor()).await;+ }+ let _ = send.finish();+ // Let the confirmation reach the sender before the stream closes.+ let _ = tokio::time::timeout(Duration::from_secs(2), send.stopped()).await;+ notify_parent_changed(&shared, &offer.path).await;+ }+ Err(err) => {+ let (code, msg) = err.into_code_and_msg();+ let reply = Envelope::error(code, msg);+ let _ = write_frame(&mut send, &reply.to_cbor()).await;+ let _ = send.finish();+ let _ = tokio::time::timeout(Duration::from_secs(2), send.stopped()).await;+ }+ }+}++// ---- PC-side client operations ----++pub(crate) fn new_upload_id() -> String {+ const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz0123456789";+ (0..24).map(|_| ALPHABET[rand::random_range(0..ALPHABET.len())] as char).collect()+}++pub(crate) async fn list(+ shared: &Arc<Shared>,+ session: &Arc<Session>,+ path: String,+) -> Result<Vec<StorageEntry>> {+ if !is_valid_storage_dir_path(&path) {+ return Err(Error::Protocol("invalid storage directory path".into()));+ }+ if !peer_offers(shared, &session.peer, STORAGE_READ)? {+ return Err(Error::Unsupported);+ }+ if !pc_allows(shared, &session.peer)? {+ return Err(Error::Denied);+ }+ let req = Envelope::new(types::STORAGE_LIST, &StorageList { path })?;+ let reply = session.request(req, REQUEST_TIMEOUT).await?;+ let body: StorageEntries = reply.expect_body(types::STORAGE_ENTRIES)?;+ Ok(body.entries.into_iter().filter_map(StorageEntry::sanitized).collect())+}++pub(crate) async fn mkdir(shared: &Arc<Shared>, session: &Arc<Session>, path: String) -> Result<()> {+ if !is_valid_storage_path(&path) {+ return Err(Error::Protocol("invalid storage path".into()));+ }+ if !peer_offers(shared, &session.peer, STORAGE_WRITE)? {+ return Err(Error::Unsupported);+ }+ if !pc_allows(shared, &session.peer)? {+ return Err(Error::Denied);+ }+ let req = Envelope::new(types::STORAGE_MKDIR, &StorageMkdir { path })?;+ session.request(req, REQUEST_TIMEOUT).await?.expect(types::OK)?;+ Ok(())+}++pub(crate) async fn rename(+ shared: &Arc<Shared>,+ session: &Arc<Session>,+ from: String,+ to: String,+) -> Result<()> {+ let body = StorageRename { from, to };+ if !body.is_valid() {+ return Err(Error::Protocol("invalid storage rename path".into()));+ }+ if !peer_offers(shared, &session.peer, STORAGE_WRITE)? {+ return Err(Error::Unsupported);+ }+ if !pc_allows(shared, &session.peer)? {+ return Err(Error::Denied);+ }+ let req = Envelope::new(types::STORAGE_RENAME, &body)?;+ session.request(req, REQUEST_TIMEOUT).await?.expect(types::OK)?;+ Ok(())+}++pub(crate) async fn delete(+ shared: &Arc<Shared>,+ session: &Arc<Session>,+ path: String,+ confirmed: bool,+) -> Result<()> {+ let body = StorageDelete { path, confirmed };+ if !body.is_valid() {+ return Err(Error::Protocol("invalid storage delete path".into()));+ }+ if !peer_offers(shared, &session.peer, STORAGE_WRITE)? {+ return Err(Error::Unsupported);+ }+ if !pc_allows(shared, &session.peer)? {+ return Err(Error::Denied);+ }+ let req = Envelope::new(types::STORAGE_DELETE, &body)?;+ session.request(req, REQUEST_TIMEOUT).await?.expect(types::OK)?;+ Ok(())+}++/// Opens a ranged read stream for `path` on `session`, returning the+/// [`StorageReadMeta`] and the raw QUIC [`RecvStream`].+pub(crate) async fn open_read_stream(+ shared: &Arc<Shared>,+ session: &Arc<Session>,+ path: String,+ offset: u64,+ length: Option<u64>,+) -> Result<(StorageReadMeta, RecvStream)> {+ let req = StorageRead { path, offset, length };+ if !req.is_valid() {+ return Err(Error::Protocol("invalid storage read path".into()));+ }+ if !peer_offers(shared, &session.peer, STORAGE_READ)? {+ return Err(Error::Unsupported);+ }+ if !pc_allows(shared, &session.peer)? {+ return Err(Error::Denied);+ }++ let (mut send, mut recv) = session.open_bi().await?;+ let header =+ StreamHeader { svc: storage::SERVICE.into(), op: storage::OP_READ.into(), v: storage::VERSION };+ let header_env = Envelope::new(types::STREAM, &header)?;+ let req_env = Envelope::new(types::STORAGE_READ, &req)?.with_id(1);+ write_frame(&mut send, &header_env.to_cbor()).await?;+ write_frame(&mut send, &req_env.to_cbor()).await?;+ let _ = send.finish();++ let reply_bytes = match tokio::time::timeout(STREAM_TIMEOUT, read_frame(&mut recv)).await {+ Ok(Ok(Some(b))) => b,+ Ok(Ok(None)) => return Err(Error::Offline),+ Ok(Err(e)) => return Err(e.into()),+ Err(_) => return Err(Error::Timeout),+ };+ let reply = Envelope::from_cbor(&reply_bytes)?;+ let meta: StorageReadMeta = reply.expect_body(types::STORAGE_READ_META)?;+ Ok((meta, recv))+}++/// Uploads `source` to `path` on `session` with resumable upload ID `id`.+/// If `stop_after` is `Some(limit)`, stops sending after `limit` total bytes+/// (used by tests to simulate an interrupted upload before resuming).+pub(crate) async fn write_with_id(+ shared: &Arc<Shared>,+ session: &Arc<Session>,+ id: String,+ path: String,+ source: FileSource,+ modified: Option<i64>,+ stop_after: Option<u64>,+) -> Result<StorageWriteDone> {+ if !is_valid_storage_id(&id) || !is_valid_storage_path(&path) {+ return Err(Error::Protocol("invalid storage write offer".into()));+ }+ if !peer_offers(shared, &session.peer, STORAGE_WRITE)? {+ return Err(Error::Unsupported);+ }+ if !pc_allows(shared, &session.peer)? {+ return Err(Error::Denied);+ }++ let (std_file, size, file_mtime) =+ tokio::task::spawn_blocking(move || -> Result<(std::fs::File, u64, Option<i64>)> {+ let f = match source {+ FileSource::Path(p) => std::fs::File::open(&p)?,+ FileSource::File(f) => f,+ };+ let meta = f.metadata()?;+ if !meta.is_file() {+ return Err(Error::Protocol("storage write source must be a regular file".into()));+ }+ let mtime = meta+ .modified()+ .ok()+ .and_then(|t| t.duration_since(UNIX_EPOCH).ok())+ .and_then(|d| i64::try_from(d.as_millis()).ok());+ Ok((f, meta.len(), mtime))+ })+ .await+ .map_err(|e| Error::Internal(e.to_string()))??;++ let offer = StorageWriteOffer { id, path, size, modified: modified.or(file_mtime) };+ if !offer.is_valid() {+ return Err(Error::Protocol("invalid storage write offer".into()));+ }++ let (mut send, mut recv) = session.open_bi().await?;+ let header =+ StreamHeader { svc: storage::SERVICE.into(), op: storage::OP_WRITE.into(), v: storage::VERSION };+ let header_env = Envelope::new(types::STREAM, &header)?;+ let offer_env = Envelope::new(types::STORAGE_WRITE, &offer)?.with_id(1);+ write_frame(&mut send, &header_env.to_cbor()).await?;+ write_frame(&mut send, &offer_env.to_cbor()).await?;++ let accept_bytes = match tokio::time::timeout(STREAM_TIMEOUT, read_frame(&mut recv)).await {+ Ok(Ok(Some(b))) => b,+ Ok(Ok(None)) => return Err(Error::Offline),+ Ok(Err(e)) => return Err(e.into()),+ Err(_) => return Err(Error::Timeout),+ };+ let accept_env = Envelope::from_cbor(&accept_bytes)?;+ let accept: StorageWriteAccept = accept_env.expect_body(types::STORAGE_WRITE_ACCEPT)?;+ let start = accept.have.min(size);+ let target_end = stop_after.map_or(size, |limit| limit.min(size));++ if target_end > start {+ let to_read = target_end - start;+ let (tx, mut rx) = tokio::sync::mpsc::channel::<std::result::Result<Bytes, std::io::Error>>(8);+ tokio::task::spawn_blocking(move || {+ let mut f = std_file;+ if start > 0+ && let Err(e) = f.seek(SeekFrom::Start(start))+ {+ let _ = tx.blocking_send(Err(e));+ return;+ }+ let mut rem = to_read;+ while rem > 0 {+ let want = (rem as usize).min(CHUNK_SIZE);+ let mut buf = vec![0u8; want];+ match f.read(&mut buf) {+ Ok(0) => break,+ Ok(n) => {+ buf.truncate(n);+ rem -= n as u64;+ if tx.blocking_send(Ok(Bytes::from(buf))).is_err() {+ return;+ }+ }+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,+ Err(e) => {+ let _ = tx.blocking_send(Err(e));+ return;+ }+ }+ }+ });++ while let Some(chunk) = rx.recv().await {+ let bytes = chunk?;+ send.write_chunk(bytes).await.map_err(|_| Error::Offline)?;+ }+ }++ if stop_after.is_some_and(|limit| limit < size) {+ let _ = send.finish();+ return Err(Error::Offline);+ }++ send.finish().map_err(|_| Error::Offline)?;+ let done_bytes = match tokio::time::timeout(STREAM_TIMEOUT, read_frame(&mut recv)).await {+ Ok(Ok(Some(b))) => b,+ Ok(Ok(None)) => return Err(Error::Offline),+ Ok(Err(e)) => return Err(e.into()),+ Err(_) => return Err(Error::Timeout),+ };+ let done_env = Envelope::from_cbor(&done_bytes)?;+ let done: StorageWriteDone = done_env.expect_body(types::STORAGE_WRITE_DONE)?;+ Ok(done)+}++// ---- FolderStorage: filesystem-backed phone storage provider ----++/// Filesystem-backed storage root that enforces relative path validation,+/// blocks `/data` and private directories, and rejects symlinks resolving+/// outside the canonical root.+#[derive(Debug, Clone)]+pub struct FolderStorage {+ root: PathBuf,+ blocked_prefixes: Vec<PathBuf>,+ trash_dir: Option<PathBuf>,+}++impl FolderStorage {+ pub fn new(root: impl Into<PathBuf>) -> Self {+ Self {+ root: root.into(),+ blocked_prefixes: vec![+ PathBuf::from("/data/data"),+ PathBuf::from("/data/user"),+ PathBuf::from("/data/system"),+ PathBuf::from("/data/app"),+ PathBuf::from("/data/misc"),+ ],+ trash_dir: None,+ }+ }++ /// Configures an optional trash directory where unconfirmed deletes of+ /// media files (`.jpg`, `.jpeg`, `.png`, `.webp`, `.gif`, `.mp4`, `.mov`,+ /// `.mp3`, `.m4a`, `.wav`, `.flac`) are moved, matching Android's+ /// `MediaStore` trash behavior.+ pub fn with_trash_dir(mut self, trash: impl Into<PathBuf>) -> Self {+ self.trash_dir = Some(trash.into());+ self+ }++ pub fn root(&self) -> &Path {+ &self.root+ }++ fn canonical_root(&self) -> std::result::Result<PathBuf, StorageError> {+ let canon = std::fs::canonicalize(&self.root).map_err(|_| StorageError::NotFound)?;+ if self.is_blocked(&canon) {+ return Err(StorageError::Denied);+ }+ Ok(canon)+ }++ fn is_blocked(&self, canon: &Path) -> bool {+ if canon == Path::new("/data") {+ return true;+ }+ self.blocked_prefixes.iter().any(|p| canon.starts_with(p))+ }++ fn ensure_inside(&self, canon_root: &Path, candidate: &Path) -> std::result::Result<(), StorageError> {+ if !candidate.starts_with(canon_root) || self.is_blocked(candidate) {+ return Err(StorageError::Denied);+ }+ Ok(())+ }++ /// Resolves an existing directory or file relative to `root`, rejecting+ /// `..`, absolute paths, and any symlink pointing outside `canonical_root`.+ pub fn resolve_existing(+ &self,+ rel: &str,+ allow_root: bool,+ ) -> std::result::Result<PathBuf, StorageError> {+ let valid = if allow_root { is_valid_storage_dir_path(rel) } else { is_valid_storage_path(rel) };+ if !valid {+ return Err(StorageError::Invalid("invalid storage path".into()));+ }+ let canon_root = self.canonical_root()?;+ if rel.is_empty() {+ return Ok(canon_root);+ }+ let mut cur = canon_root.clone();+ for seg in rel.split('/') {+ cur.push(seg);+ let meta = std::fs::symlink_metadata(&cur).map_err(|_| StorageError::NotFound)?;+ if meta.file_type().is_symlink() {+ let target = std::fs::canonicalize(&cur).map_err(|_| StorageError::Denied)?;+ self.ensure_inside(&canon_root, &target)?;+ }+ }+ let canon = std::fs::canonicalize(&cur).map_err(|_| StorageError::NotFound)?;+ self.ensure_inside(&canon_root, &canon)?;+ Ok(canon)+ }++ /// Resolves a destination path (whose final segment or parent directories+ /// might not exist yet) inside `root`, rejecting any symlink along the+ /// existing prefix that points outside `canonical_root`.+ pub fn resolve_target(&self, rel: &str) -> std::result::Result<PathBuf, StorageError> {+ if !is_valid_storage_path(rel) {+ return Err(StorageError::Invalid("invalid storage path".into()));+ }+ let canon_root = self.canonical_root()?;+ let mut cur = canon_root.clone();+ for seg in rel.split('/') {+ cur.push(seg);+ if let Ok(meta) = std::fs::symlink_metadata(&cur)+ && meta.file_type().is_symlink()+ {+ let target = std::fs::canonicalize(&cur).map_err(|_| StorageError::Denied)?;+ self.ensure_inside(&canon_root, &target)?;+ }+ }+ Ok(cur)+ }++ pub fn list(&self, path: &str) -> std::result::Result<Vec<StorageEntry>, StorageError> {+ let dir = self.resolve_existing(path, true)?;+ let canon_root = self.canonical_root()?;+ let meta = std::fs::metadata(&dir).map_err(|_| StorageError::NotFound)?;+ if !meta.is_dir() {+ return Err(StorageError::NotFound);+ }+ let read_dir = std::fs::read_dir(&dir).map_err(|_| StorageError::Denied)?;+ let mut entries = Vec::new();+ for item in read_dir.flatten() {+ let Ok(name) = item.file_name().into_string() else {+ continue;+ };+ if !is_valid_storage_name(&name) || name.starts_with(".nectarlink") {+ continue;+ }+ let item_path = item.path();+ let Ok(canon) = std::fs::canonicalize(&item_path) else {+ continue;+ };+ if self.ensure_inside(&canon_root, &canon).is_err() {+ continue;+ }+ let Ok(md) = std::fs::metadata(&canon) else {+ continue;+ };+ let is_dir = md.is_dir();+ if !is_dir && !md.is_file() {+ continue;+ }+ let modified = system_time_ms(md.modified().ok());+ entries.push(StorageEntry { name, size: if is_dir { 0 } else { md.len() }, modified, is_dir });+ }+ Ok(entries)+ }++ pub fn open_read(&self, path: &str) -> std::result::Result<StorageReadFile, StorageError> {+ let resolved = self.resolve_existing(path, false)?;+ let md = std::fs::metadata(&resolved).map_err(|_| StorageError::NotFound)?;+ if !md.is_file() {+ return Err(StorageError::NotFound);+ }+ Ok(StorageReadFile {+ source: FileSource::Path(resolved),+ size: md.len(),+ modified: system_time_ms(md.modified().ok()),+ })+ }++ pub fn write(+ &self,+ path: &str,+ staged: &Path,+ modified: Option<i64>,+ ) -> std::result::Result<StorageWriteDone, StorageError> {+ let dest = self.resolve_target(path)?;+ if let Some(parent) = dest.parent() {+ std::fs::create_dir_all(parent).map_err(|e| StorageError::Failed(e.to_string()))?;+ }+ let canon_root = self.canonical_root()?;+ if let Some(parent) = dest.parent() {+ let canon_parent = std::fs::canonicalize(parent).map_err(|_| StorageError::Denied)?;+ self.ensure_inside(&canon_root, &canon_parent)?;+ }+ if std::fs::rename(staged, &dest).is_err() {+ std::fs::copy(staged, &dest).map_err(|e| StorageError::Failed(e.to_string()))?;+ }+ if let Some(ms) = modified.filter(|m| *m >= 0)+ && let Some(st) = UNIX_EPOCH.checked_add(Duration::from_millis(ms as u64))+ && let Ok(f) = std::fs::OpenOptions::new().write(true).open(&dest)+ {+ let _ = f.set_modified(st);+ }+ let md = std::fs::metadata(&dest).map_err(|e| StorageError::Failed(e.to_string()))?;+ Ok(StorageWriteDone {+ size: md.len(),+ modified: modified.unwrap_or_else(|| system_time_ms(md.modified().ok())),+ })+ }++ pub fn mkdir(&self, path: &str) -> std::result::Result<(), StorageError> {+ let dest = self.resolve_target(path)?;+ std::fs::create_dir_all(&dest).map_err(|e| StorageError::Failed(e.to_string()))?;+ let canon_root = self.canonical_root()?;+ let canon = std::fs::canonicalize(&dest).map_err(|_| StorageError::Denied)?;+ self.ensure_inside(&canon_root, &canon)+ }++ pub fn rename(&self, from: &str, to: &str) -> std::result::Result<(), StorageError> {+ let src = self.resolve_existing(from, false)?;+ let dst = self.resolve_target(to)?;+ if let Some(parent) = dst.parent() {+ std::fs::create_dir_all(parent).map_err(|e| StorageError::Failed(e.to_string()))?;+ let canon_root = self.canonical_root()?;+ let canon_parent = std::fs::canonicalize(parent).map_err(|_| StorageError::Denied)?;+ self.ensure_inside(&canon_root, &canon_parent)?;+ }+ std::fs::rename(&src, &dst).map_err(|e| StorageError::Failed(e.to_string()))+ }++ pub fn delete(&self, path: &str, confirmed: bool) -> std::result::Result<(), StorageError> {+ let target = self.resolve_existing(path, false)?;+ let md = std::fs::metadata(&target).map_err(|_| StorageError::NotFound)?;+ if let Some(trash_dir) = &self.trash_dir+ && md.is_file()+ && is_media_extension(&target)+ {+ std::fs::create_dir_all(trash_dir).map_err(|e| StorageError::Failed(e.to_string()))?;+ let name = target+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_else(|| "trashed".into());+ let dest = trash_dir.join(name);+ if std::fs::rename(&target, &dest).is_err() {+ std::fs::copy(&target, &dest).map_err(|e| StorageError::Failed(e.to_string()))?;+ std::fs::remove_file(&target).map_err(|e| StorageError::Failed(e.to_string()))?;+ }+ return Ok(());+ }+ if !confirmed {+ return Err(StorageError::Denied);+ }+ if md.is_dir() {+ std::fs::remove_dir_all(&target).map_err(|e| StorageError::Failed(e.to_string()))+ } else {+ std::fs::remove_file(&target).map_err(|e| StorageError::Failed(e.to_string()))+ }+ }+}++fn is_media_extension(path: &Path) -> bool {+ path.extension().and_then(|e| e.to_str()).is_some_and(|ext| {+ matches!(+ ext.to_ascii_lowercase().as_str(),+ "jpg"+ | "jpeg"+ | "png"+ | "webp"+ | "gif"+ | "heic"+ | "mp4"+ | "mov"+ | "mkv"+ | "mp3"+ | "m4a"+ | "wav"+ | "flac"+ | "ogg"+ )+ })+}++fn system_time_ms(t: Option<SystemTime>) -> i64 {+ t.and_then(|st| st.duration_since(UNIX_EPOCH).ok())+ .and_then(|d| i64::try_from(d.as_millis()).ok())+ .unwrap_or(0)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn folder_storage_rejects_traversal_and_symlinks_outside_root() {+ let root_dir = tempfile::tempdir().unwrap();+ let outside_dir = tempfile::tempdir().unwrap();+ std::fs::write(outside_dir.path().join("secret.txt"), b"top secret").unwrap();+ std::fs::create_dir_all(root_dir.path().join("Documents")).unwrap();+ std::fs::write(root_dir.path().join("Documents/notes.txt"), b"hello world").unwrap();++ let storage = FolderStorage::new(root_dir.path());++ // Valid operations inside root succeed.+ let root_entries = storage.list("").unwrap();+ assert_eq!(root_entries.len(), 1);+ assert_eq!(root_entries[0].name, "Documents");+ assert!(root_entries[0].is_dir);++ // Path traversal and absolute paths are rejected.+ for bad in [+ "..",+ "../secret.txt",+ "Documents/../../secret.txt",+ "/etc/passwd",+ "/data/data",+ "Documents\\notes.txt",+ ] {+ assert!(storage.list(bad).is_err(), "{bad}");+ assert!(storage.open_read(bad).is_err(), "{bad}");+ assert!(storage.mkdir(bad).is_err(), "{bad}");+ assert!(storage.delete(bad, true).is_err(), "{bad}");+ }++ // Non-media file deletion requires confirmation (`confirmed = true`);+ // media files move to trash when a trash dir is configured.+ let trash_dir = tempfile::tempdir().unwrap();+ let storage = storage.with_trash_dir(trash_dir.path());+ assert_eq!(storage.delete("Documents/notes.txt", false), Err(StorageError::Denied));+ std::fs::write(root_dir.path().join("Documents/photo.jpg"), b"jpeg").unwrap();+ storage.delete("Documents/photo.jpg", false).unwrap();+ assert!(trash_dir.path().join("photo.jpg").exists());+ }+}diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rsindex d711586..da5e08a 100644--- a/core/nectarlink-core/src/transfer.rs+++ b/core/nectarlink-core/src/transfer.rs@@ -633,6 +633,20 @@ pub(crate) async fn accept_stream({crate::remote::receive_motion(shared, session.peer, send, recv).await;}+ Some(h)+ if h.svc == nectarlink_protocol::messages::storage::SERVICE+ && h.op == nectarlink_protocol::messages::storage::OP_READ+ && h.v == nectarlink_protocol::messages::storage::VERSION =>+ {+ crate::storage::serve_read(shared, session.peer, send, recv).await;+ }+ Some(h)+ if h.svc == nectarlink_protocol::messages::storage::SERVICE+ && h.op == nectarlink_protocol::messages::storage::OP_WRITE+ && h.v == nectarlink_protocol::messages::storage::VERSION =>+ {+ crate::storage::serve_write(shared, session.peer, send, recv).await;+ }_ => {let reply = Envelope::error(ErrorCode::Unsupported, "unknown stream");let _ = write_frame(&mut send, &reply.to_cbor()).await;diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rsindex 4e32b18..cc4b717 100644--- a/core/nectarlink-core/tests/two_devices.rs+++ b/core/nectarlink-core/tests/two_devices.rs@@ -43,6 +43,7 @@ struct RecordingPlatform {remote_inputs: Mutex<Vec<nectarlink_core::RemoteInput>>,phone_toggles: Mutex<Vec<(String, nectarlink_core::PhoneToggleValue)>>,deck_presses: Mutex<Vec<String>>,+ storage: Mutex<Option<nectarlink_core::FolderStorage>>,}impl Platform for RecordingPlatform {@@ -400,6 +401,47 @@ impl Platform for RecordingPlatform {self.deck_presses.lock().unwrap().push(tile.to_owned());Ok(())}+ fn storage_list(+ &self,+ path: &str,+ ) -> Result<Vec<nectarlink_core::StorageEntry>, nectarlink_core::StorageError> {+ let guard = self.storage.lock().unwrap();+ let storage = guard.as_ref().ok_or(nectarlink_core::StorageError::Unsupported)?;+ storage.list(path)+ }+ fn storage_open_read(+ &self,+ path: &str,+ ) -> Result<nectarlink_core::StorageReadFile, nectarlink_core::StorageError> {+ let guard = self.storage.lock().unwrap();+ let storage = guard.as_ref().ok_or(nectarlink_core::StorageError::Unsupported)?;+ storage.open_read(path)+ }+ fn storage_write(+ &self,+ path: &str,+ staged: &std::path::Path,+ modified: Option<i64>,+ ) -> Result<nectarlink_core::StorageWriteDone, nectarlink_core::StorageError> {+ let guard = self.storage.lock().unwrap();+ let storage = guard.as_ref().ok_or(nectarlink_core::StorageError::Unsupported)?;+ storage.write(path, staged, modified)+ }+ fn storage_mkdir(&self, path: &str) -> Result<(), nectarlink_core::StorageError> {+ let guard = self.storage.lock().unwrap();+ let storage = guard.as_ref().ok_or(nectarlink_core::StorageError::Unsupported)?;+ storage.mkdir(path)+ }+ fn storage_rename(&self, from: &str, to: &str) -> Result<(), nectarlink_core::StorageError> {+ let guard = self.storage.lock().unwrap();+ let storage = guard.as_ref().ok_or(nectarlink_core::StorageError::Unsupported)?;+ storage.rename(from, to)+ }+ fn storage_delete(&self, path: &str, confirmed: bool) -> Result<(), nectarlink_core::StorageError> {+ let guard = self.storage.lock().unwrap();+ let storage = guard.as_ref().ok_or(nectarlink_core::StorageError::Unsupported)?;+ storage.delete(path, confirmed)+ }}#[derive(Debug, Default)]@@ -2651,3 +2693,191 @@ async fn deck_layout_and_state_arrive_press_runs_action_and_respects_toggles_and.await;assert!(matches!(phone.node.deck_press(pc_id, "run_build".into()).await, Err(Error::NotFound)));}++#[tokio::test(flavor = "multi_thread")]+async fn phone_storage_lists_reads_ranges_writes_resumes_mutates_and_enforces_security() {+ use nectarlink_core::{FolderStorage, STORAGE_MOUNT, STORAGE_READ, STORAGE_WRITE};++ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[STORAGE_MOUNT]).await;+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[STORAGE_READ, STORAGE_WRITE]).await;++ let storage_root = tempfile::tempdir().unwrap();+ let trash_root = tempfile::tempdir().unwrap();+ let outside_root = tempfile::tempdir().unwrap();+ std::fs::write(outside_root.path().join("outside.txt"), b"do not expose").unwrap();++ std::fs::create_dir_all(storage_root.path().join("Documents")).unwrap();+ std::fs::create_dir_all(storage_root.path().join("DCIM")).unwrap();+ std::fs::write(storage_root.path().join("Documents/readme.txt"), b"0123456789abcdef").unwrap();+ std::fs::write(storage_root.path().join("DCIM/photo.jpg"), b"fake-jpeg-bytes").unwrap();++ // Create a directory link inside storage_root pointing to outside_root to verify symlink/junction rejection.+ #[cfg(windows)]+ {+ let link = storage_root.path().join("escape_link");+ let _ = std::process::Command::new("cmd")+ .args(["/C", "mklink", "/J"])+ .arg(&link)+ .arg(outside_root.path())+ .output();+ }+ #[cfg(unix)]+ {+ let _ = std::os::unix::fs::symlink(outside_root.path(), storage_root.path().join("escape_link"));+ }++ *phone.platform.storage.lock().unwrap() =+ Some(FolderStorage::new(storage_root.path()).with_trash_dir(trash_root.path()));++ pair_qr(&mut pc, &mut phone).await;+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());++ // `storage` toggle is OFF by default on the phone.+ let toggles = phone.node.device_toggles(pc_id).unwrap();+ assert!(toggles.contains(&("storage", false)));++ // Requests while `storage` is off are denied and emit `StorageRequested` once on the phone.+ assert!(matches!(pc.node.storage_list(phone_id, "").await, Err(Error::Denied)));+ wait_for(&mut phone, "storage requested prompt", |e| match e {+ NodeEvent::StorageRequested { device } if *device == pc_id => Some(()),+ _ => None,+ })+ .await;+ assert!(matches!(+ pc.node.storage_read(phone_id, "Documents/readme.txt", 0, None).await,+ Err(Error::Denied)+ ));+ assert!(matches!(pc.node.storage_mkdir(phone_id, "NewFolder").await, Err(Error::Denied)));++ // Enable `storage` on the phone for this PC.+ phone.node.set_device_toggle(pc_id, "storage", true).unwrap();++ // Root listing returns DCIM and Documents (sorted), and omits `escape_link` pointing outside root.+ let root_entries = with_timeout("list root", pc.node.storage_list(phone_id, "")).await.unwrap();+ let names: Vec<&str> = root_entries.iter().map(|e| e.name.as_str()).collect();+ assert_eq!(names, vec!["DCIM", "Documents"]);+ assert!(root_entries.iter().all(|e| e.is_dir));+ assert!(phone.node.storage_open_folders().contains(&String::new()));++ // Listing `Documents` returns `readme.txt` with its size.+ let doc_entries =+ with_timeout("list Documents", pc.node.storage_list(phone_id, "Documents")).await.unwrap();+ assert_eq!(doc_entries.len(), 1);+ assert_eq!(doc_entries[0].name, "readme.txt");+ assert_eq!(doc_entries[0].size, 16);+ assert!(!doc_entries[0].is_dir);++ // Full read and ranged read (`offset` + `length`).+ let (meta_full, bytes_full) =+ with_timeout("read full", pc.node.storage_read(phone_id, "Documents/readme.txt", 0, None))+ .await+ .unwrap();+ assert_eq!(meta_full.size, 16);+ assert_eq!(meta_full.length, 16);+ assert_eq!(bytes_full, b"0123456789abcdef");++ let (meta_range, bytes_range) =+ with_timeout("read range", pc.node.storage_read(phone_id, "Documents/readme.txt", 6, Some(5)))+ .await+ .unwrap();+ assert_eq!(meta_range.size, 16);+ assert_eq!(meta_range.length, 5);+ assert_eq!(bytes_range, b"6789a");++ let (meta_eof, bytes_eof) =+ with_timeout("read past eof", pc.node.storage_read(phone_id, "Documents/readme.txt", 100, Some(10)))+ .await+ .unwrap();+ assert_eq!(meta_eof.size, 16);+ assert_eq!(meta_eof.length, 0);+ assert!(bytes_eof.is_empty());++ // `mkdir` creates a directory and triggers `storage.changed` for watched parent `""`.+ with_timeout("mkdir Projects", pc.node.storage_mkdir(phone_id, "Projects")).await.unwrap();+ assert!(storage_root.path().join("Projects").is_dir());+ let changed_dir = wait_for(&mut pc, "storage changed on root", |e| match e {+ NodeEvent::StorageChanged { device, path } if *device == phone_id => Some(path.clone()),+ _ => None,+ })+ .await;+ assert_eq!(changed_dir, "");++ // `write` with interruption and resume using the same upload ID.+ let upload_src = tempfile::tempdir().unwrap();+ let payload = data(250 * 1024, 9);+ let local_file = upload_src.path().join("upload.bin");+ std::fs::write(&local_file, &payload).unwrap();++ // First attempt stops after 100 KiB.+ let interrupted = pc+ .node+ .storage_write_with_id(+ phone_id,+ "Documents/upload.bin",+ &local_file,+ Some("resume-upload-01".into()),+ Some(100 * 1024),+ )+ .await;+ assert!(interrupted.is_err());+ assert!(!storage_root.path().join("Documents/upload.bin").exists());++ // Wait briefly for the phone to flush the partial staging file, then resume with the same ID.+ tokio::time::sleep(Duration::from_millis(100)).await;+ let done = with_timeout(+ "resumed write",+ pc.node.storage_write_with_id(+ phone_id,+ "Documents/upload.bin",+ &local_file,+ Some("resume-upload-01".into()),+ None,+ ),+ )+ .await+ .unwrap();+ assert_eq!(done.size, payload.len() as u64);+ assert_eq!(std::fs::read(storage_root.path().join("Documents/upload.bin")).unwrap(), payload);++ // `rename` moves the uploaded file into `Projects/renamed.bin`.+ with_timeout(+ "rename file",+ pc.node.storage_rename(phone_id, "Documents/upload.bin", "Projects/renamed.bin"),+ )+ .await+ .unwrap();+ assert!(!storage_root.path().join("Documents/upload.bin").exists());+ assert_eq!(std::fs::read(storage_root.path().join("Projects/renamed.bin")).unwrap(), payload);++ // `delete`: media file moves to trash even with `confirmed = false`; non-media requires `confirmed = true`.+ with_timeout("trash photo", pc.node.storage_delete(phone_id, "DCIM/photo.jpg", false)).await.unwrap();+ assert!(!storage_root.path().join("DCIM/photo.jpg").exists());+ assert_eq!(std::fs::read(trash_root.path().join("photo.jpg")).unwrap(), b"fake-jpeg-bytes");++ assert!(matches!(+ pc.node.storage_delete(phone_id, "Projects/renamed.bin", false).await,+ Err(Error::Denied)+ ));+ with_timeout("confirmed delete", pc.node.storage_delete(phone_id, "Projects/renamed.bin", true))+ .await+ .unwrap();+ assert!(!storage_root.path().join("Projects/renamed.bin").exists());++ // Path traversal, absolute paths, `/data`, and symlinks/junctions outside root are refused.+ for bad in ["..", "../outside.txt", "Documents/../../outside.txt", "/etc/passwd", "/data/data"] {+ assert!(pc.node.storage_list(phone_id, bad).await.is_err(), "list {bad}");+ assert!(pc.node.storage_read(phone_id, bad, 0, None).await.is_err(), "read {bad}");+ assert!(pc.node.storage_mkdir(phone_id, bad).await.is_err(), "mkdir {bad}");+ assert!(pc.node.storage_delete(phone_id, bad, true).await.is_err(), "delete {bad}");+ }+ if storage_root.path().join("escape_link").exists() {+ assert!(matches!(+ pc.node.storage_list(phone_id, "escape_link").await,+ Err(Error::Denied | Error::NotFound)+ ));+ assert!(matches!(+ pc.node.storage_read(phone_id, "escape_link/outside.txt", 0, None).await,+ Err(Error::Denied | Error::NotFound)+ ));+ }+}diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rsindex 76d91b7..2727fd9 100644--- a/core/nectarlink-ffi/src/lib.rs+++ b/core/nectarlink-ffi/src/lib.rs@@ -496,6 +496,16 @@ pub enum Event {id: String,state: DeckState,},+ /// A paired PC asked to browse this phone's storage while `storage` is off+ /// (phones only).+ StorageRequested {+ id: String,+ },+ /// A folder on a paired phone changed (PCs only).+ StorageChanged {+ id: String,+ path: String,+ },}/// One tile on a PC's Deck (`docs/protocol/deck.md`).@@ -1008,7 +1018,34 @@ pub struct PhotoThumb {pub data: Vec<u8>,}-private_debug!(PhotoAlbum, PhotoItem, PhotoThumb);+/// One file or folder in a phone directory listing (`docs/protocol/storage.md`).+#[derive(Clone, PartialEq, Eq, uniffi::Record)]+pub struct StorageEntry {+ pub name: String,+ pub size: u64,+ /// Unix milliseconds.+ pub modified: i64,+ pub is_dir: bool,+}++/// An opened file on this phone ready for ranged reading (`storage.read`).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct StorageReadFile {+ pub source: FileToSend,+ pub size: u64,+ /// Unix milliseconds.+ pub modified: i64,+}++/// Result of writing a file into this phone's storage (`storage.write`).+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]+pub struct StorageWriteDone {+ pub size: u64,+ /// Unix milliseconds.+ pub modified: i64,+}++private_debug!(PhotoAlbum, PhotoItem, PhotoThumb, StorageEntry);#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]pub enum NectarlinkError {@@ -1417,6 +1454,10 @@ impl From<NodeEvent> for Event {NodeEvent::DeckState { device, state } => {Event::DeckState { id: device.to_string(), state: state.into() }}+ NodeEvent::StorageRequested { device } => Event::StorageRequested { id: device.to_string() },+ NodeEvent::StorageChanged { device, path } => {+ Event::StorageChanged { id: device.to_string(), path }+ }}}}@@ -1487,6 +1528,42 @@ impl From<MediaFailure> for core::MediaError {}}+/// Why a phone storage operation failed (`docs/protocol/storage.md`).+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, uniffi::Error)]+pub enum StorageFailure {+ #[error("no longer exists")]+ NotFound,+ #[error("access denied")]+ Denied,+ #[error("invalid path: {reason}")]+ Invalid { reason: String },+ #[error("not enough space")]+ NoSpace,+ #[error("not available")]+ Unsupported,+ #[error("failed: {reason}")]+ Failed { reason: String },+}++impl From<uniffi::UnexpectedUniFFICallbackError> for StorageFailure {+ fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {+ StorageFailure::Failed { reason: e.reason }+ }+}++impl From<StorageFailure> for core::StorageError {+ fn from(f: StorageFailure) -> Self {+ match f {+ StorageFailure::NotFound => core::StorageError::NotFound,+ StorageFailure::Denied => core::StorageError::Denied,+ StorageFailure::Invalid { reason } => core::StorageError::Invalid(reason),+ StorageFailure::NoSpace => core::StorageError::NoSpace,+ StorageFailure::Unsupported => core::StorageError::Unsupported,+ StorageFailure::Failed { reason } => core::StorageError::Failed(reason),+ }+ }+}+/// What the app does for the core: ring the phone, act on its/// notifications.#[uniffi::export(with_foreign)]@@ -1584,6 +1661,25 @@ pub trait Platform: Send + Sync {/// `"ringer"`, `"flashlight"`, `"volume"`, `"brightness"`, `"wifi"`,/// `"bluetooth"`). False if the phone couldn't.fn set_phone_toggle(&self, id: String, value: PhoneToggleValue) -> bool;+ /// A PC asked to list a folder in this phone's storage (`""` is root).+ fn storage_list(&self, path: String) -> Result<Vec<StorageEntry>, StorageFailure>;+ /// A PC asked to open a file in this phone's storage for ranged reading.+ fn storage_open_read(&self, path: String) -> Result<StorageReadFile, StorageFailure>;+ /// A PC finished uploading a file to `staged_path`: move/copy it into+ /// `path` in this phone's storage.+ fn storage_write(+ &self,+ path: String,+ staged_path: String,+ modified: Option<i64>,+ ) -> Result<StorageWriteDone, StorageFailure>;+ /// A PC asked to create a folder at `path` in this phone's storage.+ fn storage_mkdir(&self, path: String) -> Result<(), StorageFailure>;+ /// A PC asked to rename or move `from` to `to` in this phone's storage.+ fn storage_rename(&self, from: String, to: String) -> Result<(), StorageFailure>;+ /// A PC asked to delete `path` in this phone's storage (`confirmed`: the+ /// PC user confirmed permanent deletion if trash isn't available).+ fn storage_delete(&self, path: String, confirmed: bool) -> Result<(), StorageFailure>;}/// Encrypts the device key at rest (Android: a Keystore key).@@ -1831,6 +1927,42 @@ impl core::Platform for PlatformAdapter {};if self.0.set_phone_toggle(id.to_owned(), value) { Ok(()) } else { Err("the phone couldn't".into()) }}+ fn storage_list(&self, path: &str) -> Result<Vec<core::StorageEntry>, core::StorageError> {+ let items = self.0.storage_list(path.to_owned())?;+ Ok(items+ .into_iter()+ .map(|e| core::StorageEntry {+ name: e.name,+ size: e.size,+ modified: e.modified,+ is_dir: e.is_dir,+ })+ .collect())+ }+ fn storage_open_read(&self, path: &str) -> Result<core::StorageReadFile, core::StorageError> {+ let file = self.0.storage_open_read(path.to_owned())?;+ let outgoing = file_to_send(file.source).map_err(|e| core::StorageError::Failed(e.to_string()))?;+ Ok(core::StorageReadFile { source: outgoing.source, size: file.size, modified: file.modified })+ }+ fn storage_write(+ &self,+ path: &str,+ staged: &std::path::Path,+ modified: Option<i64>,+ ) -> Result<core::StorageWriteDone, core::StorageError> {+ let staged_str = staged.to_string_lossy().into_owned();+ let done = self.0.storage_write(path.to_owned(), staged_str, modified)?;+ Ok(core::StorageWriteDone { size: done.size, modified: done.modified })+ }+ fn storage_mkdir(&self, path: &str) -> Result<(), core::StorageError> {+ Ok(self.0.storage_mkdir(path.to_owned())?)+ }+ fn storage_rename(&self, from: &str, to: &str) -> Result<(), core::StorageError> {+ Ok(self.0.storage_rename(from.to_owned(), to.to_owned())?)+ }+ fn storage_delete(&self, path: &str, confirmed: bool) -> Result<(), core::StorageError> {+ Ok(self.0.storage_delete(path.to_owned(), confirmed)?)+ }}struct KeyProtectorAdapter(Arc<dyn KeyProtector>);@@ -2324,6 +2456,19 @@ impl NectarlinkNode {self.run(async move { node.photos_changed().await }).await;}+ /// A folder on this phone changed (`""` for root): PCs that have it open+ /// in File Explorer refresh it (`storage.changed`, debounced).+ pub async fn storage_changed(&self, path: String) {+ let node = self.node.clone();+ self.run(async move { node.storage_changed(path).await }).await;+ }++ /// Directory paths currently watched by any connected PC (most recently+ /// listed folders).+ pub fn storage_open_folders(&self) -> Vec<String> {+ self.node.storage_open_folders()+ }+/// A call on this phone rang, was answered or ended: tells the PCs that/// show calls (and are allowed them), now and when they connect during it.pub async fn call_changed(&self, call: Call) -> Result<()> {diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rsindex 570aa0a..90e8288 100644--- a/core/nectarlink-protocol/src/messages.rs+++ b/core/nectarlink-protocol/src/messages.rs@@ -76,6 +76,17 @@ pub mod types {pub const DECK_LAYOUT: &str = "deck.layout";pub const DECK_STATE: &str = "deck.state";pub const DECK_PRESS: &str = "deck.press";+ pub const STORAGE_LIST: &str = "storage.list";+ pub const STORAGE_ENTRIES: &str = "storage.entries";+ pub const STORAGE_READ: &str = "storage.read";+ pub const STORAGE_READ_META: &str = "storage.read.meta";+ pub const STORAGE_WRITE: &str = "storage.write";+ pub const STORAGE_WRITE_ACCEPT: &str = "storage.write.accept";+ pub const STORAGE_WRITE_DONE: &str = "storage.write.done";+ pub const STORAGE_MKDIR: &str = "storage.mkdir";+ pub const STORAGE_RENAME: &str = "storage.rename";+ pub const STORAGE_DELETE: &str = "storage.delete";+ pub const STORAGE_CHANGED: &str = "storage.changed";}/// What kind of device this is.@@ -2651,6 +2662,280 @@ impl DeckPress {}}+// ---- Storage (docs/protocol/storage.md) ----++pub mod storage {+ /// Offered by phones that list folders and read files in shared storage.+ pub const READ: &str = "storage.read";+ /// Offered by phones that create folders, write/upload files, rename and delete entries.+ pub const WRITE: &str = "storage.write";+ /// Offered by PCs that mount phone storage in File Explorer.+ pub const MOUNT: &str = "storage.mount";+ pub const SERVICE: &str = "storage";+ pub const OP_READ: &str = "read";+ pub const OP_WRITE: &str = "write";+ pub const VERSION: u32 = 1;+ /// Maximum UTF-8 bytes in a relative storage path.+ pub const MAX_PATH_BYTES: usize = 1024;+ /// Maximum `/`-separated path segments.+ pub const MAX_SEGMENTS: usize = 32;+ /// Maximum UTF-8 bytes in a single entry name.+ pub const MAX_NAME_BYTES: usize = 255;+ /// Maximum bytes in a write upload ID.+ pub const MAX_ID_BYTES: usize = 64;+}++/// Whether `name` is a valid single storage entry name (`1..=255` UTF-8 bytes,+/// not `"."` or `".."`, no `/`, `\`, NUL, or control characters).+pub fn is_valid_storage_name(name: &str) -> bool {+ (1..=storage::MAX_NAME_BYTES).contains(&name.len())+ && name != "."+ && name != ".."+ && !name.chars().any(|c| c == '/' || c == '\\' || c.is_control())+}++/// Whether `path` is a valid non-empty relative storage path (`"DCIM/Camera"`,+/// `"report.pdf"`): `1..=32` `/`-separated segments, at most 1 024 bytes, no+/// leading or trailing `/`, no `.` or `..` segments, no `\` or control chars.+pub fn is_valid_storage_path(path: &str) -> bool {+ if path.is_empty() || path.len() > storage::MAX_PATH_BYTES || path.starts_with('/') || path.ends_with('/')+ {+ return false;+ }+ let mut count = 0usize;+ for seg in path.split('/') {+ count += 1;+ if count > storage::MAX_SEGMENTS || !is_valid_storage_name(seg) {+ return false;+ }+ }+ count >= 1+}++/// Whether `path` is a valid storage directory path (`""` for the shared root,+/// or a valid relative path).+pub fn is_valid_storage_dir_path(path: &str) -> bool {+ path.is_empty() || is_valid_storage_path(path)+}++/// Whether `id` is a valid upload ID (`1..=64` printable ASCII characters+/// without `/` or `\`).+pub fn is_valid_storage_id(id: &str) -> bool {+ (1..=storage::MAX_ID_BYTES).contains(&id.len())+ && id.bytes().all(|b| (0x21..=0x7e).contains(&b) && b != b'/' && b != b'\\')+}++/// Body of `storage.list` (`docs/protocol/storage.md` §3.1).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageList {+ pub path: String,+}++impl std::fmt::Debug for StorageList {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageList").finish_non_exhaustive()+ }+}++impl StorageList {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_dir_path(&self.path)+ }+}++/// One directory entry in `storage.entries` (`docs/protocol/storage.md` §3).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageEntry {+ pub name: String,+ pub size: u64,+ /// Last-modified time in Unix milliseconds.+ pub modified: i64,+ pub is_dir: bool,+}++/// Never prints entry names in logs (protocol v0 §11).+impl std::fmt::Debug for StorageEntry {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageEntry")+ .field("size", &self.size)+ .field("modified", &self.modified)+ .field("is_dir", &self.is_dir)+ .finish_non_exhaustive()+ }+}++impl StorageEntry {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_name(&self.name) && self.modified >= 0+ }++ pub fn sanitized(mut self) -> Option<Self> {+ if !is_valid_storage_name(&self.name) {+ return None;+ }+ self.modified = self.modified.max(0);+ if self.is_dir {+ self.size = 0;+ }+ Some(self)+ }+}++/// Body of `storage.entries`: immediate children of a listed folder.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageEntries {+ #[serde(default)]+ pub entries: Vec<StorageEntry>,+}++/// Body of `storage.read` on a `storage/read` stream (`docs/protocol/storage.md` §4.1).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageRead {+ pub path: String,+ #[serde(default)]+ pub offset: u64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub length: Option<u64>,+}++impl std::fmt::Debug for StorageRead {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageRead")+ .field("offset", &self.offset)+ .field("length", &self.length)+ .finish_non_exhaustive()+ }+}++impl StorageRead {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_path(&self.path)+ }+}++/// Body of `storage.read.meta`: precedes the raw file bytes on a `storage/read` stream.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageReadMeta {+ pub size: u64,+ pub modified: i64,+ pub length: u64,+}++/// Body of `storage.write` on a `storage/write` stream (`docs/protocol/storage.md` §4.2).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageWriteOffer {+ pub id: String,+ pub path: String,+ pub size: u64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub modified: Option<i64>,+}++impl std::fmt::Debug for StorageWriteOffer {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageWriteOffer")+ .field("id", &self.id)+ .field("size", &self.size)+ .finish_non_exhaustive()+ }+}++impl StorageWriteOffer {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_id(&self.id)+ && is_valid_storage_path(&self.path)+ && self.modified.is_none_or(|m| m >= 0)+ }+}++/// Body of `storage.write.accept`: how many bytes the phone already has for this upload.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageWriteAccept {+ pub have: u64,+}++/// Body of `storage.write.done`: sent by the phone after committing the uploaded file.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageWriteDone {+ pub size: u64,+ pub modified: i64,+}++/// Body of `storage.mkdir` (`docs/protocol/storage.md` §3.2).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageMkdir {+ pub path: String,+}++impl std::fmt::Debug for StorageMkdir {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageMkdir").finish_non_exhaustive()+ }+}++impl StorageMkdir {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_path(&self.path)+ }+}++/// Body of `storage.rename` (`docs/protocol/storage.md` §3.3).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageRename {+ pub from: String,+ pub to: String,+}++impl std::fmt::Debug for StorageRename {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageRename").finish_non_exhaustive()+ }+}++impl StorageRename {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_path(&self.from) && is_valid_storage_path(&self.to) && self.from != self.to+ }+}++/// Body of `storage.delete` (`docs/protocol/storage.md` §3.4).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageDelete {+ pub path: String,+ #[serde(default)]+ pub confirmed: bool,+}++impl std::fmt::Debug for StorageDelete {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageDelete").field("confirmed", &self.confirmed).finish_non_exhaustive()+ }+}++impl StorageDelete {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_path(&self.path)+ }+}++/// Body of `storage.changed` (`docs/protocol/storage.md` §3.5).+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct StorageChanged {+ pub path: String,+}++impl std::fmt::Debug for StorageChanged {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("StorageChanged").finish_non_exhaustive()+ }+}++impl StorageChanged {+ pub fn is_valid(&self) -> bool {+ is_valid_storage_dir_path(&self.path)+ }+}+#[cfg(test)]mod tests {use super::*;@@ -3289,4 +3574,76 @@ mod tests {assert!(!DeckPress { tile: String::new() }.is_valid());assert!(!DeckPress { tile: "bad tile!".into() }.is_valid());}++ #[test]+ fn storage_paths_and_messages_validate_and_round_trip() {+ assert!(is_valid_storage_dir_path(""));+ assert!(!is_valid_storage_path(""));+ for good in ["DCIM", "DCIM/Camera/IMG_001.jpg", "Download/Report (2026) ✓.pdf", ".hidden/file.txt"]+ {+ assert!(is_valid_storage_path(good), "{good}");+ assert!(is_valid_storage_dir_path(good), "{good}");+ }+ for bad in [+ "/",+ "/DCIM",+ "DCIM/",+ "DCIM//Camera",+ ".",+ "..",+ "../etc/passwd",+ "DCIM/../secret",+ "DCIM/.",+ "DCIM\\Camera",+ "C:\\Windows",+ "bad\0name",+ "bad\nname",+ ] {+ assert!(!is_valid_storage_path(bad), "{bad}");+ assert!(!is_valid_storage_dir_path(bad), "{bad}");+ }+ let deep = vec!["a"; storage::MAX_SEGMENTS + 1].join("/");+ assert!(!is_valid_storage_path(&deep));+ let long_seg = "x".repeat(storage::MAX_NAME_BYTES + 1);+ assert!(!is_valid_storage_path(&long_seg));++ let entry = StorageEntry {+ name: "photo.jpg".into(),+ size: 123_456,+ modified: 1_750_000_000_000,+ is_dir: false,+ };+ assert!(entry.is_valid());+ assert!(!format!("{entry:?}").contains("photo.jpg"));+ let dir_entry =+ StorageEntry { name: "DCIM".into(), size: 999, modified: -5, is_dir: true }.sanitized().unwrap();+ assert_eq!(dir_entry.size, 0);+ assert_eq!(dir_entry.modified, 0);++ let entries = StorageEntries { entries: vec![entry, dir_entry] };+ let env = Envelope::new(types::STORAGE_ENTRIES, &entries).unwrap();+ let back: StorageEntries = Envelope::from_cbor(&env.to_cbor()).unwrap().body().unwrap();+ assert_eq!(back, entries);++ let read = StorageRead { path: "DCIM/photo.jpg".into(), offset: 4096, length: Some(65536) };+ assert!(read.is_valid());+ assert!(!format!("{read:?}").contains("photo.jpg"));+ let env = Envelope::new(types::STORAGE_READ, &read).unwrap();+ assert_eq!(Envelope::from_cbor(&env.to_cbor()).unwrap().body::<StorageRead>().unwrap(), read);++ let write = StorageWriteOffer {+ id: "up-1".into(),+ path: "Download/notes.txt".into(),+ size: 512,+ modified: Some(1_750_000_000_000),+ };+ assert!(write.is_valid());+ assert!(!format!("{write:?}").contains("notes.txt"));+ let env = Envelope::new(types::STORAGE_WRITE, &write).unwrap();+ assert_eq!(Envelope::from_cbor(&env.to_cbor()).unwrap().body::<StorageWriteOffer>().unwrap(), write);++ let rename = StorageRename { from: "a.txt".into(), to: "b.txt".into() };+ assert!(rename.is_valid());+ assert!(!StorageRename { from: "a.txt".into(), to: "a.txt".into() }.is_valid());+ }}diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.tomlindex 6dd1fb2..f70e8a4 100644--- a/desktop/app/Cargo.toml+++ b/desktop/app/Cargo.toml@@ -38,6 +38,10 @@ windows = { workspace = true, features = ["Foundation_Collections","Media","Media_Control",+ "Security_Cryptography",+ "Storage",+ "Storage_Provider",+ "Storage_Search","Storage_Streams","ApplicationModel","UI_Notifications",@@ -45,6 +49,10 @@ windows = { workspace = true, features = ["Win32_Graphics_Dwm","Win32_Graphics_Gdi","Win32_Graphics_Imaging",+ "Win32_Storage_CloudFilters",+ "Win32_Storage_FileSystem",+ "Win32_System_CorrelationVector",+ "Win32_System_IO","Win32_System_LibraryLoader","Win32_Security","Win32_System_Com",diff --git a/desktop/app/qml/pages/SettingsPage.qml b/desktop/app/qml/pages/SettingsPage.qmlindex 7d85ae9..fb094a9 100644--- a/desktop/app/qml/pages/SettingsPage.qml+++ b/desktop/app/qml/pages/SettingsPage.qml@@ -30,12 +30,15 @@ Item {photos: qsTr("Photos"),toggles: qsTr("Phone controls"),pc_actions: qsTr("Lock, sleep and wake this PC"),+ mirroring: qsTr("Screen mirroring"),+ storage: qsTr("Phone storage in File Explorer"),remote_input: qsTr("Control this PC's mouse, keyboard and Deck"),commands: qsTr("Allow running Deck commands"),remote_files: qsTr("Browse this PC's files while away")})readonly property var toggleDescriptions: ({+ storage: qsTr("Show this phone's storage in File Explorer so you can browse, open and drop in files."),commands: qsTr("Lets this phone trigger Deck tiles that run shell commands configured on this PC. Off by default — only enable for a phone you control.")})@@ -460,10 +463,23 @@ Item {width: parent.widthtitle: page.toggleNames[modelData.name] || modelData.namedescription: page.toggleDescriptions[modelData.name] || ""- Toggle {- label: page.toggleNames[modelData.name] || modelData.name- checked: modelData.on- onToggled: (on) => AppController.setDeviceToggle(deviceCard.deviceId, modelData.name, on)+ Row {+ spacing: 10+ Button {+ visible: modelData.name === "storage" && modelData.on+ anchors.verticalCenter: parent.verticalCenter+ variant: "tonal"+ size: "sm"+ iconPath: Icons.folder+ text: qsTr("Open in File Explorer")+ onClicked: AppController.openPhoneStorage(deviceCard.deviceId)+ }+ Toggle {+ anchors.verticalCenter: parent.verticalCenter+ label: page.toggleNames[modelData.name] || modelData.name+ checked: modelData.on+ onToggled: (on) => AppController.setDeviceToggle(deviceCard.deviceId, modelData.name, on)+ }}}}diff --git a/desktop/app/src/bridge/app.rs b/desktop/app/src/bridge/app.rsindex 1ffc587..499aebd 100644--- a/desktop/app/src/bridge/app.rs+++ b/desktop/app/src/bridge/app.rs@@ -158,6 +158,13 @@ pub mod qobject {#[qinvokable]fn logs_url(self: &AppController) -> QString;+ /// Opens a paired phone's storage sync root in File Explorer.+ #[qinvokable]+ fn open_phone_storage(self: &AppController, device: &QString);+ /// The local sync root folder path for a paired phone.+ #[qinvokable]+ fn phone_storage_path(self: &AppController, device: &QString) -> QString;+/// A short message for the user (e.g. a command failed).#[qsignal]fn toast(self: Pin<&mut AppController>, message: QString);@@ -602,6 +609,9 @@ impl qobject::AppController {}});}+ if name_str == "storage" {+ crate::storage::sync();+ }let revision = self.toggles_revision.wrapping_add(1);self.as_mut().set_toggles_revision(revision);}@@ -685,6 +695,20 @@ impl qobject::AppController {let dir = crate::logging::logs_dir(&core_host::host().data_dir);QString::from(&format!("file:///{}", dir.to_string_lossy().replace('\\', "/")))}++ pub fn open_phone_storage(&self, device: &QString) {+ let Some(id) = super::parse_device(device) else { return };+ if let Err(e) = crate::storage::open_in_explorer(id) {+ show_message(e);+ }+ }++ pub fn phone_storage_path(&self, device: &QString) -> QString {+ let Some(id) = super::parse_device(device) else { return QString::default() };+ let path =+ crate::storage::sync_root_path_for(id).map(|p| p.display().to_string()).unwrap_or_default();+ QString::from(&path)+ }}impl Drop for AppControllerRust {diff --git a/desktop/app/src/bridge/deck.rs b/desktop/app/src/bridge/deck.rsindex 7528cc3..28ce522 100644--- a/desktop/app/src/bridge/deck.rs+++ b/desktop/app/src/bridge/deck.rs@@ -47,7 +47,7 @@ struct UiPage {fn action_fields(action: &DeckAction) -> (String, bool, bool, bool, bool, String) {match action {- DeckAction::MediaPlayPause => (String::new(), false, false, false, false, "Play / Pause".into()),+ DeckAction::MediaPlayPause => (String::new(), false, false, false, false, "Media key".into()),DeckAction::MediaNext => (String::new(), false, false, false, false, "Next track".into()),DeckAction::MediaPrevious => (String::new(), false, false, false, false, "Previous track".into()),DeckAction::VolumeUp => (String::new(), false, false, false, false, "Volume +2%".into()),@@ -118,7 +118,12 @@ impl qobject::DeckController {.iter().map(|t| {let kind = t.action.kind().to_owned();- let (param, ctrl, alt, shift, win, subtitle) = action_fields(&t.action);+ let (param, ctrl, alt, shift, win, raw_subtitle) = action_fields(&t.action);+ let subtitle = if raw_subtitle.eq_ignore_ascii_case(t.label.trim()) {+ String::new()+ } else {+ raw_subtitle+ };let status = st.tile_status(&kind).unwrap_or_default();UiTile {id: t.id.clone(),diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rsindex 51f4483..4d3077e 100644--- a/desktop/app/src/core_host.rs+++ b/desktop/app/src/core_host.rs@@ -110,6 +110,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {nectarlink_core::DECK_ACTIONS.into(),nectarlink_core::RECORDER.into(),nectarlink_core::TOGGLES_SHOW.into(),+ nectarlink_core::STORAGE_MOUNT.into(),];let node = match Node::start(config, platform).await {Ok(node) => node,@@ -171,6 +172,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {crate::transfers::on_event(&event);crate::send_to::on_event(&event);crate::battery::on_event(&event);+ crate::storage::on_event(&event);}Err(RecvError::Lagged(missed)) => {// Resynchronize what can be re-read; transient events are lost.diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rsindex 8c76c03..45ffd69 100644--- a/desktop/app/src/main.rs+++ b/desktop/app/src/main.rs@@ -34,6 +34,7 @@ mod send_to;mod settings;mod startup;mod state;+mod storage;mod transfers;mod updater;mod win;@@ -191,6 +192,7 @@ fn uninstall() {if let Err(e) = send_to::remove_all() {tracing::warn!(error = %e, "can't remove the Send to entries");}+ storage::unregister_all();win::toast::unregister();startup::remove();}@@ -263,6 +265,7 @@ fn main() -> ExitCode {recordings::init(&settings);send_to::set_enabled(settings.send_to_menu);battery::set_enabled(settings.battery_alerts);+ storage::start();// A test instance (own data folder) leaves the user's menu and sign-in// alone.if options.data_dir.is_none() {@@ -318,6 +321,7 @@ fn main() -> ExitCode {tracing::info!(code, "shutting down");// QML first (it holds references into Qt), then the core.drop(engine);+ storage::shutdown();win::net::stop();core_host::shutdown();drop(app);diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rsindex 182e1fb..94f467d 100644--- a/desktop/app/src/state.rs+++ b/desktop/app/src/state.rs@@ -439,7 +439,9 @@ impl AppState {| NodeEvent::Mirroring { .. }| NodeEvent::WakeInfoChanged { .. }| NodeEvent::DeckLayout { .. }- | NodeEvent::DeckState { .. } => Changes::NONE,+ | NodeEvent::DeckState { .. }+ | NodeEvent::StorageRequested { .. }+ | NodeEvent::StorageChanged { .. } => Changes::NONE,// The gallery's own downloads (for its viewer, or the clipboard)// aren't files the user keeps.NodeEvent::Transfer(transfer) if crate::photos::is_private(&transfer.id) => {diff --git a/desktop/app/src/storage.rs b/desktop/app/src/storage.rsnew file mode 100644index 0000000..22ae3a7--- /dev/null+++ b/desktop/app/src/storage.rs@@ -0,0 +1,1231 @@+// SPDX-License-Identifier: GPL-3.0-or-later+//! Phone storage in File Explorer (`docs/protocol/storage.md`, `PLAN.md` §3.6).+//!+//! Registers a Windows Cloud Files (`cfapi`) sync root per paired phone under+//! `%USERPROFILE%\Nectarlink\<Phone name>` when the phone's `storage` toggle is+//! enabled. Placeholders are populated on demand when folders are opened+//! (`CF_CALLBACK_TYPE_FETCH_PLACEHOLDERS`) and hydrated on open via ranged+//! reads (`CF_CALLBACK_TYPE_FETCH_DATA`). Renames, deletes, and new or modified+//! files dropped into the sync root are forwarded to the phone.++#![allow(unsafe_code)]++use std::{+ collections::{HashMap, HashSet},+ ffi::{OsStr, c_void},+ os::windows::ffi::{OsStrExt, OsStringExt},+ path::{Path, PathBuf},+ sync::{+ Arc, Mutex, MutexGuard,+ atomic::{AtomicBool, Ordering},+ },+ time::Duration,+};++use nectarlink_core::{DeviceId, LinkState, NodeEvent, StorageEntry};+use windows::{+ Security::Cryptography::{BinaryStringEncoding, CryptographicBuffer},+ Storage::{+ Provider::{+ StorageProviderHardlinkPolicy, StorageProviderHydrationPolicy,+ StorageProviderHydrationPolicyModifier, StorageProviderInSyncPolicy,+ StorageProviderPopulationPolicy, StorageProviderSyncRootInfo, StorageProviderSyncRootManager,+ },+ StorageFolder,+ },+ Win32::{+ Foundation::{+ CloseHandle, GENERIC_READ, GENERIC_WRITE, HANDLE, INVALID_HANDLE_VALUE, NTSTATUS,+ STATUS_ACCESS_DENIED, STATUS_CLOUD_FILE_NETWORK_UNAVAILABLE, STATUS_CLOUD_FILE_UNSUCCESSFUL,+ STATUS_SUCCESS,+ },+ Storage::{+ CloudFilters::{+ CF_CALLBACK_INFO, CF_CALLBACK_PARAMETERS, CF_CALLBACK_REGISTRATION,+ CF_CALLBACK_TYPE_FETCH_DATA, CF_CALLBACK_TYPE_FETCH_PLACEHOLDERS, CF_CALLBACK_TYPE_NONE,+ CF_CALLBACK_TYPE_NOTIFY_DELETE, CF_CALLBACK_TYPE_NOTIFY_RENAME,+ CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH, CF_CONNECT_FLAG_REQUIRE_PROCESS_INFO,+ CF_CONNECTION_KEY, CF_CONVERT_FLAG_MARK_IN_SYNC, CF_FS_METADATA, CF_IN_SYNC_STATE_IN_SYNC,+ CF_OPERATION_INFO, CF_OPERATION_PARAMETERS, CF_OPERATION_PARAMETERS_0,+ CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAG_DISABLE_ON_DEMAND_POPULATION, CF_OPERATION_TYPE,+ CF_OPERATION_TYPE_ACK_DELETE, CF_OPERATION_TYPE_ACK_RENAME, CF_OPERATION_TYPE_TRANSFER_DATA,+ CF_OPERATION_TYPE_TRANSFER_PLACEHOLDERS, CF_PLACEHOLDER_CREATE_FLAG_MARK_IN_SYNC,+ CF_PLACEHOLDER_CREATE_INFO, CF_PLACEHOLDER_STATE_IN_SYNC, CF_PLACEHOLDER_STATE_PLACEHOLDER,+ CF_SET_IN_SYNC_FLAG_NONE, CfConnectSyncRoot, CfConvertToPlaceholder, CfCreatePlaceholders,+ CfDisconnectSyncRoot, CfExecute, CfGetPlaceholderStateFromAttributeTag,+ CfReportProviderProgress, CfSetInSyncState,+ },+ FileSystem::{+ CreateFileW, FILE_ACTION_ADDED, FILE_ACTION_MODIFIED, FILE_ACTION_RENAMED_NEW_NAME,+ FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_NORMAL, FILE_BASIC_INFO, FILE_FLAG_BACKUP_SEMANTICS,+ FILE_LIST_DIRECTORY, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_FILE_NAME,+ FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_INFORMATION,+ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FindClose, FindFirstFileW,+ OPEN_EXISTING, ReadDirectoryChangesW, WIN32_FIND_DATAW,+ },+ },+ },+ core::{HSTRING, PCWSTR},+};++use crate::{+ core_host,+ state::{Changes, CoreStatus},+ win,+};++/// Provider prefix for sync root IDs (`Nectarlink!<device_id>`).+const PROVIDER_PREFIX: &str = "Nectarlink!";++/// Difference between Windows FILETIME epoch (1601-01-01) and Unix epoch+/// (1970-01-01) in 100-nanosecond intervals.+const EPOCH_DIFF_100NS: i64 = 116_444_736_000_000_000;++/// Cloud file network unavailable NTSTATUS (`STATUS_CLOUD_FILE_NETWORK_UNAVAILABLE`).+const STATUS_CLOUD_NETWORK_UNAVAILABLE: NTSTATUS = STATUS_CLOUD_FILE_NETWORK_UNAVAILABLE;++/// Cloud file unsuccessful / cancelled operation NTSTATUS (`STATUS_CLOUD_FILE_UNSUCCESSFUL`).+const STATUS_CLOUD_UNSUCCESSFUL: NTSTATUS = STATUS_CLOUD_FILE_UNSUCCESSFUL;++/// Chunk size for hydrating files via `CF_OPERATION_TYPE_TRANSFER_DATA` (must be+/// a multiple of 4096 bytes for non-EOF chunks).+const HYDRATE_CHUNK_BYTES: usize = 256 * 1024;++fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {+ m.lock().unwrap_or_else(|e| e.into_inner())+}++struct ActiveRoot {+ device: DeviceId,+ name: String,+ root_path: PathBuf,+ connection_key: CF_CONNECTION_KEY,+ stop_watcher: Arc<AtomicBool>,+ populated_dirs: Mutex<HashSet<String>>,+ uploading: Mutex<HashSet<String>>,+}++static ACTIVE_ROOTS: Mutex<Option<HashMap<DeviceId, Arc<ActiveRoot>>>> = Mutex::new(None);+static RECONCILING: Mutex<()> = Mutex::new(());++fn active_roots() -> MutexGuard<'static, Option<HashMap<DeviceId, Arc<ActiveRoot>>>> {+ lock(&ACTIVE_ROOTS)+}++fn get_active_root(device: &DeviceId) -> Option<Arc<ActiveRoot>> {+ active_roots().as_ref().and_then(|m| m.get(device).cloned())+}++/// Starts watching paired devices and their `storage` toggles to register or+/// unregister File Explorer sync roots.+pub fn start() {+ {+ let mut map = active_roots();+ if map.is_none() {+ *map = Some(HashMap::new());+ }+ }+ core_host::host().hub.subscribe(+ Changes::DEVICES | Changes::STATUS | Changes::CAPABILITIES | Changes::TOGGLES,+ || {+ sync();+ true+ },+ );+ sync();+}++/// Triggers a reconciliation of active sync roots (e.g. after a device toggle changes).+pub fn sync() {+ let host = core_host::host();+ let Some(node) = core_host::node() else { return };+ let ready = host.hub.read(|s| matches!(s.status, Some(CoreStatus::Ready { .. })));+ if !ready {+ return;+ }+ let devices = host.hub.read(|s| {+ s.devices+ .iter()+ .map(|d| (d.id, d.info.name.clone(), matches!(d.link, LinkState::Online { .. })))+ .collect::<Vec<_>>()+ });+ let mut desired: Vec<(DeviceId, String, bool)> = Vec::new();+ let mut disabled: Vec<(DeviceId, String)> = Vec::new();+ for (id, name, online) in devices {+ let enabled = node+ .device_toggles(id)+ .ok()+ .and_then(|t| t.into_iter().find(|(k, _)| *k == "storage").map(|(_, on)| on))+ .unwrap_or(false);+ if enabled {+ desired.push((id, name, online));+ } else {+ disabled.push((id, name));+ }+ }++ let _ = std::thread::Builder::new().name("storage-sync".into()).spawn(move || {+ let _guard = lock(&RECONCILING);+ win::with_com(|| reconcile(&desired, &disabled));+ });+}++/// Handles core events (`StorageChanged`, `DeviceRemoved`, `LinkChanged`).+pub fn on_event(event: &NodeEvent) {+ match event {+ NodeEvent::DeviceRemoved(device) => {+ let device = *device;+ let _ = std::thread::Builder::new().name("storage-unpair".into()).spawn(move || {+ let _guard = lock(&RECONCILING);+ win::with_com(|| remove_device_root(device, None));+ });+ }+ NodeEvent::DeviceAdded(_)+ | NodeEvent::PeerInfoChanged { .. }+ | NodeEvent::Capabilities(_)+ | NodeEvent::LinkChanged { .. } => {+ sync();+ }+ NodeEvent::StorageChanged { device, path } => {+ let device = *device;+ let path = path.clone();+ if let Some(root) = get_active_root(&device) {+ core_host::spawn(async move {+ refresh_folder(root, &path).await;+ });+ }+ }+ _ => {}+ }+}++/// Disconnects active sync roots when the desktop app exits.+pub fn shutdown() {+ let roots: Vec<Arc<ActiveRoot>> =+ active_roots().as_mut().map(|m| m.drain().map(|(_, v)| v).collect()).unwrap_or_default();+ for root in roots {+ root.stop_watcher.store(true, Ordering::Relaxed);+ // SAFETY: connection_key was obtained from CfConnectSyncRoot.+ let _ = unsafe { CfDisconnectSyncRoot(root.connection_key) };+ }+}++/// Unregisters all `Nectarlink!*` sync roots from Windows (`--uninstall`).+pub fn unregister_all() {+ shutdown();+ win::with_com(|| {+ if let Ok(roots) = StorageProviderSyncRootManager::GetCurrentSyncRoots() {+ let count = roots.Size().unwrap_or(0);+ for i in 0..count {+ if let Ok(info) = roots.GetAt(i)+ && let Ok(id) = info.Id()+ {+ let id_str = id.to_string_lossy();+ if id_str.starts_with(PROVIDER_PREFIX) {+ let folder_path = info+ .Path()+ .ok()+ .and_then(|f| f.Path().ok())+ .map(|p| PathBuf::from(p.to_string_lossy()));+ let _ = StorageProviderSyncRootManager::Unregister(&id);+ if let Some(path) = folder_path {+ cleanup_sync_root_dir(&path);+ }+ }+ }+ }+ }+ if let Some(base) = base_sync_dir() {+ let _ = std::fs::remove_dir(&base);+ }+ });+}++/// Returns the local sync root path for a paired phone (`%USERPROFILE%\Nectarlink\<Phone name>`).+pub fn sync_root_path_for(device: DeviceId) -> Option<PathBuf> {+ if let Some(active) = get_active_root(&device) {+ return Some(active.root_path.clone());+ }+ let name = core_host::host().hub.read(|s| s.name_of(&device))?;+ Some(base_sync_dir()?.join(sanitize_folder_name(&name)))+}++/// Opens a paired phone's sync root folder in File Explorer.+pub fn open_in_explorer(device: DeviceId) -> Result<(), String> {+ let path =+ sync_root_path_for(device).ok_or_else(|| "Phone storage folder is not available".to_owned())?;+ if !path.exists() {+ std::fs::create_dir_all(&path).map_err(|e| e.to_string())?;+ }+ win::shell::run(Path::new("explorer.exe"), &format!("\"{}\"", path.display()))+}++fn base_sync_dir() -> Option<PathBuf> {+ dirs::home_dir().map(|h| h.join("Nectarlink"))+}++fn sync_root_id(device: DeviceId) -> HSTRING {+ HSTRING::from(format!("{PROVIDER_PREFIX}{device}"))+}++/// Sanitizes a phone's display name into a valid Windows directory name.+pub fn sanitize_folder_name(device_name: &str) -> String {+ let cleaned: String = device_name+ .chars()+ .map(|c| if c.is_control() || r#"<>:"/\|?*"#.contains(c) { ' ' } else { c })+ .collect();+ let mut name = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");+ name = name.trim_end_matches(['.', ' ']).chars().take(64).collect();+ let stem = name.split('.').next().unwrap_or_default().to_ascii_uppercase();+ let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")+ || ((stem.starts_with("COM") || stem.starts_with("LPT"))+ && stem.len() == 4+ && stem.as_bytes()[3].is_ascii_digit());+ if name.is_empty() {+ "Phone".into()+ } else if reserved {+ format!("{name} phone")+ } else {+ name+ }+}++/// Converts a Unix timestamp in milliseconds to Windows FILETIME 100ns ticks+/// since 1601-01-01.+pub fn unix_ms_to_filetime_ticks(unix_ms: i64) -> i64 {+ EPOCH_DIFF_100NS.saturating_add(unix_ms.max(0).saturating_mul(10_000))+}++/// Converts Windows FILETIME 100ns ticks since 1601-01-01 to Unix milliseconds.+#[cfg(test)]+pub fn filetime_ticks_to_unix_ms(ticks: i64) -> i64 {+ ticks.saturating_sub(EPOCH_DIFF_100NS).max(0) / 10_000+}++/// Computes the slash-separated relative path inside `root_path` from a full+/// local path (`""` for the sync root itself). Returns `None` if `full_path` is+/// not inside `root_path`.+pub fn relative_path_under_root(root_path: &Path, full_path: &Path) -> Option<String> {+ let root_norm = normalize_win_path(root_path);+ let full_norm = normalize_win_path(full_path);+ let root_lower = root_norm.to_lowercase();+ let full_lower = full_norm.to_lowercase();+ if full_lower == root_lower {+ return Some(String::new());+ }+ let prefix = format!("{root_lower}\\");+ if !full_lower.starts_with(&prefix) {+ return None;+ }+ let rel = &full_norm[prefix.len()..];+ let parts: Vec<&str> = rel.split('\\').filter(|s| !s.is_empty()).collect();+ if parts.iter().any(|p| *p == "." || *p == "..") {+ return None;+ }+ Some(parts.join("/"))+}++fn normalize_win_path(path: &Path) -> String {+ let s = path.to_string_lossy();+ let stripped = s.strip_prefix(r"\\?\").unwrap_or(&s);+ stripped.trim_end_matches('\\').to_owned()+}++fn reconcile(desired: &[(DeviceId, String, bool)], disabled: &[(DeviceId, String)]) {+ // Unregister any disabled devices that belong to this instance.+ for (id, name) in disabled {+ remove_device_root(*id, Some(name));+ }++ // Remove any active roots no longer in `desired`.+ let active_ids: Vec<DeviceId> =+ active_roots().as_ref().map(|m| m.keys().copied().collect()).unwrap_or_default();+ for id in active_ids {+ if !desired.iter().any(|(d, _, _)| *d == id) {+ remove_device_root(id, None);+ }+ }++ // Register and connect desired roots.+ for (id, name, online) in desired {+ let already = get_active_root(id);+ if let Some(existing) = already {+ if existing.name == *name {+ if *online {+ let root = existing.clone();+ core_host::spawn(async move {+ let is_root_populated = lock(&root.populated_dirs).contains("");+ if is_root_populated {+ refresh_folder(root, "").await;+ }+ });+ }+ continue;+ }+ // Name changed: replace root.+ remove_device_root(*id, Some(&existing.name));+ }++ if let Err(e) = register_and_connect(*id, name, *online) {+ tracing::warn!(device = %id.short(), error = %e, "can't register phone storage sync root");+ }+ }+}++fn remove_device_root(device: DeviceId, known_name: Option<&str>) {+ let removed = active_roots().as_mut().and_then(|m| m.remove(&device));+ let mut folder_to_clean: Option<PathBuf> = None;+ if let Some(root) = removed {+ root.stop_watcher.store(true, Ordering::Relaxed);+ // SAFETY: connection_key was obtained from CfConnectSyncRoot.+ let _ = unsafe { CfDisconnectSyncRoot(root.connection_key) };+ folder_to_clean = Some(root.root_path.clone());+ } else if let Some(name) = known_name+ && let Some(base) = base_sync_dir()+ {+ folder_to_clean = Some(base.join(sanitize_folder_name(name)));+ }++ let id = sync_root_id(device);+ let _ = StorageProviderSyncRootManager::Unregister(&id);++ if let Some(path) = folder_to_clean {+ cleanup_sync_root_dir(&path);+ }+ if let Some(base) = base_sync_dir() {+ let _ = std::fs::remove_dir(&base);+ }+}++fn cleanup_sync_root_dir(path: &Path) {+ if !path.exists() {+ return;+ }+ let _ = std::fs::remove_dir_all(path);+}++fn register_and_connect(device: DeviceId, name: &str, online: bool) -> Result<(), String> {+ let base = base_sync_dir().ok_or_else(|| "no user home directory".to_owned())?;+ let folder_name = sanitize_folder_name(name);+ let root_path = base.join(&folder_name);+ std::fs::create_dir_all(&root_path).map_err(|e| format!("create sync root dir: {e}"))?;++ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let icon_resource = format!("{},0", exe.display());++ let info = StorageProviderSyncRootInfo::new().map_err(|e| format!("SyncRootInfo::new: {e}"))?;+ info.SetId(&sync_root_id(device)).map_err(|e| format!("SetId: {e}"))?;++ let folder = StorageFolder::GetFolderFromPathAsync(&HSTRING::from(root_path.as_os_str()))+ .map_err(|e| format!("GetFolderFromPathAsync: {e}"))?+ .join()+ .map_err(|e| format!("GetFolderFromPathAsync.join: {e}"))?;+ info.SetPath(&folder).map_err(|e| format!("SetPath: {e}"))?;+ info.SetDisplayNameResource(&HSTRING::from(name)).map_err(|e| format!("SetDisplayNameResource: {e}"))?;+ info.SetIconResource(&HSTRING::from(&icon_resource)).map_err(|e| format!("SetIconResource: {e}"))?;+ info.SetVersion(&HSTRING::from(env!("CARGO_PKG_VERSION"))).map_err(|e| format!("SetVersion: {e}"))?;+ info.SetHydrationPolicy(StorageProviderHydrationPolicy::Full)+ .map_err(|e| format!("SetHydrationPolicy: {e}"))?;+ info.SetHydrationPolicyModifier(StorageProviderHydrationPolicyModifier::None)+ .map_err(|e| format!("SetHydrationPolicyModifier: {e}"))?;+ info.SetPopulationPolicy(StorageProviderPopulationPolicy::Full)+ .map_err(|e| format!("SetPopulationPolicy: {e}"))?;+ info.SetInSyncPolicy(+ StorageProviderInSyncPolicy::FileCreationTime | StorageProviderInSyncPolicy::DirectoryCreationTime,+ )+ .map_err(|e| format!("SetInSyncPolicy: {e}"))?;+ info.SetHardlinkPolicy(StorageProviderHardlinkPolicy::None)+ .map_err(|e| format!("SetHardlinkPolicy: {e}"))?;+ info.SetShowSiblingsAsGroup(false).map_err(|e| format!("SetShowSiblingsAsGroup: {e}"))?;++ let context_buf = CryptographicBuffer::ConvertStringToBinary(+ &HSTRING::from(device.to_string()),+ BinaryStringEncoding::Utf8,+ )+ .map_err(|e| format!("ConvertStringToBinary: {e}"))?;+ info.SetContext(&context_buf).map_err(|e| format!("SetContext: {e}"))?;++ StorageProviderSyncRootManager::Register(&info).map_err(|e| format!("Register: {e}"))?;++ let callbacks = [+ CF_CALLBACK_REGISTRATION {+ Type: CF_CALLBACK_TYPE_FETCH_PLACEHOLDERS,+ Callback: Some(on_fetch_placeholders),+ },+ CF_CALLBACK_REGISTRATION { Type: CF_CALLBACK_TYPE_FETCH_DATA, Callback: Some(on_fetch_data) },+ CF_CALLBACK_REGISTRATION { Type: CF_CALLBACK_TYPE_NOTIFY_RENAME, Callback: Some(on_notify_rename) },+ CF_CALLBACK_REGISTRATION { Type: CF_CALLBACK_TYPE_NOTIFY_DELETE, Callback: Some(on_notify_delete) },+ CF_CALLBACK_REGISTRATION { Type: CF_CALLBACK_TYPE_NONE, Callback: None },+ ];++ // Keep the DeviceId in a heap allocation for the process lifetime so async+ // cfapi callbacks always read a valid DeviceId and look up `ACTIVE_ROOTS`.+ let ctx_ptr: *const c_void = Box::into_raw(Box::new(device)).cast();+ let wide_root = to_wide_null(&root_path);+ // SAFETY: wide_root is null-terminated, callbacks ends with CF_CALLBACK_TYPE_NONE.+ let connection_key = unsafe {+ CfConnectSyncRoot(+ PCWSTR(wide_root.as_ptr()),+ callbacks.as_ptr(),+ Some(ctx_ptr),+ CF_CONNECT_FLAG_REQUIRE_PROCESS_INFO | CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH,+ )+ }+ .map_err(|e| format!("CfConnectSyncRoot: {e}"))?;++ let stop_watcher = Arc::new(AtomicBool::new(false));+ let active = Arc::new(ActiveRoot {+ device,+ name: name.to_owned(),+ root_path: root_path.clone(),+ connection_key,+ stop_watcher: stop_watcher.clone(),+ populated_dirs: Mutex::new(HashSet::new()),+ uploading: Mutex::new(HashSet::new()),+ });++ if let Some(map) = active_roots().as_mut() {+ map.insert(device, active.clone());+ }++ start_directory_watcher(active.clone(), stop_watcher);++ if online {+ core_host::spawn(async move {+ // Pre-populate top-level placeholders when connected so opening the+ // sync root in Explorer or inspecting it immediately shows folders.+ refresh_folder(active, "").await;+ });+ }++ tracing::info!(device = %device.short(), "registered phone storage sync root");+ Ok(())+}++fn to_wide_null(s: impl AsRef<OsStr>) -> Vec<u16> {+ s.as_ref().encode_wide().chain(std::iter::once(0)).collect()+}++unsafe fn pcwstr_to_string(ptr: PCWSTR) -> String {+ if ptr.is_null() {+ return String::new();+ }+ // SAFETY: caller guarantees `ptr` is a valid null-terminated wide string.+ let slice = unsafe { ptr.as_wide() };+ std::ffi::OsString::from_wide(slice).to_string_lossy().into_owned()+}++unsafe fn callback_root_and_path(+ info: *const CF_CALLBACK_INFO,+) -> Option<(Arc<ActiveRoot>, String, CF_CONNECTION_KEY, i64, i64)> {+ // SAFETY: Windows passes a valid CF_CALLBACK_INFO pointer to registered callbacks.+ let cb = unsafe { info.as_ref()? };+ if cb.CallbackContext.is_null() {+ return None;+ }+ // SAFETY: CallbackContext points to a leaked `Box<DeviceId>`.+ let device = unsafe { *(cb.CallbackContext as *const DeviceId) };+ let root = get_active_root(&device)?;+ // SAFETY: VolumeDosName and NormalizedPath are valid PCWSTRs in CF_CALLBACK_INFO.+ let vol = unsafe { pcwstr_to_string(cb.VolumeDosName) };+ // SAFETY: NormalizedPath is valid when CF_CONNECT_FLAG_REQUIRE_FULL_FILE_PATH is set.+ let norm = unsafe { pcwstr_to_string(cb.NormalizedPath) };+ let full = PathBuf::from(format!("{vol}{norm}"));+ let rel = relative_path_under_root(&root.root_path, &full)?;+ Some((root, rel, cb.ConnectionKey, cb.TransferKey, cb.RequestKey))+}++fn make_op_info(+ connection_key: CF_CONNECTION_KEY,+ transfer_key: i64,+ request_key: i64,+ op_type: CF_OPERATION_TYPE,+) -> CF_OPERATION_INFO {+ CF_OPERATION_INFO {+ StructSize: std::mem::size_of::<CF_OPERATION_INFO>() as u32,+ Type: op_type,+ ConnectionKey: connection_key,+ TransferKey: transfer_key,+ CorrelationVector: std::ptr::null(),+ SyncStatus: std::ptr::null(),+ RequestKey: request_key,+ }+}++unsafe extern "system" fn on_fetch_placeholders(+ callback_info: *const CF_CALLBACK_INFO,+ _callback_parameters: *const CF_CALLBACK_PARAMETERS,+) {+ // SAFETY: callback_info is provided by Windows cfapi.+ let Some((root, rel_path, connection_key, transfer_key, request_key)) =+ (unsafe { callback_root_and_path(callback_info) })+ else {+ return;+ };++ core_host::spawn(async move {+ let Some(node) = core_host::node() else {+ ack_placeholders_failed(connection_key, transfer_key, request_key);+ return;+ };+ match node.storage_list(root.device, &rel_path).await {+ Ok(entries) => {+ lock(&root.populated_dirs).insert(rel_path.clone());+ transfer_placeholders(connection_key, transfer_key, request_key, &rel_path, &entries);+ }+ Err(e) => {+ tracing::debug!(+ device = %root.device.short(),+ error = %e,+ "fetch placeholders failed"+ );+ ack_placeholders_failed(connection_key, transfer_key, request_key);+ }+ }+ });+}++fn transfer_placeholders(+ connection_key: CF_CONNECTION_KEY,+ transfer_key: i64,+ request_key: i64,+ parent_rel: &str,+ entries: &[StorageEntry],+) {+ let mut wide_names: Vec<Vec<u16>> = Vec::with_capacity(entries.len());+ let mut identities: Vec<Vec<u8>> = Vec::with_capacity(entries.len());+ for entry in entries {+ wide_names.push(to_wide_null(&entry.name));+ let rel =+ if parent_rel.is_empty() { entry.name.clone() } else { format!("{parent_rel}/{}", entry.name) };+ identities.push(rel.into_bytes());+ }++ let mut create_infos: Vec<CF_PLACEHOLDER_CREATE_INFO> = entries+ .iter()+ .enumerate()+ .map(|(i, entry)| build_placeholder_create_info(entry, &wide_names[i], &identities[i]))+ .collect();++ let op_info =+ make_op_info(connection_key, transfer_key, request_key, CF_OPERATION_TYPE_TRANSFER_PLACEHOLDERS);+ let mut op_params = CF_OPERATION_PARAMETERS {+ ParamSize: std::mem::size_of::<CF_OPERATION_PARAMETERS>() as u32,+ Anonymous: CF_OPERATION_PARAMETERS_0 {+ TransferPlaceholders: windows::Win32::Storage::CloudFilters::CF_OPERATION_PARAMETERS_0_4 {+ Flags: CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAG_DISABLE_ON_DEMAND_POPULATION,+ CompletionStatus: STATUS_SUCCESS,+ PlaceholderTotalCount: create_infos.len() as i64,+ PlaceholderArray: if create_infos.is_empty() {+ std::ptr::null_mut()+ } else {+ create_infos.as_mut_ptr()+ },+ PlaceholderCount: create_infos.len() as u32,+ EntriesProcessed: 0,+ },+ },+ };+ // SAFETY: op_info and op_params point to valid stack structures and buffers.+ let _ = unsafe { CfExecute(&op_info, &mut op_params) };+}++fn ack_placeholders_failed(connection_key: CF_CONNECTION_KEY, transfer_key: i64, request_key: i64) {+ let op_info =+ make_op_info(connection_key, transfer_key, request_key, CF_OPERATION_TYPE_TRANSFER_PLACEHOLDERS);+ let mut op_params = CF_OPERATION_PARAMETERS {+ ParamSize: std::mem::size_of::<CF_OPERATION_PARAMETERS>() as u32,+ Anonymous: CF_OPERATION_PARAMETERS_0 {+ TransferPlaceholders: windows::Win32::Storage::CloudFilters::CF_OPERATION_PARAMETERS_0_4 {+ Flags: windows::Win32::Storage::CloudFilters::CF_OPERATION_TRANSFER_PLACEHOLDERS_FLAGS(0),+ CompletionStatus: STATUS_CLOUD_NETWORK_UNAVAILABLE,+ PlaceholderTotalCount: 0,+ PlaceholderArray: std::ptr::null_mut(),+ PlaceholderCount: 0,+ EntriesProcessed: 0,+ },+ },+ };+ // SAFETY: op_info and op_params are valid.+ let _ = unsafe { CfExecute(&op_info, &mut op_params) };+}++fn build_placeholder_create_info(+ entry: &StorageEntry,+ wide_name: &[u16],+ identity: &[u8],+) -> CF_PLACEHOLDER_CREATE_INFO {+ let ticks = unix_ms_to_filetime_ticks(entry.modified);+ let attrs = if entry.is_dir { FILE_ATTRIBUTE_DIRECTORY.0 } else { FILE_ATTRIBUTE_NORMAL.0 };+ let file_size = if entry.is_dir { 0 } else { entry.size as i64 };+ CF_PLACEHOLDER_CREATE_INFO {+ RelativeFileName: PCWSTR(wide_name.as_ptr()),+ FsMetadata: CF_FS_METADATA {+ BasicInfo: FILE_BASIC_INFO {+ CreationTime: ticks,+ LastAccessTime: ticks,+ LastWriteTime: ticks,+ ChangeTime: ticks,+ FileAttributes: attrs,+ },+ FileSize: file_size,+ },+ FileIdentity: identity.as_ptr().cast(),+ FileIdentityLength: identity.len() as u32,+ Flags: CF_PLACEHOLDER_CREATE_FLAG_MARK_IN_SYNC,+ Result: windows::core::HRESULT(0),+ CreateUsn: 0,+ }+}++unsafe extern "system" fn on_fetch_data(+ callback_info: *const CF_CALLBACK_INFO,+ callback_parameters: *const CF_CALLBACK_PARAMETERS,+) {+ // SAFETY: callback_info and callback_parameters are provided by Windows cfapi.+ let Some((root, rel_path, connection_key, transfer_key, request_key)) =+ (unsafe { callback_root_and_path(callback_info) })+ else {+ return;+ };+ let Some(params) = (unsafe { callback_parameters.as_ref() }) else {+ return;+ };+ // SAFETY: Union variant matches CF_CALLBACK_TYPE_FETCH_DATA.+ let fetch = unsafe { params.Anonymous.FetchData };+ let required_offset = fetch.RequiredFileOffset.max(0) as u64;+ let required_length = fetch.RequiredLength.max(0) as u64;++ core_host::spawn(async move {+ let Some(node) = core_host::node() else {+ ack_data_failed(+ connection_key,+ transfer_key,+ request_key,+ required_offset as i64,+ STATUS_CLOUD_NETWORK_UNAVAILABLE,+ );+ return;+ };++ let (meta, mut recv) = match node+ .storage_read_stream(root.device, &rel_path, required_offset, Some(required_length))+ .await+ {+ Ok(res) => res,+ Err(e) => {+ tracing::debug!(+ device = %root.device.short(),+ error = %e,+ "fetch data stream failed"+ );+ ack_data_failed(+ connection_key,+ transfer_key,+ request_key,+ required_offset as i64,+ STATUS_CLOUD_NETWORK_UNAVAILABLE,+ );+ return;+ }+ };+ let total_size = meta.size;++ if required_length == 0 {+ let _ = transfer_data_chunk(+ connection_key,+ transfer_key,+ request_key,+ &[],+ required_offset as i64,+ STATUS_SUCCESS,+ );+ return;+ }++ let mut current_offset = required_offset;+ let mut remaining = required_length;+ let mut buf = Vec::with_capacity(HYDRATE_CHUNK_BYTES);++ while remaining > 0 {+ let want = (remaining as usize).min(HYDRATE_CHUNK_BYTES);+ buf.clear();+ while buf.len() < want {+ match recv.read_chunk(want - buf.len()).await {+ Ok(Some(chunk)) => buf.extend_from_slice(&chunk),+ Ok(None) => break,+ Err(e) => {+ tracing::debug!(error = %e, "hydration stream read error");+ ack_data_failed(+ connection_key,+ transfer_key,+ request_key,+ current_offset as i64,+ STATUS_CLOUD_NETWORK_UNAVAILABLE,+ );+ return;+ }+ }+ }+ if buf.is_empty() {+ break;+ }+ let len = buf.len() as u64;+ let completed = (current_offset + len).min(total_size);+ // SAFETY: valid connection_key and transfer_key during active fetch.+ let _ = unsafe {+ CfReportProviderProgress(connection_key, transfer_key, total_size as i64, completed as i64)+ };+ if !transfer_data_chunk(+ connection_key,+ transfer_key,+ request_key,+ &buf,+ current_offset as i64,+ STATUS_SUCCESS,+ ) {+ return;+ }+ current_offset += len;+ remaining = remaining.saturating_sub(len);+ }+ });+}++fn transfer_data_chunk(+ connection_key: CF_CONNECTION_KEY,+ transfer_key: i64,+ request_key: i64,+ data: &[u8],+ offset: i64,+ status: NTSTATUS,+) -> bool {+ let op_info = make_op_info(connection_key, transfer_key, request_key, CF_OPERATION_TYPE_TRANSFER_DATA);+ let mut op_params = CF_OPERATION_PARAMETERS {+ ParamSize: std::mem::size_of::<CF_OPERATION_PARAMETERS>() as u32,+ Anonymous: CF_OPERATION_PARAMETERS_0 {+ TransferData: windows::Win32::Storage::CloudFilters::CF_OPERATION_PARAMETERS_0_0 {+ Flags: windows::Win32::Storage::CloudFilters::CF_OPERATION_TRANSFER_DATA_FLAGS(0),+ CompletionStatus: status,+ Buffer: if data.is_empty() { std::ptr::null() } else { data.as_ptr().cast() },+ Offset: offset,+ Length: data.len() as i64,+ },+ },+ };+ // SAFETY: op_info and op_params reference valid memory for the duration of CfExecute.+ unsafe { CfExecute(&op_info, &mut op_params) }.is_ok()+}++fn ack_data_failed(+ connection_key: CF_CONNECTION_KEY,+ transfer_key: i64,+ request_key: i64,+ offset: i64,+ status: NTSTATUS,+) {+ let _ = transfer_data_chunk(connection_key, transfer_key, request_key, &[], offset, status);+}++unsafe extern "system" fn on_notify_rename(+ callback_info: *const CF_CALLBACK_INFO,+ callback_parameters: *const CF_CALLBACK_PARAMETERS,+) {+ // SAFETY: callback_info and callback_parameters are provided by Windows cfapi.+ let Some((root, old_rel, connection_key, transfer_key, request_key)) =+ (unsafe { callback_root_and_path(callback_info) })+ else {+ return;+ };+ let Some(cb) = (unsafe { callback_info.as_ref() }) else { return };+ let Some(params) = (unsafe { callback_parameters.as_ref() }) else { return };+ // SAFETY: Union variant matches CF_CALLBACK_TYPE_NOTIFY_RENAME.+ let rename = unsafe { params.Anonymous.Rename };+ // SAFETY: VolumeDosName and TargetPath are valid PCWSTRs.+ let vol = unsafe { pcwstr_to_string(cb.VolumeDosName) };+ let target_norm = unsafe { pcwstr_to_string(rename.TargetPath) };+ let target_full = PathBuf::from(format!("{vol}{target_norm}"));+ let new_rel = relative_path_under_root(&root.root_path, &target_full);++ core_host::spawn(async move {+ let Some(node) = core_host::node() else {+ ack_rename(connection_key, transfer_key, request_key, STATUS_CLOUD_NETWORK_UNAVAILABLE);+ return;+ };+ let status = match new_rel {+ Some(new_rel) if !old_rel.is_empty() && !new_rel.is_empty() => {+ match node.storage_rename(root.device, &old_rel, &new_rel).await {+ Ok(()) => STATUS_SUCCESS,+ Err(nectarlink_core::Error::Offline) => STATUS_CLOUD_NETWORK_UNAVAILABLE,+ Err(nectarlink_core::Error::Denied) => STATUS_ACCESS_DENIED,+ Err(_) => STATUS_CLOUD_UNSUCCESSFUL,+ }+ }+ _ => STATUS_ACCESS_DENIED,+ };+ ack_rename(connection_key, transfer_key, request_key, status);+ });+}++fn ack_rename(connection_key: CF_CONNECTION_KEY, transfer_key: i64, request_key: i64, status: NTSTATUS) {+ let op_info = make_op_info(connection_key, transfer_key, request_key, CF_OPERATION_TYPE_ACK_RENAME);+ let mut op_params = CF_OPERATION_PARAMETERS {+ ParamSize: std::mem::size_of::<CF_OPERATION_PARAMETERS>() as u32,+ Anonymous: CF_OPERATION_PARAMETERS_0 {+ AckRename: windows::Win32::Storage::CloudFilters::CF_OPERATION_PARAMETERS_0_6 {+ Flags: windows::Win32::Storage::CloudFilters::CF_OPERATION_ACK_RENAME_FLAGS(0),+ CompletionStatus: status,+ },+ },+ };+ // SAFETY: op_info and op_params are valid.+ let _ = unsafe { CfExecute(&op_info, &mut op_params) };+}++unsafe extern "system" fn on_notify_delete(+ callback_info: *const CF_CALLBACK_INFO,+ _callback_parameters: *const CF_CALLBACK_PARAMETERS,+) {+ // SAFETY: callback_info is provided by Windows cfapi.+ let Some((root, rel_path, connection_key, transfer_key, request_key)) =+ (unsafe { callback_root_and_path(callback_info) })+ else {+ return;+ };++ core_host::spawn(async move {+ if rel_path.is_empty() {+ ack_delete(connection_key, transfer_key, request_key, STATUS_ACCESS_DENIED);+ return;+ }+ let Some(node) = core_host::node() else {+ ack_delete(connection_key, transfer_key, request_key, STATUS_CLOUD_NETWORK_UNAVAILABLE);+ return;+ };+ let status = match node.storage_delete(root.device, &rel_path, true).await {+ Ok(()) => STATUS_SUCCESS,+ Err(nectarlink_core::Error::Offline) => STATUS_CLOUD_NETWORK_UNAVAILABLE,+ Err(nectarlink_core::Error::Denied) => STATUS_ACCESS_DENIED,+ Err(nectarlink_core::Error::Storage(msg)) if msg.contains("not_found") => STATUS_SUCCESS,+ Err(_) => STATUS_CLOUD_UNSUCCESSFUL,+ };+ ack_delete(connection_key, transfer_key, request_key, status);+ });+}++fn ack_delete(connection_key: CF_CONNECTION_KEY, transfer_key: i64, request_key: i64, status: NTSTATUS) {+ let op_info = make_op_info(connection_key, transfer_key, request_key, CF_OPERATION_TYPE_ACK_DELETE);+ let mut op_params = CF_OPERATION_PARAMETERS {+ ParamSize: std::mem::size_of::<CF_OPERATION_PARAMETERS>() as u32,+ Anonymous: CF_OPERATION_PARAMETERS_0 {+ AckDelete: windows::Win32::Storage::CloudFilters::CF_OPERATION_PARAMETERS_0_7 {+ Flags: windows::Win32::Storage::CloudFilters::CF_OPERATION_ACK_DELETE_FLAGS(0),+ CompletionStatus: status,+ },+ },+ };+ // SAFETY: op_info and op_params are valid.+ let _ = unsafe { CfExecute(&op_info, &mut op_params) };+}++/// Refreshes a folder's placeholders from the phone (`storage.changed` or initial connect).+async fn refresh_folder(root: Arc<ActiveRoot>, rel_folder: &str) {+ let Some(node) = core_host::node() else { return };+ let Ok(entries) = node.storage_list(root.device, rel_folder).await else { return };++ let local_dir = if rel_folder.is_empty() {+ root.root_path.clone()+ } else {+ root.root_path.join(rel_folder.replace('/', "\\"))+ };+ if !local_dir.exists() {+ return;+ }++ lock(&root.populated_dirs).insert(rel_folder.to_owned());++ let mut missing: Vec<StorageEntry> = Vec::new();+ for entry in entries {+ let child_path = local_dir.join(&entry.name);+ if !child_path.exists() {+ missing.push(entry);+ }+ }+ if missing.is_empty() {+ return;+ }++ let mut wide_names: Vec<Vec<u16>> = Vec::with_capacity(missing.len());+ let mut identities: Vec<Vec<u8>> = Vec::with_capacity(missing.len());+ for entry in &missing {+ wide_names.push(to_wide_null(&entry.name));+ let rel =+ if rel_folder.is_empty() { entry.name.clone() } else { format!("{rel_folder}/{}", entry.name) };+ identities.push(rel.into_bytes());+ }+ let mut create_infos: Vec<CF_PLACEHOLDER_CREATE_INFO> = missing+ .iter()+ .enumerate()+ .map(|(i, entry)| build_placeholder_create_info(entry, &wide_names[i], &identities[i]))+ .collect();++ let wide_dir = to_wide_null(&local_dir);+ let mut processed = 0u32;+ // SAFETY: wide_dir is null-terminated and create_infos stays alive for the call.+ let _ = unsafe {+ CfCreatePlaceholders(+ PCWSTR(wide_dir.as_ptr()),+ &mut create_infos,+ windows::Win32::Storage::CloudFilters::CF_CREATE_FLAG_NONE,+ Some(&mut processed),+ )+ };+}++/// Watches the sync root directory for files or folders dropped in by the user+/// and uploads them to the phone via `storage.write` / `storage.mkdir`.+fn start_directory_watcher(root: Arc<ActiveRoot>, stop: Arc<AtomicBool>) {+ let _ = std::thread::Builder::new().name("storage-watch".into()).spawn(move || {+ let wide_dir = to_wide_null(&root.root_path);+ // SAFETY: wide_dir is a valid null-terminated path.+ let dir_handle = unsafe {+ CreateFileW(+ PCWSTR(wide_dir.as_ptr()),+ FILE_LIST_DIRECTORY.0,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ None,+ OPEN_EXISTING,+ FILE_FLAG_BACKUP_SEMANTICS,+ None,+ )+ };+ let Ok(dir_handle) = dir_handle else { return };+ if dir_handle == INVALID_HANDLE_VALUE {+ return;+ }++ let mut buf = vec![0u64; 4096];+ while !stop.load(Ordering::Relaxed) {+ let mut bytes_returned = 0u32;+ // SAFETY: buf is 8-byte aligned and valid for ReadDirectoryChangesW.+ let ok = unsafe {+ ReadDirectoryChangesW(+ dir_handle,+ buf.as_mut_ptr().cast(),+ (buf.len() * std::mem::size_of::<u64>()) as u32,+ true,+ FILE_NOTIFY_CHANGE_FILE_NAME+ | FILE_NOTIFY_CHANGE_DIR_NAME+ | FILE_NOTIFY_CHANGE_LAST_WRITE+ | FILE_NOTIFY_CHANGE_SIZE,+ Some(&mut bytes_returned),+ None,+ None,+ )+ }+ .is_ok();++ if !ok || stop.load(Ordering::Relaxed) || bytes_returned == 0 {+ break;+ }++ let changed_paths = parse_notify_buffer(+ // SAFETY: bytes_returned bytes were initialized by ReadDirectoryChangesW.+ unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::<u8>(), bytes_returned as usize) },+ );++ for rel_win in changed_paths {+ let rel_slash = rel_win.replace('\\', "/");+ if rel_slash.is_empty()+ || rel_slash.split('/').any(|seg| seg.starts_with('.') || seg.starts_with("~$"))+ {+ continue;+ }+ let full_path = root.root_path.join(&rel_win);+ if !needs_upload(&full_path) {+ continue;+ }+ {+ let mut uploading = lock(&root.uploading);+ if !uploading.insert(rel_slash.clone()) {+ continue;+ }+ }+ let root_clone = root.clone();+ core_host::spawn(async move {+ // Brief debounce so Explorer finishes writing the dropped file.+ tokio::time::sleep(Duration::from_millis(350)).await;+ upload_local_item(&root_clone, &rel_slash, &full_path).await;+ lock(&root_clone.uploading).remove(&rel_slash);+ });+ }+ }++ // SAFETY: dir_handle was opened with CreateFileW above.+ let _ = unsafe { CloseHandle(dir_handle) };+ });+}++fn parse_notify_buffer(bytes: &[u8]) -> Vec<String> {+ let mut out = Vec::new();+ let mut offset = 0usize;+ while offset + std::mem::size_of::<FILE_NOTIFY_INFORMATION>() <= bytes.len() {+ // SAFETY: offset is within bounds and 4-byte aligned in ReadDirectoryChangesW buffer.+ let info = unsafe { &*(bytes.as_ptr().add(offset) as *const FILE_NOTIFY_INFORMATION) };+ let name_bytes = info.FileNameLength as usize;+ let name_offset = offset + std::mem::offset_of!(FILE_NOTIFY_INFORMATION, FileName);+ if name_offset + name_bytes <= bytes.len()+ && matches!(info.Action, FILE_ACTION_ADDED | FILE_ACTION_MODIFIED | FILE_ACTION_RENAMED_NEW_NAME)+ {+ // SAFETY: FileName is a UTF-16 slice of `name_bytes / 2` u16 elements.+ let wide = unsafe {+ std::slice::from_raw_parts(bytes.as_ptr().add(name_offset) as *const u16, name_bytes / 2)+ };+ let rel = std::ffi::OsString::from_wide(wide).to_string_lossy().into_owned();+ if !out.contains(&rel) {+ out.push(rel);+ }+ }+ if info.NextEntryOffset == 0 {+ break;+ }+ offset = offset.saturating_add(info.NextEntryOffset as usize);+ }+ out+}++/// Checks whether `full_path` is a newly dropped non-placeholder file/folder or+/// a modified placeholder that is no longer in sync.+fn needs_upload(full_path: &Path) -> bool {+ let wide = to_wide_null(full_path);+ let mut find_data = WIN32_FIND_DATAW::default();+ // SAFETY: wide is null-terminated and find_data is a valid struct.+ let handle = unsafe { FindFirstFileW(PCWSTR(wide.as_ptr()), &mut find_data) };+ let Ok(handle) = handle else { return false };+ if handle == INVALID_HANDLE_VALUE {+ return false;+ }+ // SAFETY: handle came from FindFirstFileW.+ let _ = unsafe { FindClose(handle) };+ // SAFETY: dwFileAttributes and dwReserved0 (reparse tag) were populated by FindFirstFileW.+ let state =+ unsafe { CfGetPlaceholderStateFromAttributeTag(find_data.dwFileAttributes, find_data.dwReserved0) };+ if (state.0 & CF_PLACEHOLDER_STATE_PLACEHOLDER.0) == 0 {+ return true;+ }+ (state.0 & CF_PLACEHOLDER_STATE_IN_SYNC.0) == 0+}++async fn upload_local_item(root: &Arc<ActiveRoot>, rel_slash: &str, full_path: &Path) {+ if !full_path.exists() || !needs_upload(full_path) {+ return;+ }+ let Some(node) = core_host::node() else { return };+ if full_path.is_dir() {+ if node.storage_mkdir(root.device, rel_slash).await.is_ok() {+ mark_path_in_sync(full_path, rel_slash, true);+ }+ } else if full_path.is_file() && node.storage_write(root.device, rel_slash, full_path).await.is_ok() {+ mark_path_in_sync(full_path, rel_slash, false);+ }+}++fn mark_path_in_sync(full_path: &Path, rel_slash: &str, is_dir: bool) {+ let wide = to_wide_null(full_path);+ let flags = if is_dir { FILE_FLAG_BACKUP_SEMANTICS } else { Default::default() };+ // SAFETY: wide is a valid null-terminated path.+ let handle = unsafe {+ CreateFileW(+ PCWSTR(wide.as_ptr()),+ GENERIC_READ.0 | GENERIC_WRITE.0,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ None,+ OPEN_EXISTING,+ flags,+ None,+ )+ };+ let Ok(handle): Result<HANDLE, _> = handle else { return };+ if handle == INVALID_HANDLE_VALUE {+ return;+ }+ let identity = rel_slash.as_bytes();+ // SAFETY: handle is open with read/write access; identity is valid for the call.+ let converted = unsafe {+ CfConvertToPlaceholder(+ handle,+ Some(identity.as_ptr().cast()),+ identity.len() as u32,+ CF_CONVERT_FLAG_MARK_IN_SYNC,+ None,+ None,+ )+ };+ if converted.is_err() {+ // Already a placeholder: mark it in sync.+ // SAFETY: handle is valid.+ let _ = unsafe { CfSetInSyncState(handle, CF_IN_SYNC_STATE_IN_SYNC, CF_SET_IN_SYNC_FLAG_NONE, None) };+ }+ // SAFETY: handle was opened with CreateFileW above.+ let _ = unsafe { CloseHandle(handle) };+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn converts_unix_ms_to_filetime_and_back() {+ let unix_ms = 1_710_000_000_123i64;+ let ticks = unix_ms_to_filetime_ticks(unix_ms);+ assert_eq!(ticks, EPOCH_DIFF_100NS + unix_ms * 10_000);+ assert_eq!(filetime_ticks_to_unix_ms(ticks), unix_ms);+ assert_eq!(unix_ms_to_filetime_ticks(-500), EPOCH_DIFF_100NS);+ }++ #[test]+ fn builds_placeholder_metadata_for_files_and_folders() {+ let file_entry = StorageEntry {+ name: "photo.jpg".into(),+ size: 42_000,+ modified: 1_700_000_000_000,+ is_dir: false,+ };+ let wide_file = to_wide_null(&file_entry.name);+ let id_file = b"DCIM/photo.jpg";+ let info_file = build_placeholder_create_info(&file_entry, &wide_file, id_file);+ assert_eq!(info_file.FsMetadata.FileSize, 42_000);+ assert_eq!(info_file.FsMetadata.BasicInfo.FileAttributes, FILE_ATTRIBUTE_NORMAL.0);+ assert_eq!(+ info_file.FsMetadata.BasicInfo.LastWriteTime,+ unix_ms_to_filetime_ticks(1_700_000_000_000)+ );+ assert_eq!(info_file.FileIdentityLength, id_file.len() as u32);++ let dir_entry =+ StorageEntry { name: "Camera".into(), size: 999, modified: 1_700_000_000_000, is_dir: true };+ let wide_dir = to_wide_null(&dir_entry.name);+ let id_dir = b"DCIM/Camera";+ let info_dir = build_placeholder_create_info(&dir_entry, &wide_dir, id_dir);+ assert_eq!(info_dir.FsMetadata.FileSize, 0);+ assert_eq!(info_dir.FsMetadata.BasicInfo.FileAttributes, FILE_ATTRIBUTE_DIRECTORY.0);+ }++ #[test]+ fn normalizes_relative_paths_and_sanitizes_folder_names() {+ let root = Path::new(r"C:\Users\alice\Nectarlink\Pixel 9");+ assert_eq!(relative_path_under_root(root, root), Some(String::new()));+ assert_eq!(+ relative_path_under_root(root, Path::new(r"C:\Users\alice\Nectarlink\Pixel 9\DCIM\Camera\a.jpg")),+ Some("DCIM/Camera/a.jpg".into())+ );+ assert_eq!(+ relative_path_under_root(root, Path::new(r"C:\Users\alice\Nectarlink\Pixel 9 Pro\DCIM")),+ None+ );++ assert_eq!(sanitize_folder_name("Pixel 9 (test)"), "Pixel 9 (test)");+ assert_eq!(sanitize_folder_name("My:Phone*1?"), "My Phone 1");+ assert_eq!(sanitize_folder_name("CON"), "CON phone");+ }+}diff --git a/docs/PLAN.md b/docs/PLAN.mdindex 54cf2d1..1edec27 100644--- a/docs/PLAN.md+++ b/docs/PLAN.md@@ -165,7 +165,7 @@ current Android. Talking through the PC comes with the HFP item above.| **Flick to send**: flick a photo/file upward on the phone and it lands on the PC. Drag a file to the screen edge on the PC and it flies to the phone. Physics-based animation on both ends | P1 || **LocalSend protocol interop**: send to and receive from any LocalSend device (iOS, Mac, Linux). We implement its open protocol in Rust; we don't reuse its (Dart) code | P1 || **Coexistence**: runs side by side with KDE Connect (ports 1714–1764) and LocalSend (53317) on the same PC without conflicts. If LocalSend's port is taken, Nectarlink still sends but leaves receiving to the LocalSend app | P0 |-| **Phone storage in Explorer** (Cloud Files API: placeholders, on-demand download, native sync icons) | P1 |+| **Phone storage in Explorer** (Cloud Files API: placeholders, on-demand download, native sync icons) ✅ | P1 || **Photos**: gallery with thumbnails, recent screenshots/photos pop up on PC, drag out to the desktop | P0 (recent), P1 (gallery) || Folder sync (Syncthing-style two-way folders, e.g. Camera → PC) | P2 |diff --git a/docs/architecture/capabilities.md b/docs/architecture/capabilities.mdindex 5ee3c63..8848c30 100644--- a/docs/architecture/capabilities.md+++ b/docs/architecture/capabilities.md@@ -122,7 +122,7 @@ the OS (`android` → phone, `windows`/`macos` → desktop).`notifications`, `messages`, `calls`, `contacts`, `clipboard`, `files`,`media`, `photos`, `recordings`, `toggles`, `pc_actions`, `mirroring` (on by-default) and `remote_input`, `commands`, `remote_files` (off by default). Toggles are this+default) and `storage`, `remote_input`, `commands`, `remote_files` (off by default). Toggles are thisdevice's policy for that peer and are stored locally, so a feature the PCuser switched off is Locked on the PC while the phone may still show it asAvailable. Everything else in the matrix is identical on both devices.diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.mdindex 4c64d96..17df672 100644--- a/docs/protocol/capabilities.md+++ b/docs/protocol/capabilities.md@@ -59,6 +59,8 @@ capability is missing.| `toggles.brightness` | Changes the screen brightness ([toggles](toggles.md)) | Modify system settings or Elevated || `toggles.wifi` | Turns Wi-Fi on or off ([toggles](toggles.md)) | Elevated || `toggles.bluetooth` | Turns Bluetooth on or off ([toggles](toggles.md)) | Elevated |+| `storage.read` | Lists folders and reads files in shared storage or picked SAF folders ([storage](storage.md)) | All files access or picked SAF folder |+| `storage.write` | Creates folders, writes/uploads files, renames and deletes entries in shared storage or picked SAF folders ([storage](storage.md)) | All files access or picked SAF folder || `camera.stream` | Streams a camera for webcam use | camera permission |## Desktop@@ -75,6 +77,7 @@ capability is missing.| `mirror.view` | Shows a phone's screen ([mirroring](mirror.md)) | app update || `mirror.listen` | Plays a mirrored phone's sound ([mirroring](mirror.md)) | app update || `files.browse` | Lets a paired phone browse and fetch its files | app update |+| `storage.mount` | Mounts a paired phone's shared storage in File Explorer ([storage](storage.md)) | app update || `input.inject` | Accepts pointer, keyboard and presentation input ([remote input](remote.md)) | app update || `recorder` | Saves and converts voice recordings from a phone ([recorder](recorder.md)) | app update || `deck.actions` | Shares its Deck layout and live tile state and runs Deck actions ([deck](deck.md)) | app update |diff --git a/docs/protocol/storage.md b/docs/protocol/storage.mdnew file mode 100644index 0000000..9eaedde--- /dev/null+++ b/docs/protocol/storage.md@@ -0,0 +1,133 @@+# Storage service (protocol v0)++> Status: **draft.** Builds on [protocol v0](v0.md) and the+> [files service](files.md); breaking changes are allowed until v1.+> License: CC BY 4.0.++Lets a PC browse and mount a phone's shared storage in File Explorer (Windows+Cloud Files API) or inspect it from the CLI: folders list on demand, files+hydrate when opened via ranged reads, files dropped in upload with resume, and+renames, folder creation and deletions round-trip to the phone.++## 1. Capabilities++| ID | Offered by | Meaning |+|---|---|---|+| `storage.read` | phone | Lists folders and reads file byte ranges in the phone's shared storage (or folders picked with the Storage Access Framework) |+| `storage.write` | phone | Creates folders, writes/uploads files, renames and deletes entries in the phone's shared storage (or picked SAF folders) |+| `storage.mount` | PC | Mounts the phone's shared storage in File Explorer |++Access is guarded by the `storage` per-device toggle (**off by default** on the+phone, and configurable per device on both sides). While `storage` is off on+the phone for a PC, the phone rejects every `storage.*` request with `DENIED`+and prompts the user once so they can allow that PC.++## 2. Relative paths++All paths in `storage.*` messages are UTF-8, `/`-separated, and relative to the+phone's shared storage root:++- `""` (empty string) names the storage root itself (valid in `storage.list`+ and `storage.changed`).+- Non-root paths (`"DCIM/Camera"`, `"Download/report.pdf"`) consist of 1–32+ `/`-separated segments, at most 1 024 UTF-8 bytes in total.+- Each segment is 1–255 UTF-8 bytes, never `"."` or `".."`, and contains no+ `/`, `\`, NUL (`\0`) or control characters.+- Leading or trailing `/` is rejected.+- The phone resolves paths strictly inside its shared root (rejecting symlinks+ pointing outside the canonical root) and never exposes `/data` or the app's+ private directories.++## 3. Control-stream messages++```+t = "storage.list" id = n b = { path: text }+t = "storage.entries" re = n b = { entries: [ StorageEntry, ... ] }+t = "storage.mkdir" id = n b = { path: text }+t = "storage.rename" id = n b = { from: text, to: text }+t = "storage.delete" id = n b = { path: text, confirmed?: bool }+t = "storage.changed" b = { path: text }+```++```+StorageEntry = {+ name: text, // Entry name (single path segment, 1–255 bytes)+ size: uint, // Bytes (0 for directories)+ modified: int, // Last-modified timestamp (Unix milliseconds)+ is_dir: bool, // True for directories, false for regular files+}+```++### 3.1 `storage.list`++Lists the immediate children of `path` (`""` for the root). Symlinks pointing+outside the shared root and unreadable/private entries are omitted. If the list+would exceed `MAX_FRAME_LEN`, entries are trimmed to fit.++Errors: `NOT_FOUND` if `path` does not exist or is not a directory; `DENIED` if+`storage` is off or permission is not granted; `INVALID` if `path` is malformed.++### 3.2 `storage.mkdir`++Creates the directory `path` (and any missing parents inside the shared root).+Succeeds if `path` already exists as a directory.++### 3.3 `storage.rename`++Renames or moves `from` to `to` within the shared storage root.++### 3.4 `storage.delete`++Deletes `path`. On Android 11+, media items indexed by `MediaStore` are moved+to the system trash when possible; otherwise, deletion requires `confirmed =+true` (indicating the user confirmed deletion on the PC, e.g. in File Explorer+or the CLI).++### 3.5 `storage.changed`++Sent (debounced) by the phone to connected PCs that have listed `path` when+files or subfolders inside `path` change on the phone. Not answered.++## 4. Stream operations (`svc = "storage"`, `v = 1`)++File reads and writes use dedicated bidirectional QUIC streams opened by the PC+so large transfers and ranged hydrations never block the control stream.++### 4.1 `storage.read` (`op = "read"`)++```+PC -> phone: t = "stream" b = { svc: "storage", op: "read", v: 1 }+PC -> phone: t = "storage.read" id=1 b = { path: text, offset: uint, length?: uint }+phone -> PC: t = "storage.read.meta" re=1 b = { size: uint, modified: int, length: uint }+phone -> PC: <length raw bytes, then FIN>+```++Reads `length` bytes (or until EOF when `length` is omitted) starting at byte+`offset`. The phone replies with `storage.read.meta` giving the total file+`size`, `modified` time (Unix ms), and the exact `length` of raw bytes that+follow on the stream, or an `error` frame (`NOT_FOUND`, `DENIED`, `INVALID`)+before any raw bytes.++### 4.2 `storage.write` (`op = "write"`)++```+PC -> phone: t = "stream" b = { svc: "storage", op: "write", v: 1 }+PC -> phone: t = "storage.write" id=1 b = { id: text, path: text, size: uint, modified?: int }+phone -> PC: t = "storage.write.accept" re=1 b = { have: uint }+PC -> phone: <size - have raw bytes starting at offset have, then FIN>+phone -> PC: t = "storage.write.done" b = { size: uint, modified: int }+```++Uploads a file of `size` bytes to `path`. Like `files` ([files](files.md) §3),+writes are staged by `(peer, id, path, size)` so an interrupted upload retried+with the same `id` resumes from `have` bytes. Once all `size` bytes arrive, the+phone atomically commits the file to `path` (applying `modified` if given) and+sends `storage.write.done`.++## 5. Security and privacy++- The phone never exposes `/data` or its own private app directories.+- Every path is validated before touching the filesystem, and canonical paths+ are checked to stay inside the shared storage root (or within the user's+ chosen SAF trees when full storage access is not granted).+- Paths and file contents are never logged (protocol v0 §11).