arblant
FoxyVPN-MultiAcc / app / src / main / java / com / vauth / foxyvpn / vpn / upstream / H2UpstreamSession.kt
H2UpstreamSession.kt815 lines · 33.8 KB
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 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
package com.vauth.foxyvpn.vpn.upstream

import android.os.Build
import com.vauth.foxyvpn.BuildConfig
import com.vauth.foxyvpn.data.AppLogger
import io.netty.bootstrap.Bootstrap
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.WriteBufferWaterMark
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.handler.codec.http2.DefaultHttp2DataFrame
import io.netty.handler.codec.http2.DefaultHttp2Headers
import io.netty.handler.codec.http2.DefaultHttp2HeadersFrame
import io.netty.handler.codec.http2.DefaultHttp2PingFrame
import io.netty.handler.codec.http2.DefaultHttp2WindowUpdateFrame
import io.netty.handler.codec.http2.Http2CodecUtil
import io.netty.handler.codec.http2.Http2DataFrame
import io.netty.handler.codec.http2.Http2FrameCodecBuilder
import io.netty.handler.codec.http2.Http2FrameLogger
import io.netty.handler.codec.http2.Http2GoAwayFrame
import io.netty.handler.codec.http2.Http2HeadersFrame
import io.netty.handler.codec.http2.Http2MultiplexHandler
import io.netty.handler.codec.http2.Http2PingFrame
import io.netty.handler.codec.http2.Http2ResetFrame
import io.netty.handler.codec.http2.Http2Settings
import io.netty.handler.codec.http2.Http2SettingsFrame
import io.netty.handler.codec.http2.Http2StreamChannel
import io.netty.handler.codec.http2.Http2StreamChannelBootstrap
import io.netty.handler.codec.http2.Http2StreamFrame
import io.netty.handler.logging.LogLevel
import io.netty.handler.proxy.HttpProxyHandler
import io.netty.handler.proxy.ProxyHandler
import io.netty.handler.proxy.Socks5ProxyHandler
import io.netty.handler.ssl.ApplicationProtocolConfig
import io.netty.handler.ssl.ApplicationProtocolNames
import io.netty.resolver.NoopAddressResolverGroup
import io.netty.handler.ssl.SslContext
import io.netty.handler.ssl.SslContextBuilder
import io.netty.handler.ssl.SslHandshakeCompletionEvent
import io.netty.handler.ssl.SslProvider
import io.netty.handler.ssl.SupportedCipherSuiteFilter
import io.netty.util.ReferenceCountUtil
import io.netty.util.concurrent.Future
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withTimeoutOrNull
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetSocketAddress
import java.security.Provider
import java.security.Security
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

private const val TAG = "H2UpstreamSession"

private const val KEEPALIVE_CHECK_INTERVAL_MS = 3_000L
private const val KEEPALIVE_IDLE_THRESHOLD_MS = 15_000L
private const val KEEPALIVE_PING_TIMEOUT_MS = 10_000L

private const val KEEPALIVE_PING_PAYLOAD = 0x466F78795650_4EL

private const val OPEN_STREAM_TIMEOUT_MS = 20_000L

private const val TCP_CONNECT_TIMEOUT_MS = 15_000

private const val TLS_ENDPOINT_IDENTIFICATION_HTTPS = "HTTPS"

private const val CONSCRYPT_PROVIDER_NAME = "Conscrypt"

private val TLS_PROVIDER: Provider? = runCatching { Security.getProvider(CONSCRYPT_PROVIDER_NAME) }.getOrNull()

private val TLS_PROTOCOLS: Array<String> =
    if (TLS_PROVIDER != null || Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        arrayOf("TLSv1.3", "TLSv1.2")
    } else {
        arrayOf("TLSv1.2")
    }

private const val HTTP2_FLOW_CONTROL_WINDOW_BYTES = 16 * 1024 * 1024

private const val HTTP2_MAX_FRAME_SIZE_BYTES = 256 * 1024

private val STREAM_WRITE_WATER_MARK = WriteBufferWaterMark(512 * 1024, 2 * 1024 * 1024)

private val PARENT_WRITE_WATER_MARK = WriteBufferWaterMark(1024 * 1024, 4 * 1024 * 1024)

private const val WRITE_BACKPRESSURE_TIMEOUT_MS = 60_000L

private const val STREAM_SLOT_WAIT_TIMEOUT_MS = 15_000L

private const val STREAM_SLOT_POLL_INTERVAL_MS = 20L

private const val DRAIN_IDLE_TIMEOUT_MS = 120_000L

private const val DRAIN_POLL_INTERVAL_MS = 250L

data class UpstreamProxyConfig(
    val type: Type,
    val host: String,
    val port: Int,
    val username: String? = null,
    val password: String? = null,
) {
    enum class Type { SOCKS5, HTTP }
}

class H2UpstreamSession(
    private val upstreamHost: String,
    private val upstreamPort: Int,
    bearerToken: String,
    private val upstreamProxy: UpstreamProxyConfig? = null,
    private val edgeAddress: String? = null,
) : UpstreamSession {

    private val group = NioEventLoopGroup(1)

    @Volatile private var currentBearerToken: String = bearerToken

    private val connectHost: String = edgeAddress?.takeIf { it.isNotBlank() } ?: upstreamHost

    private val keepaliveScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
    private var parentChannel: Channel? = null

    @Volatile private var lastActivityAt = System.currentTimeMillis()

    @Volatile private var lastStreamDataAt = System.currentTimeMillis()
    @Volatile private var awaitingPingAck = false
    @Volatile private var pingSentAt = 0L
    @Volatile private var acceptingNewStreams = true
    private val activeStreams = AtomicInteger(0)

    @Volatile private var maxConcurrentStreams = Int.MAX_VALUE

    private val closed = AtomicBoolean(false)

    @Volatile private var closing = false

    private val drainWatcherArmed = AtomicBoolean(false)

    override val isConnected: Boolean
        get() = parentChannel?.isActive == true && acceptingNewStreams

    override fun updateBearerToken(token: String) {
        if (token.isBlank() || token == currentBearerToken) return
        currentBearerToken = token
        AppLogger.i(
            TAG,
            "proxy pass swapped into the live session; the existing HTTP/2 tunnel keeps running and " +
                "subsequent flows authenticate with the new pass",
        )
    }

    override fun disableNewStreamsAndCloseWhenIdle() {
        acceptingNewStreams = false
        if (activeStreams.get() == 0) {
            close()
            return
        }

        if (!drainWatcherArmed.compareAndSet(false, true)) return

        lastStreamDataAt = System.currentTimeMillis()
        keepaliveScope.launch {

            while (activeStreams.get() > 0 &&
                System.currentTimeMillis() - lastStreamDataAt < DRAIN_IDLE_TIMEOUT_MS
            ) {
                delay(DRAIN_POLL_INTERVAL_MS)
            }
            val stranded = activeStreams.get()
            if (stranded > 0) {
                AppLogger.w(
                    TAG,
                    "a swapped-out upstream session has moved no data for " +
                        "${DRAIN_IDLE_TIMEOUT_MS / 1_000}s with $stranded flow(s) still open; closing it so its " +
                        "socket and event loop are not held for the lifetime of the tunnel",
                )
            }
            close()
        }
    }

    private fun noteInboundActivity() {
        lastActivityAt = System.currentTimeMillis()
        if (awaitingPingAck) awaitingPingAck = false
    }

    private fun noteStreamData() {
        val now = System.currentTimeMillis()
        lastActivityAt = now

        lastStreamDataAt = now
    }

    override suspend fun connect() = withContext(Dispatchers.IO) {

        val sslContextBuilder = SslContextBuilder.forClient()
            .sslProvider(SslProvider.JDK)
            .protocols(*TLS_PROTOCOLS)
            .applicationProtocolConfig(
                ApplicationProtocolConfig(
                    ApplicationProtocolConfig.Protocol.ALPN,

                    ApplicationProtocolConfig.SelectorFailureBehavior.FATAL_ALERT,
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.FATAL_ALERT,
                    ApplicationProtocolNames.HTTP_2,
                ),
            )
            .ciphers(null, SupportedCipherSuiteFilter.INSTANCE)

        val tlsProvider = TLS_PROVIDER
        if (tlsProvider != null) {
            sslContextBuilder.sslContextProvider(tlsProvider)
        } else {
            AppLogger.w(
                TAG,
                "Conscrypt is unavailable; falling back to the platform TLS stack " +
                    "(protocols=${TLS_PROTOCOLS.joinToString()})",
            )
        }

        UpstreamTrust.trustManagerFactory()?.let { sslContextBuilder.trustManager(it) }
        val sslContext: SslContext = sslContextBuilder.build()

        if (connectHost != upstreamHost) {
            AppLogger.i(
                TAG,
                "custom edge address in use: TCP to $connectHost:$upstreamPort, still presenting and " +
                    "verifying \"$upstreamHost\"",
            )
        }

        val handshakeDone = CompletableDeferred<Unit>()
        val bootstrap = Bootstrap()
            .group(group)
            .channel(FoxyNioSocketChannel::class.java)
            .apply {
                if (upstreamProxy != null) resolver(NoopAddressResolverGroup.INSTANCE)
            }

            .option(ChannelOption.TCP_NODELAY, true)

            .option(ChannelOption.SO_KEEPALIVE, true)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, TCP_CONNECT_TIMEOUT_MS)
            .option(ChannelOption.WRITE_BUFFER_WATER_MARK, PARENT_WRITE_WATER_MARK)
            .handler(object : ChannelInitializer<FoxyNioSocketChannel>() {
                override fun initChannel(ch: FoxyNioSocketChannel) {
                    runCatching {
                        com.vauth.foxyvpn.data.ControlPlaneHttp.socketProtector?.invoke(ch.publicJavaChannel().socket())
                    }.onFailure {
                        com.vauth.foxyvpn.data.AppLogger.e(TAG, "failed to protect netty socket", it)
                    }

                    upstreamProxy?.let { proxy -> ch.pipeline().addLast(buildProxyHandler(proxy)) }

                    val sslHandler = sslContext.newHandler(ch.alloc(), upstreamHost, upstreamPort)

                    val engine = sslHandler.engine()
                    engine.sslParameters = engine.sslParameters.apply {
                        endpointIdentificationAlgorithm = TLS_ENDPOINT_IDENTIFICATION_HTTPS
                    }

                    val frameCodecBuilder = Http2FrameCodecBuilder.forClient()

                        .initialSettings(
                            Http2Settings.defaultSettings()
                                .initialWindowSize(HTTP2_FLOW_CONTROL_WINDOW_BYTES)
                                .maxFrameSize(HTTP2_MAX_FRAME_SIZE_BYTES)
                                .pushEnabled(false),
                        )

                        .autoAckPingFrame(false)
                    if (BuildConfig.DEBUG) {

                        frameCodecBuilder.frameLogger(Http2FrameLogger(LogLevel.DEBUG))
                    }
                    val frameCodec = frameCodecBuilder.build()
                    ch.pipeline().addLast(sslHandler)
                    ch.pipeline().addLast(frameCodec)

                    ch.pipeline().addLast(Http2MultiplexHandler(RejectPushStreamHandler()))

                    ch.pipeline().addLast(object : ChannelInboundHandlerAdapter() {
                        override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
                            noteInboundActivity()
                            when (msg) {
                                is Http2GoAwayFrame -> {
                                    acceptingNewStreams = false
                                    val reason = msg.content().toString(Charsets.UTF_8).ifBlank { "<no reason given>" }
                                    AppLogger.w(
                                        TAG,
                                        "upstream sent GOAWAY: errorCode=${msg.errorCode()} lastStreamId=${msg.lastStreamId()} reason=\"$reason\"",
                                    )
                                    msg.release()
                                }
                                is Http2SettingsFrame -> {

                                    val announced = msg.settings().maxConcurrentStreams()
                                    if (announced != null) {

                                        val limit = announced.coerceIn(1L, Int.MAX_VALUE.toLong()).toInt()
                                        if (limit != maxConcurrentStreams) {
                                            maxConcurrentStreams = limit
                                            AppLogger.i(
                                                TAG,
                                                "upstream allows $limit concurrent stream(s); new flows will wait " +
                                                    "for a free slot instead of being refused",
                                            )
                                        }
                                    }
                                }
                                is Http2PingFrame -> {

                                    if (msg.ack()) {
                                        if (msg.content() == KEEPALIVE_PING_PAYLOAD) awaitingPingAck = false
                                    } else {
                                        ctx.writeAndFlush(DefaultHttp2PingFrame(msg.content(), true))
                                    }
                                }
                                else -> {

                                    ReferenceCountUtil.release(msg)
                                }
                            }
                        }

                        override fun channelInactive(ctx: ChannelHandlerContext) {
                            acceptingNewStreams = false
                            val detail = "upstream channel to $upstreamHost:$upstreamPort became inactive " +
                                "(local=${ctx.channel().localAddress()})"

                            if (closing) AppLogger.d(TAG, detail) else AppLogger.w(TAG, detail)
                            if (!handshakeDone.isCompleted) {
                                handshakeDone.completeExceptionally(
                                    IOException("Upstream connection closed before completing the TLS/ALPN handshake"),
                                )
                            }
                            super.channelInactive(ctx)
                        }

                        override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {

                            if (closing || handshakeDone.isCompleted) {

                                AppLogger.w(
                                    TAG,
                                    "upstream connection to $upstreamHost:$upstreamPort dropped: ${cause.message} " +
                                        "(usually the network changed underneath it)",
                                )
                            } else {
                                AppLogger.e(
                                    TAG,
                                    "upstream channel error to $upstreamHost:$upstreamPort (often a TLS/ALPN handshake or, " +
                                        "if an upstream proxy is configured, a proxy CONNECT failure)",
                                    cause,
                                )
                            }
                            if (!handshakeDone.isCompleted) handshakeDone.completeExceptionally(cause)
                            ctx.close()
                        }

                        override fun userEventTriggered(ctx: ChannelHandlerContext, evt: Any) {
                            if (evt is SslHandshakeCompletionEvent) {
                                if (evt.isSuccess) {
                                    val negotiated = sslHandler.applicationProtocol()
                                    AppLogger.i(
                                        TAG,
                                        "TLS handshake to $connectHost:$upstreamPort complete, " +
                                            "verified name=$upstreamHost, negotiated ALPN protocol=$negotiated, " +
                                            "local=${ctx.channel().localAddress()}",
                                    )
                                    if (negotiated == ApplicationProtocolNames.HTTP_2) {
                                        handshakeDone.complete(Unit)
                                    } else {
                                        val err = IllegalStateException(
                                            "Upstream did not negotiate HTTP/2 over ALPN (got '$negotiated')",
                                        )
                                        handshakeDone.completeExceptionally(err)
                                        ctx.close()
                                    }
                                } else {
                                    val cause = evt.cause() ?: IllegalStateException("TLS handshake failed with no cause")
                                    AppLogger.e(TAG, "TLS/ALPN handshake to $connectHost:$upstreamPort failed", cause)
                                    handshakeDone.completeExceptionally(cause)
                                }
                            }
                            super.userEventTriggered(ctx, evt)
                        }
                    })
                }
            })

        parentChannel = if (upstreamProxy != null) {
            bootstrap.connect(InetSocketAddress.createUnresolved(connectHost, upstreamPort)).awaitChannel()
        } else {
            bootstrap.connect(connectHost, upstreamPort).awaitChannel()
        }
        handshakeDone.await()
        lastActivityAt = System.currentTimeMillis()
        lastStreamDataAt = System.currentTimeMillis()

        parentChannel?.writeAndFlush(
            DefaultHttp2WindowUpdateFrame(HTTP2_FLOW_CONTROL_WINDOW_BYTES - Http2CodecUtil.DEFAULT_WINDOW_SIZE),
        )
        startKeepalive()
    }

    private fun buildProxyHandler(proxy: UpstreamProxyConfig): ProxyHandler {
        val proxyAddress = InetSocketAddress(proxy.host, proxy.port)
        val hasCredentials = !proxy.username.isNullOrBlank()
        AppLogger.i(
            TAG,
            "chaining upstream connection to $connectHost:$upstreamPort through ${proxy.type} proxy $proxyAddress",
        )
        return when (proxy.type) {
            UpstreamProxyConfig.Type.SOCKS5 -> if (hasCredentials) {
                Socks5ProxyHandler(proxyAddress, proxy.username, proxy.password.orEmpty())
            } else {
                Socks5ProxyHandler(proxyAddress)
            }
            UpstreamProxyConfig.Type.HTTP -> if (hasCredentials) {
                HttpProxyHandler(proxyAddress, proxy.username, proxy.password.orEmpty())
            } else {
                HttpProxyHandler(proxyAddress)
            }
        }
    }

    private fun startKeepalive() {
        keepaliveScope.launch {

            while (isActive && parentChannel?.isActive == true && !closed.get()) {
                delay(KEEPALIVE_CHECK_INTERVAL_MS)
                val now = System.currentTimeMillis()
                val idleFor = now - lastActivityAt
                val ch = parentChannel ?: break
                when {

                    awaitingPingAck && now - pingSentAt >= KEEPALIVE_PING_TIMEOUT_MS -> {
                        AppLogger.w(
                            TAG,
                            "keepalive PING went unanswered for ${now - pingSentAt}ms; closing dead upstream session",
                        )
                        close()
                        break
                    }
                    !awaitingPingAck && idleFor >= KEEPALIVE_IDLE_THRESHOLD_MS -> {
                        awaitingPingAck = true
                        pingSentAt = now
                        ch.writeAndFlush(DefaultHttp2PingFrame(KEEPALIVE_PING_PAYLOAD, false))
                    }
                }
            }
        }
    }

    private fun releaseStreamSlot() {
        if (activeStreams.decrementAndGet() == 0 && !acceptingNewStreams) {
            close()
        }
    }

    private fun tryReserveStreamSlot(): Boolean {
        while (true) {
            val inFlight = activeStreams.get()
            if (inFlight >= maxConcurrentStreams) return false

            if (activeStreams.compareAndSet(inFlight, inFlight + 1)) return true
        }
    }

    private suspend fun reserveStreamSlot(authority: String) {
        if (tryReserveStreamSlot()) return

        val acquired = withTimeoutOrNull(STREAM_SLOT_WAIT_TIMEOUT_MS) {
            while (!tryReserveStreamSlot()) {
                if (!isConnected) {
                    throw IOException("H2UpstreamSession closed while waiting for a free stream slot")
                }
                delay(STREAM_SLOT_POLL_INTERVAL_MS)
            }
            true
        }
        if (acquired == null) {
            throw UpstreamConnectTimeoutException(
                authority = authority,
                message = "Timed out waiting for one of the upstream's $maxConcurrentStreams concurrent " +
                    "stream slots to free up",
                cause = IOException("upstream concurrent stream limit reached"),
            )
        }
    }

    override suspend fun openStream(targetHost: String, targetPort: Int): TunneledStream {

        val parent = parentChannel ?: throw IOException("H2UpstreamSession is not connected")
        if (!parent.isActive) throw IOException("H2UpstreamSession channel is not active")
        if (!acceptingNewStreams) throw IOException("H2UpstreamSession is shutting down (GOAWAY received)")

        val authority = if (targetHost.contains(":")) "[$targetHost]:$targetPort" else "$targetHost:$targetPort"
        val responseHeaders = CompletableDeferred<Unit>()
        val streamInput = NettyStreamInput()

        reserveStreamSlot(authority)

        var handedOff = false
        try {
            val streamChannel = run {
                val streamChannelFuture = Http2StreamChannelBootstrap(parent)

                    .option(ChannelOption.WRITE_BUFFER_WATER_MARK, STREAM_WRITE_WATER_MARK)
                    .handler(object : SimpleChannelInboundHandler<Http2StreamFrame>() {
                        override fun channelActive(ctx: ChannelHandlerContext) {
                            streamInput.attachChannel(ctx.channel() as Http2StreamChannel)
                            super.channelActive(ctx)
                        }

                        override fun channelRead0(ctx: ChannelHandlerContext, frame: Http2StreamFrame) {
                            noteInboundActivity()
                            when (frame) {
                                is Http2HeadersFrame -> {

                                    val statusText = frame.headers().status()?.toString()

                                    val statusCode = statusText?.trim()?.toIntOrNull()
                                    if (statusCode != null && statusCode in 200..299) {
                                        if (!responseHeaders.isCompleted) responseHeaders.complete(Unit)
                                    } else {
                                        val cause = UpstreamConnectRejectedException(
                                            statusCode = statusCode,
                                            authority = authority,
                                            message = "Upstream rejected CONNECT to $authority: status=${statusText ?: "<missing>"}",
                                        )
                                        if (!responseHeaders.isCompleted) responseHeaders.completeExceptionally(cause)
                                        ctx.close()
                                    }
                                }
                                is Http2DataFrame -> {

                                    noteStreamData()
                                    val bytes = ByteArray(frame.content().readableBytes())
                                    frame.content().readBytes(bytes)
                                    streamInput.offerData(bytes)
                                    if (frame.isEndStream) streamInput.offerEnd()
                                }
                                is Http2ResetFrame -> {
                                    val streamId = (ctx.channel() as Http2StreamChannel).stream().id()
                                    val cause = IOException("Upstream reset stream $streamId (errorCode=${frame.errorCode()})")
                                    AppLogger.d(TAG, "upstream reset stream $streamId: errorCode=${frame.errorCode()}")
                                    if (!responseHeaders.isCompleted) responseHeaders.completeExceptionally(cause)
                                    streamInput.offerError(cause)
                                }
                                else -> Unit
                            }
                        }

                        override fun channelInactive(ctx: ChannelHandlerContext) {

                            if (!responseHeaders.isCompleted) {
                                responseHeaders.completeExceptionally(
                                    IOException("Upstream stream closed before CONNECT completed"),
                                )
                            }
                            streamInput.offerEnd()
                            super.channelInactive(ctx)
                        }
                    })
                    .open()

                val ch = try {
                    withTimeout(OPEN_STREAM_TIMEOUT_MS) { awaitStreamChannel(streamChannelFuture) }
                } catch (e: TimeoutCancellationException) {

                    throw UpstreamConnectTimeoutException(
                        authority = authority,
                        message = "Timed out opening HTTP/2 stream channel to $upstreamHost:$upstreamPort",
                        cause = e,
                    )
                }

                val headers = DefaultHttp2Headers().apply {
                    method("CONNECT")
                    authority(authority)

                    add("proxy-authorization", "Bearer $currentBearerToken")
                }
                ch.writeAndFlush(DefaultHttp2HeadersFrame(headers, false))

                try {
                    withTimeout(OPEN_STREAM_TIMEOUT_MS) { responseHeaders.await() }
                } catch (e: TimeoutCancellationException) {
                    ch.close()
                    throw UpstreamConnectTimeoutException(
                        authority = authority,
                        message = "Timed out waiting for CONNECT response from $upstreamHost:$upstreamPort ($authority)",
                        cause = e,
                    )
                }

                ch
            }

            streamChannel.closeFuture().addListener {
                releaseStreamSlot()
            }
            handedOff = true

            return TunneledStream(
                input = streamInput,
                output = NettyStreamOutput(streamChannel),
                close = { streamChannel.close() },
            )
        } finally {

            if (!handedOff) releaseStreamSlot()
        }
    }

    override fun close() {

        if (!closed.compareAndSet(false, true)) return
        closing = true
        keepaliveScope.cancel()
        parentChannel?.close()

        group.shutdownGracefully(0, 1, TimeUnit.SECONDS)
    }

    private class RejectPushStreamHandler : ChannelInitializer<Http2StreamChannel>() {
        override fun initChannel(ch: Http2StreamChannel) {
            AppLogger.w(TAG, "upstream opened an unexpected server-initiated stream ${ch.stream().id()}; closing it")
            ch.close()
        }
    }

    private inner class NettyStreamOutput(
        private val streamChannel: Http2StreamChannel,
    ) : OutputStream() {
        override fun write(b: Int) = write(byteArrayOf(b.toByte()))

        override fun write(b: ByteArray, off: Int, len: Int) {
            if (len <= 0) return
            if (!streamChannel.isActive) throw IOException("Upstream stream is closed")

            noteStreamData()
            val buf = streamChannel.alloc().buffer(len).writeBytes(b, off, len)
            val future = streamChannel.writeAndFlush(DefaultHttp2DataFrame(buf, false))

            if (!streamChannel.isWritable) {
                if (!future.await(WRITE_BACKPRESSURE_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
                    future.cancel(false)
                    throw IOException("Upstream stream stopped accepting data (write timed out)")
                }
                if (!future.isSuccess) {
                    throw IOException("Failed writing to the upstream stream", future.cause())
                }
            } else if (future.isDone && !future.isSuccess) {

                throw IOException("Failed writing to the upstream stream", future.cause())
            }
        }

        override fun close() {

            if (streamChannel.isActive) streamChannel.writeAndFlush(DefaultHttp2DataFrame(true))
        }
    }

    private class NettyStreamInput : InputStream() {
        private sealed class Chunk {
            class Data(val bytes: ByteArray) : Chunk()
            object End : Chunk()
            class Error(val cause: Throwable) : Chunk()
        }

        private val queue = LinkedBlockingQueue<Chunk>()
        private val pendingBytes = AtomicInteger(0)
        private var current: ByteArray? = null
        private var currentPos = 0

        private var pendingTerminal: Chunk? = null
        @Volatile private var finished = false
        @Volatile private var channel: Http2StreamChannel? = null

        fun attachChannel(ch: Http2StreamChannel) {
            channel = ch
        }

        fun offerData(bytes: ByteArray) {
            if (bytes.isEmpty()) return
            queue.put(Chunk.Data(bytes))
            if (pendingBytes.addAndGet(bytes.size) >= HIGH_WATERMARK_BYTES) {
                channel?.config()?.isAutoRead = false
            }
        }

        fun offerEnd() = queue.put(Chunk.End)

        fun offerError(cause: Throwable) = queue.put(Chunk.Error(cause))

        override fun read(): Int {
            val single = ByteArray(1)
            val n = read(single, 0, 1)
            return if (n <= 0) -1 else single[0].toInt() and 0xFF
        }

        override fun read(b: ByteArray, off: Int, len: Int): Int {
            if (len == 0) return 0
            if (finished && current == null) return -1
            var totalRead = 0
            while (totalRead < len) {
                if (current == null || currentPos >= current!!.size) {
                    val chunk = pendingTerminal?.also { pendingTerminal = null }
                        ?: if (totalRead == 0) queue.take() else (queue.poll() ?: break)
                    when (chunk) {
                        is Chunk.Data -> {
                            current = chunk.bytes
                            currentPos = 0
                            val remaining = pendingBytes.addAndGet(-chunk.bytes.size)
                            val ch = channel
                            if (ch != null && remaining <= LOW_WATERMARK_BYTES) {
                                ch.eventLoop().execute { ch.config().isAutoRead = true }
                            }
                        }
                        is Chunk.End -> {
                            if (totalRead > 0) {

                                pendingTerminal = Chunk.End
                                return totalRead
                            }
                            finished = true
                            return -1
                        }
                        is Chunk.Error -> {
                            if (totalRead > 0) {
                                pendingTerminal = chunk
                                return totalRead
                            }
                            finished = true
                            throw IOException("Upstream stream failed", chunk.cause)
                        }
                    }
                }
                val data = current ?: break
                val available = data.size - currentPos
                val toCopy = minOf(len - totalRead, available)
                System.arraycopy(data, currentPos, b, off + totalRead, toCopy)
                currentPos += toCopy
                totalRead += toCopy
                if (currentPos >= data.size) current = null
            }
            return totalRead
        }

        companion object {

            private const val HIGH_WATERMARK_BYTES = 128 * 1024
            private const val LOW_WATERMARK_BYTES = 32 * 1024
        }
    }
}

private suspend fun awaitStreamChannel(future: Future<Http2StreamChannel>): Http2StreamChannel =
    suspendCancellableCoroutine { cont ->
        future.addListener {
            if (future.isSuccess) {
                cont.resume(future.now)
            } else {
                cont.resumeWithException(future.cause() ?: IllegalStateException("Netty future failed with no cause"))
            }
        }
        cont.invokeOnCancellation { future.cancel(false) }
    }

private suspend fun ChannelFuture.awaitChannel(): Channel =
    suspendCancellableCoroutine { cont ->
        addListener { completed ->
            if (completed.isSuccess) {
                cont.resume(channel())
            } else {
                cont.resumeWithException(
                    completed.cause() ?: IOException("Upstream TCP connect failed with no cause"),
                )
            }
        }
        cont.invokeOnCancellation {
            runCatching { channel().close() }
        }
    }

@androidx.annotation.Keep
internal class FoxyNioSocketChannel : io.netty.channel.socket.nio.NioSocketChannel() {
    fun publicJavaChannel(): java.nio.channels.SocketChannel = super.javaChannel() as java.nio.channels.SocketChannel
}