diff --git a/.gitea/workflows/android-build.yml b/.gitea/workflows/android-build.yml new file mode 100644 index 0000000..cb0c4e1 --- /dev/null +++ b/.gitea/workflows/android-build.yml @@ -0,0 +1,53 @@ +name: Build Android APKs + +on: + push: + +jobs: + build: + runs-on: debian + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + - name: Set up Android command line tools + uses: android-actions/setup-android@v3.2.2 + with: + packages: platform-tools + + - name: Install Android SDK platform and build tools + run: sdkmanager --install "platforms;android-37.0" "build-tools;36.0.0" + + - name: Build APKs + shell: bash + env: + ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }} + ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }} + run: | + set -euo pipefail + if [[ -n "$ANDROID_KEYSTORE_BASE64" ]]; then + if [[ -z "$ANDROID_KEYSTORE_PASSWORD" || -z "$ANDROID_KEY_ALIAS" || -z "$ANDROID_KEY_PASSWORD" ]]; then + echo "Release signing secrets are incomplete" >&2 + exit 1 + fi + export ANDROID_KEYSTORE_PATH="$(mktemp "${TMPDIR:-/tmp}/smb-explorer-release.XXXXXX.jks")" + printf '%s' "$ANDROID_KEYSTORE_BASE64" | base64 --decode > "$ANDROID_KEYSTORE_PATH" + trap 'rm -f "$ANDROID_KEYSTORE_PATH"' EXIT + fi + chmod +x ./gradlew + ./gradlew --no-daemon :app:assembleRelease :app:assembleDebug + + - name: Upload APKs + uses: actions/upload-artifact@v4 + with: + name: android-apks + path: app/build/outputs/apk/**/*.apk + if-no-files-found: error diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4b42951 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +.gradle/ +build/ +**/build/ +local.properties +.idea/ +*.iml +*.jks +*.keystore diff --git a/README.md b/README.md new file mode 100644 index 0000000..d774cf5 --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +# SMB Explorer + +Android 9+ SMB explorer. The first implementation is a Phase 0 compatibility probe for a real Samba share. + +## Run the probe + +Open the project in Android Studio, or run `./gradlew assembleDebug` with a JDK and Android SDK configured. Install `app/build/outputs/apk/debug/app-debug.apk` on the Galaxy S24. Enter the NAS host, share, credentials, and an optional folder path. Enter a large file path relative to the share to test three 64 KiB reads at the beginning, middle, and end. The screen reports listing time, entry count, byte counts, and hashes; it does not save credentials or downloaded content. + +Repeat after switching Wi-Fi off and back on. Record the Samba version, dialect, signing/encryption settings, Wi-Fi conditions, listing latency, and whether each range read succeeded. The probe opens a fresh connection for each run. + +Use **Test & save** to authenticate, list the selected folder, and save the share. When shares are saved, the app opens to a compact share list. Tap a share to browse it, **Edit** to change its connection fields, or **Add share** to open the new connection form. **Remove** deletes a saved entry after confirmation. The connection list, including passwords, is encrypted with a device-bound Android Keystore key. App backup is disabled because the key cannot be restored on another device. + +Tap a saved share to browse it. Folder rows open subfolders; the breadcrumb buttons navigate to parent folders or the root. Search filters the current listing, Sort cycles through name, date, and size with folders first, Show filters by file type, and Refresh reloads the current folder. File rows currently show details; media viewing and file actions are later phases. + +The current environment has not supplied a NAS address or credentials, so live compatibility and reconnect results remain to be measured on the device. + +Implementation plan: [PLAN.md](PLAN.md). + +## Gitea Actions + +Every push runs `.gitea/workflows/android-build.yml` on the runner labelled `debian`. The `android-apks` artifact on the Actions run contains a debug APK for testing and an unsigned release APK by default. The workflow installs JDK 17 and the required Android SDK packages, so the runner needs outbound access to the action repositories, Gradle, Maven, and Google Android downloads. + +For an installable release APK, add these repository Actions secrets: `ANDROID_KEYSTORE_BASE64` (base64 encoding of your release `.jks` file), `ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`, and `ANDROID_KEY_PASSWORD`. When all are present, the workflow signs the release build. Keep the keystore and its passwords backed up outside the repository; future updates need the same signing key. Never commit the keystore or passwords. diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..3811e20 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,47 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.plugin.compose") +} + +android { + namespace = "dev.alvin.smbexplorer" + compileSdk = 37 + val releaseKeystore = providers.environmentVariable("ANDROID_KEYSTORE_PATH").orNull + if (releaseKeystore != null) { + signingConfigs { + create("release") { + storeFile = file(releaseKeystore) + storePassword = providers.environmentVariable("ANDROID_KEYSTORE_PASSWORD").get() + keyAlias = providers.environmentVariable("ANDROID_KEY_ALIAS").get() + keyPassword = providers.environmentVariable("ANDROID_KEY_PASSWORD").get() + } + } + buildTypes { + getByName("release") { signingConfig = signingConfigs.getByName("release") } + } + } + defaultConfig { + applicationId = "dev.alvin.smbexplorer" + minSdk = 28 + targetSdk = 36 + versionCode = 1 + versionName = "0.1" + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + buildFeatures { compose = true } +} + +dependencies { + implementation(platform("androidx.compose:compose-bom:2026.09.00")) + implementation("androidx.activity:activity-compose:1.11.0") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.foundation:foundation") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") + implementation("com.hierynomus:smbj:0.15.0") + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test.ext:junit:1.3.0") +} diff --git a/app/src/androidTest/java/dev/alvin/smbexplorer/SavedShareStoreTest.kt b/app/src/androidTest/java/dev/alvin/smbexplorer/SavedShareStoreTest.kt new file mode 100644 index 0000000..5572a50 --- /dev/null +++ b/app/src/androidTest/java/dev/alvin/smbexplorer/SavedShareStoreTest.kt @@ -0,0 +1,30 @@ +package dev.alvin.smbexplorer + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class SavedShareStoreTest { + @Test fun encryptedShareSurvivesStoreRecreationAndCanBeRemoved() { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val store = SavedShareStore(context) + val target = SmbTarget("test.invalid", "media", 445, "tester", "distinct-test-secret", "") + val saved = store.save(target, "photos") + try { + val reloaded = SavedShareStore(context).load().single { it.id == saved.id } + assertEquals(target, reloaded.target) + assertEquals("photos", reloaded.folder) + val raw = context.getSharedPreferences("saved_shares", 0).getString("connections", "")!! + assertFalse(raw.contains(target.password)) + assertFalse(raw.contains(target.host)) + } finally { + store.delete(saved.id) + } + assertTrue(SavedShareStore(context).load().none { it.id == saved.id }) + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..b7f1098 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/app/src/main/java/dev/alvin/smbexplorer/BrowseScreen.kt b/app/src/main/java/dev/alvin/smbexplorer/BrowseScreen.kt new file mode 100644 index 0000000..2448cef --- /dev/null +++ b/app/src/main/java/dev/alvin/smbexplorer/BrowseScreen.kt @@ -0,0 +1,156 @@ +package dev.alvin.smbexplorer + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.withContext +import java.text.DateFormat +import java.util.Date + +private enum class SortMode { Name, Date, Size } +private enum class FileFilter { All, Images, Videos, Other, Folders } + +private val imageExtensions = setOf("jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "bmp", "avif") +private val videoExtensions = setOf("mp4", "mkv", "webm", "avi", "mov", "m4v", "ts", "mpeg", "mpg") + +private fun FileFilter.matches(entry: RemoteEntry): Boolean { + val extension = entry.name.substringAfterLast('.', "").lowercase() + return when (this) { + FileFilter.All -> true + FileFilter.Folders -> entry.directory + FileFilter.Images -> !entry.directory && extension in imageExtensions + FileFilter.Videos -> !entry.directory && extension in videoExtensions + FileFilter.Other -> !entry.directory && extension !in imageExtensions && extension !in videoExtensions + } +} + +@Composable +fun BrowseScreen(saved: SavedShare, onConnections: () -> Unit) { + var path by remember(saved.id) { mutableStateOf(saved.folder.trim('/', '\\').replace('/', '\\')) } + var refresh by remember { mutableIntStateOf(0) } + var search by remember { mutableStateOf("") } + var sort by remember { mutableStateOf(SortMode.Name) } + var filter by remember { mutableStateOf(FileFilter.All) } + var result by remember { mutableStateOf(null) } + var error by remember { mutableStateOf(null) } + var loading by remember { mutableStateOf(true) } + var selectedFile by remember { mutableStateOf(null) } + + fun up() { + path = path.substringBeforeLast('\\', "") + search = "" + } + BackHandler { if (path.isEmpty()) onConnections() else up() } + + LaunchedEffect(saved.id, path, refresh) { + loading = true + error = null + result = null + try { + result = withContext(Dispatchers.IO) { SmbProbe().use { it.run(saved.target, path, null) } } + } catch (e: CancellationException) { + throw e + } catch (e: Exception) { + error = "Could not open folder: ${e.javaClass.simpleName}: ${e.message ?: "No details"}" + } finally { + loading = false + } + } + + selectedFile?.let { file -> + AlertDialog( + onDismissRequest = { selectedFile = null }, + title = { Text(file.name) }, + text = { Text("Size: ${file.size} bytes\nModified: ${formatDate(file.modifiedAt)}\nPath: ${if (path.isEmpty()) file.name else "$path\\${file.name}"}") }, + confirmButton = { Button(onClick = { selectedFile = null }) { Text("Close") } }, + ) + } + + val visible = remember(result, search, sort, filter) { result?.entries.orEmpty() + .asSequence() + .filter { it.name.contains(search, ignoreCase = true) } + .filter { filter.matches(it) } + .sortedWith(compareByDescending { it.directory }.then( + when (sort) { + SortMode.Name -> compareBy(String.CASE_INSENSITIVE_ORDER) { it.name } + SortMode.Date -> compareByDescending { it.modifiedAt } + SortMode.Size -> compareByDescending { it.size } + }, + )) + .toList() + } + + Column(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Text(saved.target.share, style = MaterialTheme.typography.headlineSmall) + Button(onClick = onConnections) { Text("Connections") } + } + Row(Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Button(onClick = { path = ""; search = "" }) { Text("Root") } + var prefix = "" + path.split('\\').filter(String::isNotEmpty).forEach { segment -> + prefix = if (prefix.isEmpty()) segment else "$prefix\\$segment" + val destination = prefix + Button(onClick = { path = destination; search = "" }) { Text(segment) } + } + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(search, { search = it }, label = { Text("Search this folder") }, modifier = Modifier.weight(1f)) + Button(onClick = { refresh++ }) { Text("Refresh") } + } + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(onClick = { sort = SortMode.entries[(sort.ordinal + 1) % SortMode.entries.size] }) { + Text("Sort: ${sort.name}") + } + Button(onClick = { filter = FileFilter.entries[(filter.ordinal + 1) % FileFilter.entries.size] }) { + Text("Show: ${filter.name}") + } + } + if (loading) Text("Loading…") + error?.let { Text(it, color = MaterialTheme.colorScheme.error) } + result?.let { Text("${visible.size} of ${it.entries.size} entries · ${it.listingMs} ms") } + LazyColumn { + items(visible, key = { "$path/${it.name}" }) { entry -> + Row(Modifier.fillMaxWidth().clickable { + if (entry.directory) { + path = if (path.isEmpty()) entry.name else "$path\\${entry.name}" + search = "" + } else selectedFile = entry + }.padding(vertical = 12.dp), horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(if (entry.directory) "📁" else "📄") + Column { + Text(entry.name) + if (!entry.directory) Text("${entry.size} B · ${formatDate(entry.modifiedAt)}", style = MaterialTheme.typography.bodySmall) + } + } + } + } + } +} + +private fun formatDate(timestamp: Long): String = if (timestamp <= 0) "Unknown" else DateFormat.getDateTimeInstance().format(Date(timestamp)) diff --git a/app/src/main/java/dev/alvin/smbexplorer/MainActivity.kt b/app/src/main/java/dev/alvin/smbexplorer/MainActivity.kt new file mode 100644 index 0000000..f8fb083 --- /dev/null +++ b/app/src/main/java/dev/alvin/smbexplorer/MainActivity.kt @@ -0,0 +1,189 @@ +package dev.alvin.smbexplorer + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.launch +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { MaterialTheme(colorScheme = darkColorScheme()) { Surface { ProbeScreen() } } } + } +} + +@Composable +private fun ProbeScreen() { + val context = LocalContext.current + val store = remember { SavedShareStore(context) } + val initialShares = remember { runCatching { store.load() } } + var savedShares by remember { mutableStateOf(initialShares.getOrDefault(emptyList())) } + var showConnectionForm by remember { mutableStateOf(savedShares.isEmpty()) } + var selectedId by remember { mutableStateOf(null) } + var pendingDelete by remember { mutableStateOf(null) } + var browsing by remember { mutableStateOf(null) } + var host by remember { mutableStateOf("") } + var share by remember { mutableStateOf("") } + var port by remember { mutableStateOf("445") } + var username by remember { mutableStateOf("") } + var password by remember { mutableStateOf("") } + var domain by remember { mutableStateOf("") } + var folder by remember { mutableStateOf("") } + var sample by remember { mutableStateOf("") } + var status by remember { mutableStateOf(initialShares.exceptionOrNull()?.let { "Could not read saved shares: ${it.javaClass.simpleName}" } ?: "Enter a share and run the compatibility probe.") } + var entries by remember { mutableStateOf(emptyList()) } + var running by remember { mutableStateOf(false) } + val scope = rememberCoroutineScope() + val valid = host.isNotBlank() && share.isNotBlank() && (port.toIntOrNull()?.let { it in 1..65535 } == true) + + fun loadConnection(item: SavedShare) { + selectedId = item.id + host = item.target.host + share = item.target.share + port = item.target.port.toString() + username = item.target.username + password = item.target.password + domain = item.target.domain + folder = item.folder + sample = "" + entries = emptyList() + status = "Loaded ${item.target.host}/${item.target.share}." + } + + fun newConnection() { + selectedId = null + host = ""; share = ""; port = "445"; username = ""; password = ""; domain = ""; folder = ""; sample = "" + entries = emptyList() + status = "Enter a new share." + showConnectionForm = true + } + + fun runProbe(saveOnSuccess: Boolean) { + val target = SmbTarget(host.trim(), share.trim(), port.toInt(), username, password, domain.trim()) + val requestedFolder = folder + val requestedSample = if (saveOnSuccess) null else sample.takeIf(String::isNotBlank) + running = true + status = "Connecting…" + entries = emptyList() + scope.launch { + try { + val result = withContext(Dispatchers.IO) { + SmbProbe().use { it.run(target, requestedFolder, requestedSample) } + } + if (saveOnSuccess) { + val saved = withContext(Dispatchers.IO) { store.save(target, requestedFolder, selectedId) } + selectedId = saved.id + savedShares = withContext(Dispatchers.IO) { store.load() } + showConnectionForm = false + browsing = saved + } + entries = result.entries + status = (if (saveOnSuccess) "Share tested and saved. " else "") + + "${result.entries.size} entries in ${result.listingMs} ms. " + + result.ranges.joinToString("; ") { "offset ${it.offset}: ${it.bytesRead} bytes, SHA-256 ${it.sha256}" } + } catch (e: Exception) { + status = "${if (saveOnSuccess) "Test or save" else "Probe"} failed: ${e.javaClass.simpleName}: ${e.message ?: "No details"}" + } finally { + running = false + } + } + } + + browsing?.let { saved -> + BrowseScreen(saved, onConnections = { browsing = null; showConnectionForm = false }) + return + } + + pendingDelete?.let { item -> + AlertDialog( + onDismissRequest = { pendingDelete = null }, + title = { Text("Remove saved share?") }, + text = { Text("${item.target.host}/${item.target.share} will be removed from this device.") }, + confirmButton = { Button(onClick = { + try { + store.delete(item.id) + savedShares = store.load() + if (selectedId == item.id) selectedId = null + if (savedShares.isEmpty()) showConnectionForm = true + status = "Saved share removed." + } catch (e: Exception) { + status = "Could not remove share: ${e.javaClass.simpleName}" + } + pendingDelete = null + }) { Text("Remove") } }, + dismissButton = { Button(onClick = { pendingDelete = null }) { Text("Cancel") } }, + ) + } + + LazyColumn(Modifier.fillMaxSize().padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + item { Text("SMB Explorer", style = MaterialTheme.typography.headlineMedium) } + item { Text("Your shares", style = MaterialTheme.typography.titleLarge) } + if (savedShares.isEmpty()) item { Text("No shares saved yet.") } + items(savedShares, key = { "saved:${it.id}" }) { item -> + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Button(onClick = { + loadConnection(item) + browsing = item + }, modifier = Modifier.weight(1f)) { Text("${item.target.host}/${item.target.share}") } + TextButton(onClick = { loadConnection(item); showConnectionForm = true }) { Text("Edit") } + TextButton(onClick = { pendingDelete = item }) { Text("Remove") } + } + } + if (!showConnectionForm) item { OutlinedButton(onClick = { newConnection() }) { Text("Add share") } } + if (showConnectionForm) { + item { Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + Text(if (selectedId == null) "Add share" else "Edit share", style = MaterialTheme.typography.titleLarge) + if (savedShares.isNotEmpty()) TextButton(onClick = { showConnectionForm = false }) { Text("Cancel") } + } } + item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(host, { host = it }, label = { Text("Host or IP") }, modifier = Modifier.weight(1f)) + OutlinedTextField(port, { port = it }, label = { Text("Port") }, modifier = Modifier.weight(.4f)) + } } + item { OutlinedTextField(share, { share = it }, label = { Text("Share") }, modifier = Modifier.fillMaxWidth()) } + item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedTextField(username, { username = it }, label = { Text("Username") }, modifier = Modifier.weight(1f)) + OutlinedTextField(domain, { domain = it }, label = { Text("Domain (optional)") }, modifier = Modifier.weight(1f)) + } } + item { OutlinedTextField(password, { password = it }, label = { Text("Password") }, visualTransformation = PasswordVisualTransformation(), modifier = Modifier.fillMaxWidth()) } + item { OutlinedTextField(folder, { folder = it }, label = { Text("Folder path (optional)") }, modifier = Modifier.fillMaxWidth()) } + item { OutlinedTextField(sample, { sample = it }, label = { Text("Large file path for range reads (optional)") }, modifier = Modifier.fillMaxWidth()) } + item { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Button(enabled = !running && valid, onClick = { runProbe(true) }) { Text(if (running) "Running…" else "Test & save") } + Button(enabled = !running && valid, onClick = { runProbe(false) }) { Text("Run probe") } + } } + item { Text(status) } + items(entries, key = { "entry:${it.name}" }) { entry -> + Text("${if (entry.directory) "📁" else "📄"} ${entry.name} ${if (entry.directory) "" else "(${entry.size} B)"}") + } + } + } +} diff --git a/app/src/main/java/dev/alvin/smbexplorer/SavedShareStore.kt b/app/src/main/java/dev/alvin/smbexplorer/SavedShareStore.kt new file mode 100644 index 0000000..460c0f1 --- /dev/null +++ b/app/src/main/java/dev/alvin/smbexplorer/SavedShareStore.kt @@ -0,0 +1,84 @@ +package dev.alvin.smbexplorer + +import android.content.Context +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import org.json.JSONArray +import org.json.JSONObject +import java.security.KeyStore +import java.util.UUID +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +data class SavedShare(val id: String, val target: SmbTarget, val folder: String) + +/** Encrypts the complete connection list with a non-exportable Android Keystore key. */ +class SavedShareStore(context: Context) { + private val preferences = context.getSharedPreferences("saved_shares", Context.MODE_PRIVATE) + private val alias = "smb_explorer_saved_shares_v1" + + fun load(): List { + val encoded = preferences.getString("connections", null) ?: return emptyList() + val payload = Base64.decode(encoded, Base64.NO_WRAP) + require(payload.size > 12) { "Saved shares are damaged" } + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(128, payload.copyOfRange(0, 12))) + val array = JSONArray(String(cipher.doFinal(payload.copyOfRange(12, payload.size)), Charsets.UTF_8)) + return (0 until array.length()).map { index -> + val item = array.getJSONObject(index) + SavedShare( + item.getString("id"), + SmbTarget( + item.getString("host"), item.getString("share"), item.getInt("port"), + item.getString("username"), item.getString("password"), item.getString("domain"), + ), + item.optString("folder"), + ) + } + } + + fun save(target: SmbTarget, folder: String, existingId: String? = null): SavedShare { + val item = SavedShare(existingId ?: UUID.randomUUID().toString(), target, folder) + write(load().filterNot { it.id == item.id } + item) + return item + } + + fun delete(id: String) = write(load().filterNot { it.id == id }) + + private fun write(items: List) { + val array = JSONArray() + items.forEach { item -> + array.put(JSONObject().apply { + put("id", item.id) + put("host", item.target.host) + put("share", item.target.share) + put("port", item.target.port) + put("username", item.target.username) + put("password", item.target.password) + put("domain", item.target.domain) + put("folder", item.folder) + }) + } + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, key()) + val payload = cipher.iv + cipher.doFinal(array.toString().toByteArray(Charsets.UTF_8)) + check(preferences.edit().putString("connections", Base64.encodeToString(payload, Base64.NO_WRAP)).commit()) { + "Could not save shares" + } + } + + private fun key(): SecretKey { + val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (keyStore.getKey(alias, null) as? SecretKey)?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init(KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build()) + }.generateKey() + } +} diff --git a/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt b/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt new file mode 100644 index 0000000..618b0bd --- /dev/null +++ b/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt @@ -0,0 +1,108 @@ +package dev.alvin.smbexplorer + +import com.hierynomus.msfscc.fileinformation.FileIdBothDirectoryInformation +import com.hierynomus.msdtyp.AccessMask +import com.hierynomus.smbj.SMBClient +import com.hierynomus.smbj.auth.AuthenticationContext +import com.hierynomus.smbj.share.DiskShare +import com.hierynomus.smbj.share.Share +import com.hierynomus.smbj.share.File +import com.hierynomus.mssmb2.SMB2ShareAccess +import com.hierynomus.msfscc.FileAttributes +import com.hierynomus.mssmb2.SMB2CreateDisposition +import com.hierynomus.mssmb2.SMB2CreateOptions +import java.io.Closeable +import java.security.MessageDigest +import java.util.EnumSet + +data class SmbTarget( + val host: String, + val share: String, + val port: Int, + val username: String, + val password: String, + val domain: String, +) + +data class RemoteEntry(val name: String, val directory: Boolean, val size: Long, val modifiedAt: Long) +data class RangeResult(val offset: Long, val bytesRead: Int, val sha256: String) +data class ProbeResult(val entries: List, val listingMs: Long, val ranges: List) + +/** A short lived compatibility probe. Nothing is persisted and all handles close on failure. */ +class SmbProbe : Closeable { + private val client = SMBClient() + + fun run(target: SmbTarget, folder: String, sampleFile: String?): ProbeResult { + require(target.host.isNotBlank() && target.share.isNotBlank()) + require(target.port in 1..65535) + val normalizedFolder = normalize(folder) + val connection = client.connect(target.host.trim(), target.port) + try { + val auth = AuthenticationContext( + target.username, + target.password.toCharArray(), + target.domain, + ) + val session = connection.authenticate(auth) + try { + val share: Share = session.connectShare(target.share.trim()) + try { + require(share is DiskShare) { "The selected share is not a disk share" } + val start = System.nanoTime() + val entries = share.list(normalizedFolder) + .filter { it.fileName != "." && it.fileName != ".." } + .map { it.toEntry() } + val listingMs = (System.nanoTime() - start) / 1_000_000 + val ranges = sampleFile?.takeIf { it.isNotBlank() }?.let { + readRanges(share, normalize(it)) + } ?: emptyList() + return ProbeResult(entries, listingMs, ranges) + } finally { + share.close() + } + } finally { + session.close() + } + } finally { + connection.close() + } + } + + private fun readRanges(share: DiskShare, path: String): List { + val file: File = share.openFile( + path, + EnumSet.of(AccessMask.GENERIC_READ), + EnumSet.noneOf(FileAttributes::class.java), + EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ), + SMB2CreateDisposition.FILE_OPEN, + EnumSet.noneOf(SMB2CreateOptions::class.java), + ) + try { + val length = file.length + val offsets = listOf(0L, (length / 2).coerceAtLeast(0), (length - 65536).coerceAtLeast(0)).distinct() + return offsets.map { offset -> + val buffer = ByteArray(65536) + val count = file.read(buffer, offset).coerceAtLeast(0) + val digest = MessageDigest.getInstance("SHA-256").digest(buffer.copyOf(count)) + RangeResult(offset, count, digest.joinToString("") { "%02x".format(it) }) + } + } finally { + file.close() + } + } + + override fun close() = client.close() +} + +private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry( + fileName, + fileAttributes.toInt() and 0x10 != 0, + endOfFile, + lastWriteTime.toEpochMillis(), +) + +private fun normalize(path: String): String { + val parts = path.replace('/', '\\').split('\\').filter { it.isNotEmpty() && it != "." } + require(parts.none { it == ".." }) { "Parent path segments are not allowed" } + return parts.joinToString("\\") +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..24b0c0c --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "9.4.0" apply false + id("org.jetbrains.kotlin.plugin.compose") version "2.2.20" apply false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..459e0db --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..b1b8ef5 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..eb84db6 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,9 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..249efbb --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# gradlew start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh gradlew +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..a51ec4f --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,82 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem gradlew startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..abe645d --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,9 @@ +pluginManagement { + repositories { google(); mavenCentral(); gradlePluginPortal() } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { google(); mavenCentral() } +} +rootProject.name = "SmbExplorer" +include(":app")