Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ import kotlinx.coroutines.Job
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
Expand Down Expand Up @@ -198,6 +200,14 @@ class PairingReceiver(
private companion object {
private const val TAG = "PairingReceiver"

/**
* How long a connected phone may stay silent (no message, no attempt
* in flight) before the TV drops it and goes back to advertising. The
* advertiser serves one phone at a time, so a phone that loses its
* network must not hold setup forever. Same limit as tvOS and Roku.
*/
private val IDLE_TIMEOUT = 180.seconds

/** Bound on withdrawing an abandoned request (DeviceSignInMachine's). */
private val WITHDRAW_TIMEOUT = 5.seconds
}
Expand Down Expand Up @@ -233,6 +243,17 @@ class PairingReceiver(

private val signedInNames = mutableListOf<String>()

/** Drops a silent phone after [IDLE_TIMEOUT]; see [armIdleTimer]. */
private var idleJob: Job? = null

/**
* Set when the session starts closing (idle expiry or the stream ended):
* from then on nothing re-arms the timer or starts an attempt. Guarded by
* [sessionLock], which orders expiry against activity.
*/
private var sessionClosing = false
private val sessionLock = Any()

/**
* The setup attempt that owns [deviceLogin]'s shared state. An attempt
* can outlive its connection (saving a session can't be cancelled) while
Expand Down Expand Up @@ -328,6 +349,10 @@ class PairingReceiver(
sessionDenied = false
activeTransport = transport
signedInNames.clear()
synchronized(sessionLock) {
sessionClosing = false
idleJob = null
}
var preserveTerminalStatus = false
try {
val identity = identityProvider()
Expand All @@ -350,7 +375,11 @@ class PairingReceiver(
coroutineScope {
val scope = this
sessionScope = scope
armIdleTimer(transport, scope)
Comment thread
Quick104 marked this conversation as resolved.
Resolved
transport.incoming.collectMessage { message ->
// An attempt in flight holds the timer; it restarts when
// the attempt ends (or below, when a push replaces it).
if (pushJob?.isActive != true) armIdleTimer(transport, scope)
when (message) {
is PairingMessage.PushServer ->
handlePushServer(message, transport, scope)
Expand Down Expand Up @@ -389,6 +418,7 @@ class PairingReceiver(
true
}
// Stream ended (Done/Cancel/EOF) — cancel any in-flight device-login.
beginClosing(transport)
pushJob?.cancel()
if (!preserveTerminalStatus) {
if (signedInNames.isNotEmpty()) {
Expand All @@ -402,16 +432,21 @@ class PairingReceiver(
} catch (e: CancellationException) {
throw e
} catch (_: Throwable) {
// Transport / decode error: connection dropped mid-session.
// Transport / decode error: connection dropped mid-session (the
// idle timer's close ends a real socket this way too). Like a
// clean end: a lone failure keeps its explanation on screen.
if (signedInNames.isNotEmpty()) {
_status.value = PairingReceiverStatus.Completed(signedInNames.toList())
preserveTerminalStatus = true
} else if (_status.value is PairingReceiverStatus.Failed) {
preserveTerminalStatus = true
}
} finally {
// A newer connection may own the receiver already (the advertiser
// restarted while this one unwound): its session, push and status
// are not this run's to clear.
if (activeTransport === transport) {
beginClosing(transport)
pushJob?.cancel()
pushJob = null
pendingPush = null
Expand Down Expand Up @@ -446,6 +481,7 @@ class PairingReceiver(
// consented session: the approval covers that one origin.
val unencrypted = cleartextConsent.requiresApproval(message.serverURL)
if (!consented || unencrypted) {
armIdleTimer(transport, sessionScope)
pendingPush = message
_status.value = PairingReceiverStatus.ConsentRequested(
message.serverURL,
Expand All @@ -467,18 +503,68 @@ class PairingReceiver(
// auto-approves only after its user confirmed the first code.
val automatic = signedInNames.isNotEmpty()
val ad = advertisement
pushJob = sessionScope.launch {
if (approveCleartext) {
canonicalHttpOrigin(push.serverURL)?.let { cleartextConsent.approve(it) }
// The idle timer waits while an attempt is in flight: device login is
// bounded by the code's own expiry, and the unreachable-address
// choice waits on the TV user. Under the lock, so an expired or
// ending session never starts one.
synchronized(sessionLock) {
if (sessionClosing) return
idleJob?.cancel()
idleJob = null
pushJob = sessionScope.launch {
if (approveCleartext) {
canonicalHttpOrigin(push.serverURL)?.let { cleartextConsent.approve(it) }
}
if (ad.state == PairingReceiverState.Login) {
runLoginAttempt(push, transport, ad)
} else {
runAttempt(push, transport, automatic)
}
// A cancelled attempt can still get here (the result sends
// swallow cancellation); only a finished one restarts the wait.
if (isActive) armIdleTimer(transport, sessionScope)
}
if (ad.state == PairingReceiverState.Login) {
runLoginAttempt(push, transport, ad)
} else {
runAttempt(push, transport, automatic)
}
}

/**
* (Re)start the idle deadline for [transport]'s session. On expiry the
* session is closed without a goodbye frame: a write to a dead peer can
* block, and both phone apps treat a closed connection as the end.
* Closing ends [run], which returns the TV to advertising.
*/
private fun armIdleTimer(transport: PairingTransport, scope: CoroutineScope) {
synchronized(sessionLock) {
if (sessionClosing || activeTransport !== transport) return
idleJob?.cancel()
idleJob = scope.launch {
delay(IDLE_TIMEOUT)
synchronized(sessionLock) {
// Activity that cancelled this timer first wins; otherwise
// expiry wins and a later Allow finds nothing to allow.
if (!isActive || activeTransport !== transport || sessionClosing) return@launch
sessionClosing = true
pendingPush = null
}
Log.i(TAG, "pairing session idle timeout; dropping peer")
transport.close()
Comment thread
Quick104 marked this conversation as resolved.
Resolved
Comment thread
Quick104 marked this conversation as resolved.
Resolved
Comment thread
Quick104 marked this conversation as resolved.
Resolved
}
}
}

/**
* [transport]'s session is ending: stop the idle timer and refuse new
* attempts. A newer connection's session is left alone.
*/
private fun beginClosing(transport: PairingTransport) {
synchronized(sessionLock) {
if (activeTransport !== transport) return
sessionClosing = true
idleJob?.cancel()
idleJob = null
}
}

/**
* `login` mode: only the advertised server is accepted, by the identity
* the phone pushed (a push without one can't be checked, so it's
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,23 @@ import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
import kotlin.test.assertIs
import kotlin.time.Duration.Companion.seconds

/** In-memory transport: inbound via a channel, outbound recorded in a list. */
private class FakeTransport : PairingTransport {
/**
* In-memory transport: inbound via a channel, outbound recorded in a list.
* [closeFails]: [close] ends [incoming] with an error, as closing the real
* socket does to its blocked read.
*/
private class FakeTransport(private val closeFails: Boolean = false) : PairingTransport {
private val inbound = Channel<PairingMessage>(Channel.UNLIMITED)
val sent = mutableListOf<PairingMessage>()
var closed = false
Expand All @@ -38,7 +45,7 @@ private class FakeTransport : PairingTransport {

override fun close() {
closed = true
inbound.close()
inbound.close(if (closeFails) java.net.SocketException("Socket closed") else null)
}

/** Push an inbound message from the "phone". */
Expand Down Expand Up @@ -660,6 +667,52 @@ class PairingReceiverTest {
job.join()
}

@Test
fun aSilentPhoneIsDroppedAfterTheIdleLimit() = runTest {
val transport = FakeTransport()
val login = FakeDeviceLogin()
val recv = receiver(FakeAuthPort(), login)
val job = launch { recv.run(transport) }
yield()
transport.deliver(PairingMessage.PushServer("https://srv.test", "Srv"))
settle()
assertEquals(PairingReceiverStatus.ConsentRequested("https://srv.test", "Srv"), recv.status.value)

// The phone's network drops: no frame and no close ever arrive.
advanceTimeBy(179.seconds)
runCurrent()
assertFalse(transport.closed)
advanceTimeBy(2.seconds)
runCurrent()
assertTrue(transport.closed, "a silent phone is dropped at the idle limit")
job.join()
// Back to waiting, so the advertiser takes the next phone.
assertEquals(PairingReceiverStatus.Idle, recv.status.value)
// An Allow that lands after the drop starts nothing.
recv.allowPendingServer()
assertEquals(null, login.beganWith)
}

@Test
fun aFinishedAttemptRestartsTheIdleLimitAndKeepsItsFailure() = runTest {
val transport = FakeTransport(closeFails = true)
val login = FakeDeviceLogin()
val recv = receiver(FakeAuthPort(), login)
val job = launch { recv.run(transport) }
yield()
transport.deliver(PairingMessage.PushServer("https://srv.test", "Srv"))
settle()
recv.allowPendingServer()
settle()
login.fail("denied")
settle()
advanceTimeBy(181.seconds)
runCurrent()
assertTrue(transport.closed, "the idle limit restarts after an attempt")
job.join()
assertEquals(PairingReceiverStatus.Failed("Srv", PairingFailureCode.Denied), recv.status.value)
}

@Test
fun anAbandonedSetupRequestIsWithdrawnButTheSignInScreensIsNot() = runTest {
// How the attempt ends -> whether the TV withdraws its request.
Expand Down
Loading