scoop:scoop.tls:0.1.0
src/sync_pump.scoop
Selected production source · src/sync_pump.scoop
1
package scoop.tls3
import scoop.platform.io.*4
import scoop.platform.memory.*5
import scoop.tls.native.*7
internal class SyncPump(8
val engine: TlsEngine,9
val source: ByteSource,10
val sink: ByteSink,11
val input: NativeByteBuffer,12
val output: NativeByteBuffer13
) {14
var progress: Long = 0L16
fun drive(operation: Int, borrow: NativeByteBorrow?): Long {17
progress = 0L18
while (true) {19
val step = nextStep(operation, borrow)20
progress = step.count21
val sent = drain()22
when (step.kind) {23
case Done -> return progress24
case Closed -> {25
if (operation == 1) return 0L26
throw TlsException("TLS protocol", TlsFailureKind.Protocol, 0UL, 0L, 0, "unexpected close_notify")27
}28
case WantRead -> receive()29
case WantVerification -> engine.verify()30
case WantWrite -> if (sent == 0L) throw IllegalStateException(Some("TLS output retry has no pending ciphertext"))31
}32
}33
}35
private fun nextStep(operation: Int, borrow: NativeByteBorrow?): TlsStep {36
@Unsafe { return when (operation) {37
case 0 -> engine.handshake()38
case 1 -> engine.read(borrow!!)39
case 2 -> engine.write(borrow!!)40
case 3 -> engine.shutdown()41
else -> throw IllegalArgumentException(Some("invalid TLS operation"))42
} }43
}45
fun drain(): Long {46
var total = 0L47
while (output.readableBytes > 0L || engine.pendingOutput > 0L) {48
if (output.readableBytes == 0L) {49
output.clear()50
engine.takeCiphertext(output)51
}52
val requested = output.readableBytes53
val sent = sink.writeFrom(output, requested)54
if (sent < 0L || sent > requested) throw IllegalStateException(Some("invalid TLS transport write progress"))55
if (sent == 0L) throw WriteZeroException()56
total += sent57
}58
return total59
}61
private fun receive() {62
input.clear()63
val available = engine.inputCapacity64
if (available == 0L) throw IllegalStateException(Some("TLS input retry has no BIO space"))65
val count = source.readInto(input, available)66
if (count < 0L || count > available) throw IllegalStateException(Some("invalid TLS transport read progress"))67
if (count == 0L) engine.endInput()68
else engine.receiveCiphertext(input)69
}70
}