net: classify VPN routes and scope sync retries to the prompted source

Read link addresses after resolution so a network change during DNS
cannot authorize the wrong interface, require the persisted offline
state before the form acts, skip on-link prompting for destinations the
active VPN routes, and retry a raced sync only for the source the prompt
belongs to.
This commit is contained in:
austinried
2026-11-14 12:08:14 +00:00
parent f73bee3a9a
commit 94093d5e91
4 changed files with 59 additions and 11 deletions
@@ -26,14 +26,31 @@ class LocalNetworkAccess(
if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK) return false if (Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_SDK) return false
if (granted()) return false if (granted()) return false
val host = serverHost(address) ?: return false val host = serverHost(address) ?: return false
val linkAddresses = currentLinkAddresses()
if (linkAddresses.isEmpty()) return false
if (isLocalHostname(host)) return true
return withContext(Dispatchers.IO) { return withContext(Dispatchers.IO) {
val linkAddresses = currentLinkAddresses()
if (linkAddresses.isEmpty()) return@withContext false
if (isLocalHostname(host)) return@withContext true
val resolved = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList()) val resolved = runCatching { InetAddress.getAllByName(host).toList() }.getOrDefault(emptyList())
resolved.any { candidate -> linkAddresses.any { it.contains(candidate) } } if (resolved.isEmpty()) return@withContext false
val current = currentLinkAddresses()
resolved.any { candidate ->
!routedThroughVpn(candidate) && current.any { it.contains(candidate) }
} }
} }
}
@RequiresApi(LOCAL_NETWORK_PERMISSION_SDK)
private fun routedThroughVpn(address: InetAddress): Boolean {
val manager = context.getSystemService(ConnectivityManager::class.java) ?: return false
val network = manager.activeNetwork ?: return false
val capabilities = manager.getNetworkCapabilities(network) ?: return false
if (!capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return false
return manager
.getLinkProperties(network)
?.routes
.orEmpty()
.any { route -> route.destination.contains(address) }
}
@Synchronized @Synchronized
fun markDenied(address: String) { fun markDenied(address: String) {
@@ -48,6 +48,12 @@ class SyncManager(
private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle) private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle)
val status: StateFlow<SyncStatus> = _status val status: StateFlow<SyncStatus> = _status
private val _runningSource = MutableStateFlow<Long?>(null)
val runningSource: StateFlow<Long?> = _runningSource
private val _failedSource = MutableStateFlow<Long?>(null)
val failedSource: StateFlow<Long?> = _failedSource
init { init {
scope.launch { scope.launch {
for (silent in requests) { for (silent in requests) {
@@ -82,9 +88,11 @@ class SyncManager(
runCatching { preferences.setLastSyncAt(System.currentTimeMillis()) } runCatching { preferences.setLastSyncAt(System.currentTimeMillis()) }
.onFailure { Log.w("sync", "could not record the sync attempt", it) } .onFailure { Log.w("sync", "could not record the sync attempt", it) }
val startedAt = System.nanoTime() val startedAt = System.nanoTime()
val source = sourceRepository.activeMusicSource()
_runningSource.value = source?.id
val result = val result =
try { try {
val source = sourceRepository.activeMusicSource() ?: throw NoServerException() if (source == null) throw NoServerException()
Log.i("sync", "started (source ${source.id})") Log.i("sync", "started (source ${source.id})")
serverActions.flush() serverActions.flush()
val resetPoint = queueRepository.captureResetPoint() val resetPoint = queueRepository.captureResetPoint()
@@ -99,6 +107,7 @@ class SyncManager(
"${completed.playlists} playlists, ${completed.playlistSongs} playlist tracks, ${completed.pruned} pruned", "${completed.playlists} playlists, ${completed.playlistSongs} playlist tracks, ${completed.pruned} pruned",
) )
queueRepository.resetChangedOriginsAndClearPendingOrigins(changedOrigins, resetPoint, source.id) queueRepository.resetChangedOriginsAndClearPendingOrigins(changedOrigins, resetPoint, source.id)
_failedSource.value = null
SyncStatus.Success SyncStatus.Success
} catch (cancellation: CancellationException) { } catch (cancellation: CancellationException) {
throw cancellation throw cancellation
@@ -116,7 +125,10 @@ class SyncManager(
} }
} }
if (!silent) showMessage(message) if (!silent) showMessage(message)
_failedSource.value = source?.id
SyncStatus.Failed(message) SyncStatus.Failed(message)
} finally {
_runningSource.value = null
} }
_status.value = result _status.value = result
} }
@@ -122,6 +122,11 @@ class RootViewModel(
.map { it?.address } .map { it?.address }
.stateIn(viewModelScope, SharingStarted.Eagerly, null) .stateIn(viewModelScope, SharingStarted.Eagerly, null)
val activeSourceId =
sourceRepository
.activeSourceId()
.stateIn(viewModelScope, SharingStarted.Eagerly, null)
val offline = sourceRepository.offline val offline = sourceRepository.offline
val offlineLoaded = sourceRepository.offlineLoaded val offlineLoaded = sourceRepository.offlineLoaded
@@ -210,23 +215,37 @@ fun SubtracksRoot(root: RootViewModel = koinViewModel()) {
val localNetworkGate = rememberLocalNetworkGate() val localNetworkGate = rememberLocalNetworkGate()
val syncManager = koinInject<SyncManager>() val syncManager = koinInject<SyncManager>()
val serverAddress by root.serverAddress.collectAsStateWithLifecycle() val serverAddress by root.serverAddress.collectAsStateWithLifecycle()
val activeSourceId by root.activeSourceId.collectAsStateWithLifecycle()
val offline by root.offline.collectAsStateWithLifecycle() val offline by root.offline.collectAsStateWithLifecycle()
val offlineLoaded by root.offlineLoaded.collectAsStateWithLifecycle() val offlineLoaded by root.offlineLoaded.collectAsStateWithLifecycle()
val networkRevision = rememberNetworkRevision() val networkRevision = rememberNetworkRevision()
LaunchedEffect(serverAddress, networkRevision, offline, offlineLoaded) { LaunchedEffect(serverAddress, activeSourceId, networkRevision, offline, offlineLoaded) {
if (!offlineLoaded) return@LaunchedEffect if (!offlineLoaded) return@LaunchedEffect
if (offline) { if (offline) {
localNetworkGate.cancel() localNetworkGate.cancel()
return@LaunchedEffect return@LaunchedEffect
} }
val promptedSourceId = activeSourceId
val statusBeforePrompt = syncManager.status.value val statusBeforePrompt = syncManager.status.value
localNetworkGate.run( localNetworkGate.run(
address = serverAddress, address = serverAddress,
onGranted = { onGranted = {
val status = syncManager.status.value val status = syncManager.status.value
val raced = val raced =
status is SyncStatus.Running || when (status) {
(status is SyncStatus.Failed && statusBeforePrompt !is SyncStatus.Failed) is SyncStatus.Running -> {
syncManager.runningSource.value == promptedSourceId
}
is SyncStatus.Failed -> {
statusBeforePrompt !is SyncStatus.Failed &&
syncManager.failedSource.value == promptedSourceId
}
else -> {
false
}
}
if (raced) syncManager.requestSync() if (raced) syncManager.requestSync()
}, },
onNotNeeded = {}, onNotNeeded = {},
@@ -72,7 +72,7 @@ fun AddSourceRoute(
onGranted: () -> Unit, onGranted: () -> Unit,
onDenied: () -> Unit = onGranted, onDenied: () -> Unit = onGranted,
) { ) {
if (gatedBusy) return if (!offlineLoaded || gatedBusy) return
gatedBusy = true gatedBusy = true
val address = state.address val address = state.address
@@ -81,7 +81,7 @@ fun AddSourceRoute(
if (viewModel.state.value.address == address) action() if (viewModel.state.value.address == address) action()
} }
if (!offlineLoaded || offline) { if (offline) {
finish(onGranted) finish(onGranted)
} else { } else {
localNetworkGate.run( localNetworkGate.run(
@@ -92,7 +92,7 @@ fun AddSourceRoute(
} }
} }
AddSourceScreen( AddSourceScreen(
state = if (gatedBusy) state.copy(busy = true) else state, state = if (gatedBusy || !offlineLoaded) state.copy(busy = true) else state,
onNameChange = viewModel::setName, onNameChange = viewModel::setName,
onAddressChange = viewModel::setAddress, onAddressChange = viewModel::setAddress,
onUsernameChange = viewModel::setUsername, onUsernameChange = viewModel::setUsername,