mirror of
https://github.com/austinried/subtracks.git
synced 2026-11-16 01:00:17 +01:00
net: request local network access for on-link servers
Android 17 blocks apps targeting API 37 from reaching directly connected addresses without ACCESS_LOCAL_NETWORK, and a blocked TCP connect is indistinguishable from a dead server. Resolve the configured host, check it against the active network's link addresses, and ask for the permission only when the server is actually on-link, so routed RFC1918 and VPN destinations do not trigger a prompt.
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
@@ -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<LinkAddress> {
|
||||
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)
|
||||
}
|
||||
@@ -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
|
||||
@@ -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('/') + "/"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) }
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<LocalNetworkAccess>()
|
||||
val scope = rememberCoroutineScope()
|
||||
var pending by remember { mutableStateOf<PendingRequest?>(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
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -289,6 +289,10 @@
|
||||
<string name="delete_server_body">%1$s and its downloaded songs will be removed from this device.</string>
|
||||
<string name="connection_ok">Connection OK</string>
|
||||
<string name="connection_token_fallback">Server does not support token auth; using the password instead</string>
|
||||
<string name="local_network_permission_title">Allow local network access</string>
|
||||
<string name="local_network_permission_body">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.</string>
|
||||
<string name="local_network_permission_continue">Continue</string>
|
||||
<string name="local_network_permission_denied">Local network access is blocked. Allow Nearby devices for Subtracks in Android settings to reach this server.</string>
|
||||
<string name="connection_failed">Failed: %1$s</string>
|
||||
<string name="save_failed">Could not save: %1$s</string>
|
||||
<string name="active_server_delete_error">The active server can\'t be deleted; switch to another server first</string>
|
||||
|
||||
Reference in New Issue
Block a user