diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 30fe98e1..fe2cb585 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -2,6 +2,7 @@ + diff --git a/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt b/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt new file mode 100644 index 00000000..979d84f3 --- /dev/null +++ b/app/src/main/kotlin/com/subtracks/data/net/LocalNetworkAccess.kt @@ -0,0 +1,60 @@ +package com.subtracks.data.net + +import android.content.Context +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.LinkAddress +import android.os.Build +import androidx.core.content.ContextCompat +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.net.InetAddress + +internal const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK" + +private const val LOCAL_NETWORK_PERMISSION_SDK = 37 + +class LocalNetworkAccess( + private val context: Context, +) { + suspend fun requiresPermission(address: String): Boolean { + if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK || granted()) return false + val host = serverHost(address) ?: return false + val linkAddresses = currentLinkAddresses() + if (linkAddresses.isEmpty()) return false + return withContext(Dispatchers.IO) { + val resolved = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList()) + resolved.any { candidate -> + linkAddresses.any { candidate.isWithinPrefix(it.address, it.prefixLength) } + } + } + } + + private fun granted(): Boolean = + ContextCompat.checkSelfPermission(context, LOCAL_NETWORK_PERMISSION) == PackageManager.PERMISSION_GRANTED + + private fun currentLinkAddresses(): List { + val manager = context.getSystemService(ConnectivityManager::class.java) ?: return emptyList() + val network = manager.activeNetwork ?: return emptyList() + return manager.getLinkProperties(network)?.linkAddresses.orEmpty() + } +} + +internal fun InetAddress.isWithinPrefix( + prefix: InetAddress, + prefixLength: Int, +): Boolean { + val own = address + val network = prefix.address + if (own.size != network.size || prefixLength !in 0..(own.size * 8)) return false + + val wholeBytes = prefixLength / 8 + for (index in 0 until wholeBytes) { + if (own[index] != network[index]) return false + } + + val remainingBits = prefixLength % 8 + if (remainingBits == 0) return true + val mask = (0xFF shl (8 - remainingBits)) and 0xFF + return (own[wholeBytes].toInt() and mask) == (network[wholeBytes].toInt() and mask) +} diff --git a/app/src/main/kotlin/com/subtracks/data/net/ServerAddress.kt b/app/src/main/kotlin/com/subtracks/data/net/ServerAddress.kt new file mode 100644 index 00000000..bbbb1371 --- /dev/null +++ b/app/src/main/kotlin/com/subtracks/data/net/ServerAddress.kt @@ -0,0 +1,16 @@ +package com.subtracks.data.net + +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull + +internal fun normalizeServerAddress(address: String): String { + val trimmed = address.trim() + val withScheme = + if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) { + trimmed + } else { + "http://$trimmed" + } + return withScheme.trimEnd('/') + "/" +} + +internal fun serverHost(address: String): String? = normalizeServerAddress(address).toHttpUrlOrNull()?.host diff --git a/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt b/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt index 92ad0d4c..c34cb274 100644 --- a/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt +++ b/app/src/main/kotlin/com/subtracks/data/repo/SourceRepository.kt @@ -12,6 +12,7 @@ import com.subtracks.data.model.SubsonicSource import com.subtracks.data.model.artistImageKey import com.subtracks.data.model.coverArtKey import com.subtracks.data.net.NetworkMode +import com.subtracks.data.net.normalizeServerAddress import com.subtracks.data.prefs.StreamQuality import com.subtracks.data.prefs.UserPreferences import com.subtracks.data.source.MusicSource @@ -209,7 +210,7 @@ class SourceRepository( dao.insertSource( Source( name = name.trim(), - address = normalizeAddress(address), + address = normalizeServerAddress(address), isActive = false, createdAt = System.currentTimeMillis(), ), @@ -238,7 +239,7 @@ class SourceRepository( ) { val dao = db.sourcesDao() if (dao.sourceOnce(id) == null) return - dao.updateSourceDetails(id, name.trim(), normalizeAddress(address)) + dao.updateSourceDetails(id, name.trim(), normalizeServerAddress(address)) dao.upsertSubsonicSource( SubsonicSource( sourceId = id, @@ -322,22 +323,11 @@ class SourceRepository( useTokenAuth: Boolean, onTokenAuthUnsupported: () -> Unit = {}, ) = SubsonicClient( - baseUrl = normalizeAddress(address).toHttpUrl(), + baseUrl = normalizeServerAddress(address).toHttpUrl(), username = username, password = password, useTokenAuth = useTokenAuth, http = http, onTokenAuthUnsupported = onTokenAuthUnsupported, ) - - private fun normalizeAddress(address: String): String { - val trimmed = address.trim() - val withScheme = - if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) { - trimmed - } else { - "http://$trimmed" - } - return withScheme.trimEnd('/') + "/" - } } diff --git a/app/src/main/kotlin/com/subtracks/di/AppModule.kt b/app/src/main/kotlin/com/subtracks/di/AppModule.kt index 8916de63..e8af5ef2 100644 --- a/app/src/main/kotlin/com/subtracks/di/AppModule.kt +++ b/app/src/main/kotlin/com/subtracks/di/AppModule.kt @@ -14,6 +14,7 @@ import com.subtracks.data.download.DownloadEngine import com.subtracks.data.download.DownloadNotifier import com.subtracks.data.download.OkHttpArtworkFetcher import com.subtracks.data.download.SystemDownloadEngine +import com.subtracks.data.net.LocalNetworkAccess import com.subtracks.data.net.networkAvailable import com.subtracks.data.net.networkMode import com.subtracks.data.prefs.UserPreferences @@ -70,6 +71,7 @@ fun appModule( single { createAndroidDatabase(context) } single { http } single { createUserPreferences(context) } + single { LocalNetworkAccess(context.applicationContext) } single { CoroutineScope(SupervisorJob() + Dispatchers.Default) } single(named("io")) { CoroutineScope(SupervisorJob() + Dispatchers.IO) } single(named("playback")) { CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) } diff --git a/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt b/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt index 8270dfe7..3af23158 100644 --- a/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt +++ b/app/src/main/kotlin/com/subtracks/ui/AppRoot.kt @@ -76,6 +76,7 @@ import com.subtracks.ui.components.LoadingState import com.subtracks.ui.components.MenuTarget import com.subtracks.ui.components.PlaylistInfoDialog import com.subtracks.ui.components.SongInfoDialog +import com.subtracks.ui.components.rememberLocalNetworkGate import com.subtracks.ui.components.statusBarScrim import com.subtracks.ui.downloads.DownloadsRoute import com.subtracks.ui.home.HomeListRequest @@ -111,6 +112,12 @@ class RootViewModel( .activeSourceId() .map { it != null } .stateIn(viewModelScope, SharingStarted.Eagerly, null) + + val serverAddress = + sourceRepository + .activeConfig() + .map { it?.address } + .stateIn(viewModelScope, SharingStarted.Eagerly, null) } private const val NAVIGATION_DURATION_MS = 260 @@ -193,6 +200,11 @@ internal fun focusPops( @Composable fun SubtracksRoot(root: RootViewModel = koinViewModel()) { + val localNetworkGate = rememberLocalNetworkGate() + val serverAddress by root.serverAddress.collectAsStateWithLifecycle() + LaunchedEffect(serverAddress) { + localNetworkGate.run(address = serverAddress, onGranted = {}) + } when (val hasSource = root.hasSource.collectAsStateWithLifecycle().value) { null -> { LoadingState() diff --git a/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt b/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt new file mode 100644 index 00000000..ad0f4013 --- /dev/null +++ b/app/src/main/kotlin/com/subtracks/ui/components/LocalNetworkGate.kt @@ -0,0 +1,104 @@ +package com.subtracks.ui.components + +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.AlertDialog +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.res.stringResource +import com.subtracks.R +import com.subtracks.data.net.LOCAL_NETWORK_PERMISSION +import com.subtracks.data.net.LocalNetworkAccess +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import org.koin.compose.koinInject + +class LocalNetworkGate internal constructor( + private val scope: CoroutineScope, + private val checker: LocalNetworkAccess, + private val requestPermission: (onGranted: () -> Unit, onDenied: () -> Unit) -> Unit, +) { + fun run( + address: String?, + onGranted: () -> Unit, + onDenied: () -> Unit = {}, + ) { + if (address == null) { + onGranted() + return + } + scope.launch { + if (checker.requiresPermission(address)) { + requestPermission(onGranted, onDenied) + } else { + onGranted() + } + } + } +} + +private class PendingRequest( + val onGranted: () -> Unit, + val onDenied: () -> Unit, +) + +@Composable +fun rememberLocalNetworkGate(): LocalNetworkGate { + val checker = koinInject() + val scope = rememberCoroutineScope() + var pending by remember { mutableStateOf(null) } + var awaitingSystemPrompt by remember { mutableStateOf(false) } + val launcher = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + val request = pending + pending = null + awaitingSystemPrompt = false + if (request != null) { + if (granted) request.onGranted() else request.onDenied() + } + } + + val gate = + LocalNetworkGate(scope, checker) { onGranted, onDenied -> + pending = PendingRequest(onGranted, onDenied) + } + + val request = pending + if (request != null && !awaitingSystemPrompt) { + AlertDialog( + onDismissRequest = { + pending = null + request.onDenied() + }, + title = { Text(stringResource(R.string.local_network_permission_title)) }, + text = { Text(stringResource(R.string.local_network_permission_body)) }, + confirmButton = { + TextButton( + onClick = { + awaitingSystemPrompt = true + launcher.launch(LOCAL_NETWORK_PERMISSION) + }, + ) { + Text(stringResource(R.string.local_network_permission_continue)) + } + }, + dismissButton = { + TextButton( + onClick = { + pending = null + request.onDenied() + }, + ) { + Text(stringResource(R.string.actions_cancel)) + } + }, + ) + } + return gate +} diff --git a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt index 324ff67b..1894d7bd 100644 --- a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt +++ b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceScreen.kt @@ -48,6 +48,7 @@ import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.subtracks.R import com.subtracks.ui.components.DismissOnRequest +import com.subtracks.ui.components.rememberLocalNetworkGate import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import org.koin.compose.viewmodel.koinViewModel @@ -62,6 +63,7 @@ fun AddSourceRoute( viewModel: AddSourceViewModel = koinViewModel(key = sourceId?.toString() ?: "new") { parametersOf(sourceId) }, ) { val state by viewModel.state.collectAsStateWithLifecycle() + val localNetworkGate = rememberLocalNetworkGate() AddSourceScreen( state = state, onNameChange = viewModel::setName, @@ -69,8 +71,20 @@ fun AddSourceRoute( onUsernameChange = viewModel::setUsername, onPasswordChange = viewModel::setPassword, onTokenAuthChange = viewModel::setTokenAuth, - onTest = viewModel::testConnection, - onSave = { viewModel.save(onSaved) }, + onTest = { + localNetworkGate.run( + address = state.address, + onGranted = viewModel::testConnection, + onDenied = viewModel::localNetworkPermissionDenied, + ) + }, + onSave = { + localNetworkGate.run( + address = state.address, + onGranted = { viewModel.save(onSaved) }, + onDenied = { viewModel.save(onSaved) }, + ) + }, onDelete = { viewModel.delete(onSaved) }, onBack = onBack, dismissals = dismissals, diff --git a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt index 864f6d74..4add31cc 100644 --- a/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt +++ b/app/src/main/kotlin/com/subtracks/ui/settings/AddSourceViewModel.kt @@ -112,6 +112,12 @@ class AddSourceViewModel( } } + fun localNetworkPermissionDenied() { + _state.update { + it.copy(message = resources.getString(R.string.local_network_permission_denied), isError = true) + } + } + fun save(onSaved: () -> Unit) { val validated = _state.value.validated() if (validated.nameError || validated.addressError) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index fc41ab04..e30146ec 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -289,6 +289,10 @@ %1$s and its downloaded songs will be removed from this device. Connection OK Server does not support token auth; using the password instead + Allow local network access + Android blocks apps from reaching devices on your local network until you allow it. Your server is on this network, so Subtracks needs the Nearby devices permission to sync and play. Allow it on the next prompt. + Continue + Local network access is blocked. Allow Nearby devices for Subtracks in Android settings to reach this server. Failed: %1$s Could not save: %1$s The active server can\'t be deleted; switch to another server first diff --git a/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt b/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt new file mode 100644 index 00000000..fe82c5ce --- /dev/null +++ b/app/src/test/kotlin/com/subtracks/data/net/LocalNetworkAccessTest.kt @@ -0,0 +1,57 @@ +package com.subtracks.data.net + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import java.net.InetAddress + +class LocalNetworkAccessTest { + @Test + fun matchesAnAddressInsideASlash24Network() { + assertTrue(address("192.168.1.122").isWithinPrefix(address("192.168.1.243"), 24)) + } + + @Test + fun rejectsAnAddressOutsideASlash24Network() { + assertFalse(address("10.224.202.10").isWithinPrefix(address("192.168.22.11"), 24)) + } + + @Test + fun matchesAnAddressInsideASlash8Network() { + assertTrue(address("10.224.202.10").isWithinPrefix(address("10.0.0.1"), 8)) + } + + @Test + fun masksThePartialByteOfANonOctetPrefix() { + assertTrue(address("192.168.1.200").isWithinPrefix(address("192.168.1.130"), 25)) + assertFalse(address("192.168.1.100").isWithinPrefix(address("192.168.1.130"), 25)) + } + + @Test + fun doesNotMatchAcrossAddressFamilies() { + assertFalse(address("::1").isWithinPrefix(address("10.0.0.1"), 8)) + assertFalse(address("10.0.0.1").isWithinPrefix(address("fd00::1"), 64)) + } + + @Test + fun matchesAnIpv6Prefix() { + assertTrue(address("fd00:1234:5678:9abc::5").isWithinPrefix(address("fd00:1234:5678:9abc::1"), 64)) + assertFalse(address("fd00:1234:5678:9abd::5").isWithinPrefix(address("fd00:1234:5678:9abc::1"), 64)) + } + + @Test + fun matchesAHostRoute() { + assertTrue(address("10.0.0.5").isWithinPrefix(address("10.0.0.5"), 32)) + assertFalse(address("10.0.0.6").isWithinPrefix(address("10.0.0.5"), 32)) + } + + @Test + fun extractsTheHostFromAServerAddress() { + assertEquals("navidrome.example.com", serverHost("https://navidrome.example.com/music/")) + assertEquals("navidrome.example.com", serverHost("navidrome.example.com:4533")) + assertEquals("10.224.202.10", serverHost("http://10.224.202.10")) + } + + private fun address(value: String): InetAddress = InetAddress.getByName(value) +}