1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package com.vauth.foxyvpn.vpn.upstream
import com.vauth.foxyvpn.data.model.AccountLiveStats
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
private const val STATS_TRACKER_INTERVAL_MS = 2_000L
/**
* Multi-account session orchestrator (multi-account patch).
*
* Holds one [UpstreamSession] per account and multiplexes new streams across
* them with round-robin. Implements [UpstreamSession] so the rest of the VPN
* service (watchdog, redial, teardown) keeps working unchanged.
*
* Byte counters are gathered by wrapping every opened stream; speeds are
* derived by the stats tracker.
*/
class MultiUpstreamSessionPool : UpstreamSession {
private data class AccountEntry(
val accountId: String,
val email: String,
val session: UpstreamSession,
@Volatile var isExhausted: Boolean = false,
@Volatile var passExpiresAtEpochSeconds: Long? = null,
val bytesDown: AtomicLong = AtomicLong(0L),
val bytesUp: AtomicLong = AtomicLong(0L),
val activeStreams: AtomicInteger = AtomicInteger(0),
@Volatile var speedDownBytesPerSec: Long = 0L,
@Volatile var speedUpBytesPerSec: Long = 0L,
)
private val entries = CopyOnWriteArrayList<AccountEntry>()
private val roundRobin = AtomicInteger(0)
private val _liveStats = MutableStateFlow<List<AccountLiveStats>>(emptyList())
val liveStats: StateFlow<List<AccountLiveStats>> = _liveStats
val accountCount: Int get() = entries.size
fun addAccountSession(accountId: String, email: String, session: UpstreamSession) {
entries.removeAll { it.accountId == accountId }
entries.add(AccountEntry(accountId = accountId, email = email, session = session))
publishStatsSnapshot()
}
fun removeAccountSession(accountId: String) {
entries.filter { it.accountId == accountId }.forEach { runCatching { it.session.close() } }
entries.removeAll { it.accountId == accountId }
publishStatsSnapshot()
}
fun markExhausted(accountId: String) {
entries.find { it.accountId == accountId }?.isExhausted = true
publishStatsSnapshot()
}
fun setPassExpiry(accountId: String, expiresAtEpochSeconds: Long?) {
entries.find { it.accountId == accountId }?.passExpiresAtEpochSeconds = expiresAtEpochSeconds
}
fun minPassExpiry(): Long? = entries.mapNotNull { it.passExpiresAtEpochSeconds }.minOrNull()
fun updateAccountToken(accountId: String, token: String) {
entries.find { it.accountId == accountId }?.session?.updateBearerToken(token)
}
override suspend fun connect() {
// Sessions are dialed before being added; nothing to do here.
}
override suspend fun openStream(targetHost: String, targetPort: Int): TunneledStream {
val candidates = entries.filter { it.session.isConnected && !it.isExhausted }
if (candidates.isEmpty()) throw IOException("No connected upstream account available")
val start = roundRobin.getAndIncrement()
var lastError: Throwable? = null
for (i in candidates.indices) {
val entry = candidates[(start + i).mod(candidates.size)]
try {
val stream = entry.session.openStream(targetHost, targetPort)
entry.activeStreams.incrementAndGet()
var closed = false
fun onClose() {
if (!closed) {
closed = true
entry.activeStreams.decrementAndGet()
}
}
return TunneledStream(
input = CountingInputStream(stream.input) { n -> entry.bytesDown.addAndGet(n) },
output = CountingOutputStream(stream.output) { n -> entry.bytesUp.addAndGet(n) },
close = {
try {
stream.close()
} finally {
onClose()
}
},
)
} catch (failure: Throwable) {
lastError = failure
}
}
throw lastError ?: IOException("No connected upstream account available")
}
override fun disableNewStreamsAndCloseWhenIdle() {
entries.forEach { runCatching { it.session.disableNewStreamsAndCloseWhenIdle() } }
}
override fun updateBearerToken(token: String) {
entries.forEach { runCatching { it.session.updateBearerToken(token) } }
}
override val isConnected: Boolean
get() = entries.any { it.session.isConnected && !it.isExhausted }
override fun close() {
entries.forEach { runCatching { it.session.close() } }
entries.clear()
_liveStats.value = emptyList()
}
fun startStatsTracker(scope: CoroutineScope): Job = scope.launch {
var lastBytes = snapshotBytes()
var lastAt = System.currentTimeMillis()
while (isActive) {
delay(STATS_TRACKER_INTERVAL_MS)
val now = System.currentTimeMillis()
val elapsedSeconds = (now - lastAt).coerceAtLeast(1L).toDouble() / 1_000.0
_liveStats.value = entries.map { entry ->
val (prevDown, prevUp) = lastBytes[entry.accountId] ?: (0L to 0L)
val down = entry.bytesDown.get()
val up = entry.bytesUp.get()
entry.speedDownBytesPerSec = ((down - prevDown).coerceAtLeast(0L) / elapsedSeconds).toLong()
entry.speedUpBytesPerSec = ((up - prevUp).coerceAtLeast(0L) / elapsedSeconds).toLong()
AccountLiveStats(
accountId = entry.accountId,
email = entry.email,
isConnected = entry.session.isConnected,
isExhausted = entry.isExhausted,
activeStreams = entry.activeStreams.get(),
bytesDown = down,
bytesUp = up,
speedDownBytesPerSec = entry.speedDownBytesPerSec,
speedUpBytesPerSec = entry.speedUpBytesPerSec,
)
}
lastBytes = snapshotBytes()
lastAt = now
}
}
private fun snapshotBytes(): Map<String, Pair<Long, Long>> =
entries.associate { it.accountId to (it.bytesDown.get() to it.bytesUp.get()) }
private fun publishStatsSnapshot() {
_liveStats.value = entries.map { entry ->
AccountLiveStats(
accountId = entry.accountId,
email = entry.email,
isConnected = entry.session.isConnected,
isExhausted = entry.isExhausted,
activeStreams = entry.activeStreams.get(),
bytesDown = entry.bytesDown.get(),
bytesUp = entry.bytesUp.get(),
speedDownBytesPerSec = entry.speedDownBytesPerSec,
speedUpBytesPerSec = entry.speedUpBytesPerSec,
)
}
}
private class CountingInputStream(
private val delegate: InputStream,
private val onBytes: (Long) -> Unit,
) : InputStream() {
override fun read(): Int = delegate.read().also { if (it >= 0) onBytes(1L) }
override fun read(b: ByteArray, off: Int, len: Int): Int =
delegate.read(b, off, len).also { if (it > 0) onBytes(it.toLong()) }
override fun available(): Int = delegate.available()
override fun skip(n: Long): Long = delegate.skip(n)
override fun close() = delegate.close()
}
private class CountingOutputStream(
private val delegate: OutputStream,
private val onBytes: (Long) -> Unit,
) : OutputStream() {
override fun write(b: Int) {
delegate.write(b)
onBytes(1L)
}
override fun write(b: ByteArray, off: Int, len: Int) {
delegate.write(b, off, len)
onBytes(len.toLong())
}
override fun flush() = delegate.flush()
override fun close() = delegate.close()
}
}