From ad0205b0e1d82a3026f2fdfbf94836629ff7e59e Mon Sep 17 00:00:00 2001 From: denis0001-dev Date: Tue, 17 Nov 2026 12:45:23 +0300 Subject: [PATCH] SSH proxy fix Signed-off-by: denis0001-dev --- .../ru/fromchat/incognito/IncognitoMode.kt | 6 + .../ru/fromchat/network/proxy/ProxyRuntime.kt | 126 ++++++++++-------- .../ru/fromchat/network/proxy/ProxyStore.kt | 92 ++++++++++--- .../kotlin/ru/fromchat/ui/auth/AuthLayout.kt | 30 ++++- .../kotlin/ru/fromchat/ui/auth/AuthScreen.kt | 7 + .../ru/fromchat/ui/auth/UsernameStep.kt | 14 +- .../ui/components/ConnectingEllipsis.kt | 2 +- .../ui/main/settings/proxy/AddProxyScreen.kt | 6 + .../network/proxy/JvmTlsStreamHttp.jvm.kt | 61 +++++---- 9 files changed, 238 insertions(+), 106 deletions(-) diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/incognito/IncognitoMode.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/incognito/IncognitoMode.kt index 189938c..4d771d0 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/incognito/IncognitoMode.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/incognito/IncognitoMode.kt @@ -1,10 +1,12 @@ package ru.fromchat.incognito import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import ru.fromchat.api.local.db.store.closeMessageDatabaseForIncognitoSession import ru.fromchat.config.ServerConfig import ru.fromchat.network.proxy.ProxyRuntime +import ru.fromchat.network.proxy.ProxyStore import ru.fromchat.logging.AppLogStore import ru.fromchat.logging.FromChatLogDirs import ru.fromchat.logging.Logger @@ -36,6 +38,7 @@ object IncognitoMode { IncognitoContainer.open(key, root) registerIncognitoLifecycleHooks() seedIncognitoSettingsFromNormalProfile() + ProxyStore.beginIncognitoProxySession(ProxyRuntime.selection.value) purgePlaintextLogsUnderAppData() AppLogStore.onIncognitoSessionBoundary() closeMessageDatabaseForIncognitoSession() @@ -65,6 +68,9 @@ object IncognitoMode { volumeKey?.fill(0) volumeKey = null volumeRootPath = null + runBlocking { + ProxyStore.restoreNormalProxySelectionAfterIncognito() + } active = false FromChatTlsHostBypass.clear() ServerConfig.reloadFromSettings() diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt index fbf1cb4..c51ac72 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyRuntime.kt @@ -2,9 +2,9 @@ package ru.fromchat.network.proxy import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.first import kotlinx.coroutines.withTimeout import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.flow.asStateFlow @@ -33,6 +33,11 @@ object ProxyRuntime { private val applyMutex = Mutex() + /** Only one SSH [prepareTunnelForSelection] at a time (HTTP gate may wait with many requests). */ + private val sshTunnelMutex = Mutex() + + private val publishRouteMutex = Mutex() + private val _selection = MutableStateFlow(defaultProxySelection()) val selection: StateFlow = _selection.asStateFlow() @@ -76,9 +81,6 @@ object ProxyRuntime { fun initialize() { onIncognitoSessionBoundary() - kotlinx.coroutines.runBlocking { - refreshEffectiveRoute(startTunnel = true) - } } fun onIncognitoSessionBoundary() { @@ -88,6 +90,9 @@ object ProxyRuntime { if (loaded == ProxySelection.System && !systemProxyAvailable()) { _selection.value = ProxySelection.Direct } + kotlinx.coroutines.runBlocking { + refreshEffectiveRoute(startTunnel = true) + } } val needsDirectBypassForCalls: Boolean @@ -105,64 +110,55 @@ object ProxyRuntime { if (probeIsolation || !selectionUsesProxy()) return try { withTimeout(timeoutMs) { - awaitTrafficRouteReadyLoop() + when (val selection = _selection.value) { + ProxySelection.Direct, + ProxySelection.System, + -> return@withTimeout + is ProxySelection.Custom -> { + val proxies = _savedProxies.value.ifEmpty { ProxyStore.readProxies() } + when ( + val proxy = proxyById(selection.id, proxies) + ) { + null, + is HttpProxy, + is Socks5Proxy, + -> return@withTimeout + is SshProxy -> awaitSshTunnelForTraffic() + } + } + } } } catch (_: TimeoutCancellationException) { throw ProxyRouteNotReadyException("Proxy route not ready in ${timeoutMs}ms") } } - private suspend fun awaitTrafficRouteReadyLoop() { - while (true) { - when (val selection = _selection.value) { - ProxySelection.Direct -> return - ProxySelection.System -> { - publishEffectiveRoute() - return - } - is ProxySelection.Custom -> { - val proxy = proxyById( - selection.id, - _savedProxies.value.ifEmpty { ProxyStore.readProxies() }, - ) - if (proxy == null) { - publishEffectiveRoute() - return - } - when (proxy.type) { - ProxyType.HTTP, - ProxyType.SOCKS5, - -> { - publishEffectiveRoute() - return - } - ProxyType.SSH -> when (_tunnelState.value) { - is ProxyTunnelState.Active, - is ProxyTunnelState.Error, - -> { - publishEffectiveRoute() - return - } - ProxyTunnelState.Idle, - ProxyTunnelState.Connecting, - -> { - refreshEffectiveRoute(startTunnel = true) - delay(50) - } - } - } - } - } + private suspend fun awaitSshTunnelForTraffic() { + when (_tunnelState.value) { + is ProxyTunnelState.Active, + is ProxyTunnelState.Error, + -> return + ProxyTunnelState.Idle -> requestSshTunnelStart() + ProxyTunnelState.Connecting -> Unit + } + _tunnelState.first { + it is ProxyTunnelState.Active || it is ProxyTunnelState.Error } } + private suspend fun requestSshTunnelStart() { + refreshEffectiveRoute(startTunnel = true) + } + private suspend fun publishEffectiveRoute() { - val next = buildRoute(_selection.value, _savedProxies.value) - val sshPort = sshLocalPortFromRoute(next) - if (next == _currentRoute.value && (sshPort < 0 || sshPort == lastHttpClientSshLocalPort)) return - _currentRoute.value = next - if (sshPort >= 0) lastHttpClientSshLocalPort = sshPort - ApiClient.rebuildHttpClients() + publishRouteMutex.withLock { + val next = buildRoute(_selection.value, _savedProxies.value) + val sshPort = sshLocalPortFromRoute(next) + if (next == _currentRoute.value && (sshPort < 0 || sshPort == lastHttpClientSshLocalPort)) return + _currentRoute.value = next + if (sshPort >= 0) lastHttpClientSshLocalPort = sshPort + ApiClient.rebuildHttpClients() + } } private fun sshLocalPortFromRoute(route: ProxyRoute): Int = @@ -213,8 +209,18 @@ object ProxyRuntime { refreshEffectiveRoute(startTunnel = false) } - suspend fun upsertProxy(proxy: Proxy, password: String?, privateKey: String?) { - val scope = ProxyStore.scopeForProxyId(proxy.id) ?: ProxyStore.defaultScopeForNewProxy() + suspend fun upsertProxy( + proxy: Proxy, + password: String?, + privateKey: String?, + listingScope: SavedProxyScope? = null, + ) { + val scope = when (listingScope) { + SavedProxyScope.Global -> SavedProxyScope.Global + SavedProxyScope.IncognitoSession -> + ProxyStore.effectiveStorageScopeForProxy(proxy.id) + null -> ProxyStore.effectiveStorageScopeForProxy(proxy.id) + } ProxyStore.upsertListedProxy(SavedProxyListing(proxy, scope)) when { proxy is SshProxy && proxy.auth is SshKeyAuth -> { @@ -248,7 +254,9 @@ object ProxyRuntime { private suspend fun refreshEffectiveRoute(startTunnel: Boolean) { if (startTunnel) { - prepareTunnelForSelection(_selection.value) + sshTunnelMutex.withLock { + prepareTunnelForSelection(_selection.value) + } } publishEffectiveRoute() } @@ -270,6 +278,14 @@ object ProxyRuntime { val proxy = proxyById(customId, _savedProxies.value) ?: return if (proxy !is SshProxy) return + if (_tunnelState.value is ProxyTunnelState.Active && sshForwarder != null) { + return + } + if (_tunnelState.value is ProxyTunnelState.Connecting) { + return + } + + stopSshTunnel() _tunnelState.value = ProxyTunnelState.Connecting val user = proxy.username?.trim().orEmpty() if (user.isEmpty()) { diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyStore.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyStore.kt index bb93f6d..71d3e0d 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyStore.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/network/proxy/ProxyStore.kt @@ -28,6 +28,10 @@ object ProxyStore { const val PROXY_DIRECT_EXPLICIT_KEY = "proxy_direct_explicit_v1" const val INCOGNITO_TRUSTED_CERTS_KEY = "proxy_trusted_certs_v1" + private const val PROXY_SELECTION_BEFORE_INCOGNITO_KEY = "proxy_selection_before_incognito_v1" + private const val PROXY_DIRECT_EXPLICIT_BEFORE_INCOGNITO_KEY = + "proxy_direct_explicit_before_incognito_v1" + private fun passwordKey(id: String) = "proxy_secret_password_$id" private fun privateKeyKey(id: String) = "proxy_secret_private_key_$id" @@ -73,19 +77,68 @@ object ProxyStore { return null } + private suspend fun isGlobalProxyId(id: String): Boolean = + readGlobalProxies().any { it.id == id } + + /** Where to persist proxy mutations (global list wins over incognito session copy). */ + suspend fun effectiveStorageScopeForProxy(id: String): SavedProxyScope = + when { + isGlobalProxyId(id) -> SavedProxyScope.Global + IncognitoMode.active && readSessionProxies().any { it.id == id } -> + SavedProxyScope.IncognitoSession + else -> defaultScopeForNewProxy() + } + + private suspend fun dropSessionProxyIfGlobal(id: String) { + if (!IncognitoMode.active) return + val session = readSessionProxies() + if (session.none { it.id == id }) return + writeSessionProxies(session.filterNot { it.id == id }) + removeSecrets(SavedProxyScope.IncognitoSession, id) + } + suspend fun seedIncognitoProxyStateFromNormal(normal: Settings, incognito: Settings) { - if (normal.contains(PROXY_SELECTION_KEY)) { - incognito.putString(PROXY_SELECTION_KEY, normal.getString(PROXY_SELECTION_KEY, "")) - } - if (normal.contains(PROXY_DIRECT_EXPLICIT_KEY)) { - incognito.putBoolean( - PROXY_DIRECT_EXPLICIT_KEY, - normal.getBoolean(PROXY_DIRECT_EXPLICIT_KEY, false), - ) - } + incognito.putString(PROXY_SELECTION_KEY, normal.getString(PROXY_SELECTION_KEY, "")) + incognito.putBoolean( + PROXY_DIRECT_EXPLICIT_KEY, + normal.getBoolean(PROXY_DIRECT_EXPLICIT_KEY, false), + ) incognito.remove(SAVED_PROXIES_SESSION_KEY) } + /** + * Snapshots normal-mode proxy choice for restore on exit, and seeds the incognito volume + * so the same route stays active for the session. + */ + suspend fun beginIncognitoProxySession(selection: ProxySelection) { + withContext(Dispatchers.IO) { + val enc = json.encodeToString(ProxySelection.serializer(), selection) + val directExplicit = selection == ProxySelection.Direct + val normal = normalProfileSettings() + normal.putString(PROXY_SELECTION_BEFORE_INCOGNITO_KEY, enc) + normal.putBoolean(PROXY_DIRECT_EXPLICIT_BEFORE_INCOGNITO_KEY, directExplicit) + val incognito = incognitoProfileSettings() + incognito.putString(PROXY_SELECTION_KEY, enc) + incognito.putBoolean(PROXY_DIRECT_EXPLICIT_KEY, directExplicit) + } + } + + /** Restores normal-mode proxy selection captured when incognito started. */ + suspend fun restoreNormalProxySelectionAfterIncognito() { + withContext(Dispatchers.IO) { + val normal = normalProfileSettings() + val raw = normal.getString(PROXY_SELECTION_BEFORE_INCOGNITO_KEY, "") + if (raw.isEmpty()) return@withContext + normal.putString(PROXY_SELECTION_KEY, raw) + normal.putBoolean( + PROXY_DIRECT_EXPLICIT_KEY, + normal.getBoolean(PROXY_DIRECT_EXPLICIT_BEFORE_INCOGNITO_KEY, false), + ) + normal.remove(PROXY_SELECTION_BEFORE_INCOGNITO_KEY) + normal.remove(PROXY_DIRECT_EXPLICIT_BEFORE_INCOGNITO_KEY) + } + } + private suspend fun readGlobalProxies(): List = decodeProxyList(normalProfileSettings().getString(SAVED_PROXIES_KEY, "")) @@ -124,8 +177,14 @@ object ProxyStore { } suspend fun upsertListedProxy(listing: SavedProxyListing) { - val scope = listing.scope val proxy = listing.proxy + val scope = + when { + listing.scope == SavedProxyScope.Global || isGlobalProxyId(proxy.id) -> + SavedProxyScope.Global + listing.scope == SavedProxyScope.IncognitoSession -> SavedProxyScope.IncognitoSession + else -> effectiveStorageScopeForProxy(proxy.id) + } withContext(Dispatchers.IO) { val list = when (scope) { SavedProxyScope.Global -> readGlobalProxies().toMutableList() @@ -138,7 +197,10 @@ object ProxyStore { list.add(proxy) } when (scope) { - SavedProxyScope.Global -> writeGlobalProxies(list) + SavedProxyScope.Global -> { + writeGlobalProxies(list) + dropSessionProxyIfGlobal(proxy.id) + } SavedProxyScope.IncognitoSession -> writeSessionProxies(list) } } @@ -146,16 +208,16 @@ object ProxyStore { suspend fun removeProxy(id: String) { withContext(Dispatchers.IO) { - when (scopeForProxyId(id)) { - SavedProxyScope.Global -> { + when { + isGlobalProxyId(id) -> { writeGlobalProxies(readGlobalProxies().filterNot { it.id == id }) removeSecrets(SavedProxyScope.Global, id) + dropSessionProxyIfGlobal(id) } - SavedProxyScope.IncognitoSession -> { + IncognitoMode.active && readSessionProxies().any { it.id == id } -> { writeSessionProxies(readSessionProxies().filterNot { it.id == id }) removeSecrets(SavedProxyScope.IncognitoSession, id) } - null -> Unit } } } diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthLayout.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthLayout.kt index 707f2bd..5671bbe 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthLayout.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthLayout.kt @@ -28,7 +28,11 @@ 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 kotlinx.coroutines.launch +import ru.fromchat.incognito.IncognitoMode +import ru.fromchat.logging.Logger import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @@ -141,6 +145,7 @@ internal fun AuthStepListFooter( hideAuthRouteSwitch: Boolean = false, ) { val navController = LocalNavController.current + val scope = rememberCoroutineScope() if (hideAuthRouteSwitch) return Row( Modifier @@ -156,9 +161,14 @@ internal fun AuthStepListFooter( if (incognitoFlow) { TextCta( onClick = { - navController.navigate(AUTH_ROUTE) { - popUpTo(AUTH_INCOGNITO_ROUTE) { inclusive = true } - launchSingleTop = true + scope.launch { + if (IncognitoMode.active) { + IncognitoMode.destroy() + } + navController.navigate(AUTH_ROUTE) { + popUpTo(AUTH_INCOGNITO_ROUTE) { inclusive = true } + launchSingleTop = true + } } }, modifier = Modifier.fillMaxWidth(), @@ -170,9 +180,17 @@ internal fun AuthStepListFooter( } else { TextCta( onClick = { - navController.navigate(AUTH_INCOGNITO_ROUTE) { - popUpTo(AUTH_ROUTE) { inclusive = true } - launchSingleTop = true + scope.launch { + if (!IncognitoMode.active) { + runCatching { IncognitoMode.activate() } + .onFailure { error -> + Logger.e("AuthStepListFooter", "incognito activate failed", error) + } + } + navController.navigate(AUTH_INCOGNITO_ROUTE) { + popUpTo(AUTH_ROUTE) { inclusive = true } + launchSingleTop = true + } } }, modifier = Modifier.fillMaxWidth(), diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthScreen.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthScreen.kt index 765bcca..aa4b8e6 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthScreen.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/AuthScreen.kt @@ -321,6 +321,13 @@ fun AuthScreen( LaunchedEffect(incognitoFlow) { AuthRegisterDraft.incognitoEnabled = incognitoFlow + if (incognitoFlow) { + if (!IncognitoMode.active) { + runCatching { IncognitoMode.activate() } + } + } else if (!incognitoOverlayFromChat && IncognitoMode.active) { + IncognitoMode.destroy() + } } LaunchedEffect(incognitoOverlayFromChat) { diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/UsernameStep.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/UsernameStep.kt index 45e4b25..33d54d1 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/UsernameStep.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/auth/UsernameStep.kt @@ -114,12 +114,14 @@ internal fun usernameStepPage( ) try { if (incognitoEnabled) { - try { - IncognitoMode.activate() - } catch (e: IllegalArgumentException) { - Logger.e(USERNAME_STEP_TAG, "incognito activate failed username=$trimmed", e) - onSnackbar(unexpected, e) - return@launch + if (!IncognitoMode.active) { + try { + IncognitoMode.activate() + } catch (e: IllegalArgumentException) { + Logger.e(USERNAME_STEP_TAG, "incognito activate failed username=$trimmed", e) + onSnackbar(unexpected, e) + return@launch + } } } else if (IncognitoMode.active) { IncognitoMode.destroy() diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/components/ConnectingEllipsis.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/components/ConnectingEllipsis.kt index ac3a674..db60a9b 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/components/ConnectingEllipsis.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/components/ConnectingEllipsis.kt @@ -60,4 +60,4 @@ fun ConnectingEllipsis( } } } -} +} \ No newline at end of file diff --git a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/AddProxyScreen.kt b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/AddProxyScreen.kt index 20c77ef..06dd826 100644 --- a/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/AddProxyScreen.kt +++ b/app/shared/src/commonMain/kotlin/ru/fromchat/ui/main/settings/proxy/AddProxyScreen.kt @@ -56,6 +56,7 @@ import org.jetbrains.compose.resources.stringResource import ru.fromchat.Res import ru.fromchat.network.proxy.ProxyRuntime import ru.fromchat.network.proxy.ProxyStore +import ru.fromchat.network.proxy.SavedProxyScope import ru.fromchat.network.proxy.ProxyType import ru.fromchat.network.proxy.HttpProxy import ru.fromchat.network.proxy.PasswordAuth @@ -165,6 +166,7 @@ fun AddProxyScreen( var showDeleteConfirm by remember { mutableStateOf(false) } val savedProxies by ProxyRuntime.savedProxies.collectAsState() + val savedProxyListings by ProxyRuntime.savedProxyListings.collectAsState() LaunchedEffect(editingProxyId, savedProxies) { val id = editingProxyId ?: return@LaunchedEffect @@ -340,10 +342,14 @@ fun AddProxyScreen( } } scope.launch { + val listingScope = editingProxyId?.let { editId -> + savedProxyListings.firstOrNull { it.proxy.id == editId }?.scope + } ProxyRuntime.upsertProxy( proxy = proxy, password = password.takeIf { it.isNotEmpty() }, privateKey = privateKey.takeIf { it.isNotEmpty() }, + listingScope = listingScope, ) onDone() } diff --git a/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/JvmTlsStreamHttp.jvm.kt b/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/JvmTlsStreamHttp.jvm.kt index ae5023f..9d8860b 100644 --- a/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/JvmTlsStreamHttp.jvm.kt +++ b/app/shared/src/jvmMain/kotlin/ru/fromchat/network/proxy/JvmTlsStreamHttp.jvm.kt @@ -90,16 +90,9 @@ internal fun writeTlsApplicationData( internal fun readTlsApplicationData(ctx: TlsEngineIoContext, buf: ByteArray, off: Int, len: Int): Int { var appBuffer = ByteBuffer.allocate(ctx.appSize) - var inboundEof = false while (true) { - if (ctx.peerBuffer.position() == 0) { - if (inboundEof) return -1 - val added = appendInboundCiphertext(ctx.peerBuffer, ctx.plainIn, ctx.netSize, allowEof = true) - if (!added) inboundEof = true - if (ctx.peerBuffer.position() == 0) { - if (inboundEof) return -1 - continue - } + if (ctx.peerBuffer.position() == 0 && !readInboundCiphertext(ctx.peerBuffer, ctx.plainIn, ctx.netSize)) { + return -1 } ctx.peerBuffer.flip() if (!ctx.peerBuffer.hasRemaining()) { @@ -125,9 +118,15 @@ internal fun readTlsApplicationData(ctx: TlsEngineIoContext, buf: ByteArray, off } when (result.status) { SSLEngineResult.Status.CLOSED -> return -1 - SSLEngineResult.Status.BUFFER_UNDERFLOW -> continue + SSLEngineResult.Status.BUFFER_UNDERFLOW -> { + if (!readInboundCiphertext(ctx.peerBuffer, ctx.plainIn, ctx.netSize) && ctx.peerBuffer.position() == 0) { + return -1 + } + } else -> { - if (inboundEof && ctx.peerBuffer.position() == 0) return -1 + if (ctx.peerBuffer.position() == 0 && !readInboundCiphertext(ctx.peerBuffer, ctx.plainIn, ctx.netSize)) { + return -1 + } } } } @@ -238,6 +237,10 @@ private fun appendTlsInbound(peerBuffer: ByteBuffer, plainIn: InputStream, maxCh } } +/** + * Reads more TLS ciphertext into [peerBuffer] when the engine needs input. + * @return `false` if EOF before any byte was buffered; `true` if the buffer holds ciphertext. + */ private fun appendInboundCiphertext( peerBuffer: ByteBuffer, plainIn: InputStream, @@ -253,11 +256,24 @@ private fun appendInboundCiphertext( val before = peerBuffer.position() val read = fillFromSocketBlocking(plainIn, peerBuffer, maxChunk) if (!read && peerBuffer.position() == before) { - return allowEof + return false } return peerBuffer.position() > before } +/** Blocks until more TLS ciphertext is buffered or the socket hits EOF. */ +private fun readInboundCiphertext( + peerBuffer: ByteBuffer, + plainIn: InputStream, + maxChunk: Int, + allowEof: Boolean = false, +): Boolean { + if (appendInboundCiphertext(peerBuffer, plainIn, maxChunk, allowEof = allowEof)) { + return true + } + return if (allowEof) peerBuffer.position() > 0 else false +} + private fun drainPeerCiphertext( engine: SSLEngine, plainIn: InputStream, @@ -337,16 +353,9 @@ private fun readPlaintextUntilClosed( ): ByteArray { var appBuffer = ByteBuffer.allocate(appSize) val collected = ArrayList(8192) - var inboundEof = false while (true) { - if (peerBuffer.position() == 0) { - if (inboundEof) break - val added = appendInboundCiphertext(peerBuffer, plainIn, netSize, allowEof = true) - if (!added) inboundEof = true - if (peerBuffer.position() == 0) { - if (inboundEof) break - continue - } + if (peerBuffer.position() == 0 && !readInboundCiphertext(peerBuffer, plainIn, netSize, allowEof = true)) { + break } peerBuffer.flip() if (!peerBuffer.hasRemaining()) { @@ -370,9 +379,15 @@ private fun readPlaintextUntilClosed( } when (result.status) { SSLEngineResult.Status.CLOSED -> break - SSLEngineResult.Status.BUFFER_UNDERFLOW -> continue + SSLEngineResult.Status.BUFFER_UNDERFLOW -> { + if (!readInboundCiphertext(peerBuffer, plainIn, netSize, allowEof = true) && peerBuffer.position() == 0) { + break + } + } else -> { - if (inboundEof && peerBuffer.position() == 0) break + if (peerBuffer.position() == 0 && !readInboundCiphertext(peerBuffer, plainIn, netSize, allowEof = true)) { + break + } } } }