Scoop API

scoop:scoop.tls:0.1.0

src/native/engine.scoop

Selected production source · src/native/engine.scoop

1package scoop.tls.native
3import scoop.crypto.native.cryptoBytes
4import scoop.platform.memory.*
5import scoop.tls.*
7/**
8 * The next action required by the transport-independent [TlsEngine].
9 */
10public enum TlsStepKind {
11 /**
12 * The requested operation completed or transferred plaintext bytes.
13 */
14 Done,
15 /**
16 * Feed additional ciphertext before retrying the operation.
17 */
18 WantRead,
19 /**
20 * Drain pending ciphertext before retrying the operation.
21 */
22 WantWrite,
23 /**
24 * The peer completed the TLS close protocol.
25 */
26 Closed,
27 /**
28 * Run and complete the pending certificate-verification work before retrying.
29 */
30 WantVerification }
31/**
32 * The result of one engine step.
33 *
34 * @property kind The action needed to continue the TLS protocol.
35 * @property count The plaintext byte count transferred by the step.
36 */
37public struct TlsStep(val kind: TlsStepKind, val count: Long)
39/**
40 * A transport-independent TLS state machine with explicit ciphertext input and output. The caller
41 * drives handshake, transfer, verification, and shutdown steps and serializes access to the
42 * engine. Close it to release the native session.
43 */
44public class TlsEngine private constructor(private var handle: ULong) : Closeable {
45 /**
46 * Creates native TLS sessions without owning a network transport.
47 */
48 public companion object {
49 /**
50 * Creates a client engine configured to verify the supplied DNS name or IP address. The
51 * caller must drive the handshake.
52 */
53 public fun client(context: TlsClientContext, peer: TlsPeerName): TlsEngine = TlsEngine(context.newSession(peer))
54 /**
55 * Creates a server engine from a server context. The caller must drive the handshake.
56 */
57 public fun server(context: TlsServerContext): TlsEngine = TlsEngine(context.newSession())
58 }
60 private fun nativeHandle(): ULong {
61 if (handle == 0UL) throw IllegalStateException(Some("TLS engine is closed"))
62 return handle
63 }
65 /**
66 * The number of additional ciphertext bytes the engine can currently accept.
67 */
68 public val inputCapacity: Long get() { @Unsafe { return inputCapacity(nativeHandle()) } }
69 /**
70 * The ciphertext byte count available for draining to the transport.
71 */
72 public val pendingOutput: Long get() { @Unsafe { return pendingOutput(nativeHandle()) } }
73 /**
74 * The negotiated version and ALPN after handshake completion; querying too early throws
75 * [IllegalStateException].
76 */
77 public val connectionInfo: TlsConnectionInfo get() {
78 @Unsafe {
79 val owned = nativeHandle()
80 val version = when (sessionVersion(owned)) {
81 case 0x0303 -> TlsVersion.Tls12
82 case 0x0304 -> TlsVersion.Tls13
83 else -> throw IllegalStateException(Some("TLS handshake is incomplete"))
84 }
85 val alpn = cryptoBytes(sessionAlpn(owned), "read TLS ALPN")
86 return TlsConnectionInfo(version, if (alpn.size == 0L) None else Some(alpn))
87 }
88 }
90 /**
91 * Advances the handshake once and reports whether to feed input, drain output, or perform
92 * certificate verification.
93 */
94 public fun handshake(): TlsStep { @Unsafe { return checkedStep(sessionStep(nativeHandle(), 0, None, 0L), "TLS handshake") } }
95 /**
96 * Advances the TLS close handshake once. The caller continues driving the indicated transport
97 * or verification work.
98 */
99 public fun shutdown(): TlsStep { @Unsafe { return checkedStep(sessionStep(nativeHandle(), 3, None, 0L), "TLS shutdown") } }
101 /**
102 * Takes the pending native verification work. Run it, complete it on this engine, and release
103 * it exactly once; keep the pointer valid throughout those operations.
104 */
105 @Unsafe public fun takeVerification(): Ptr<Unit> =
106 workPointer(takeVerification(nativeHandle()), "take TLS verification")
108 /**
109 * Applies the result of completed verification work to this engine. The caller still owns and
110 * must release the work record.
111 */
112 @Unsafe public fun completeVerification(work: Ptr<Unit>) {
113 tlsValue(completeVerification(nativeHandle(), work), "complete TLS verification")
114 }
116 /**
117 * Runs pending certificate verification synchronously, applies its result, and releases the
118 * native work record even on failure.
119 */
120 public fun verify() {
121 @Unsafe {
122 val work = takeVerification()
123 try { runVerification(work); completeVerification(work) }
124 finally { freeVerification(work) }
125 }
126 }
128 /**
129 * Attempts to decrypt into a nonempty writable native borrow. The caller keeps the borrow
130 * alive and completes it with the actual transferred count.
131 */
132 @Unsafe public fun read(borrow: NativeByteBorrow): TlsStep {
133 if (borrow.length == 0L) throw IllegalArgumentException(Some("TLS engine read requires a nonempty buffer"))
134 return checkedStep(sessionStep(nativeHandle(), 1, borrow.pointer(), borrow.length), "TLS read")
135 }
137 /**
138 * Attempts to encrypt a nonempty readable native borrow, accepting at most 16,384 bytes. The
139 * caller keeps the borrow alive and accounts for the returned count.
140 */
141 @Unsafe public fun write(borrow: NativeByteBorrow): TlsStep {
142 if (borrow.length == 0L) throw IllegalArgumentException(Some("TLS engine write requires a nonempty buffer"))
143 val count = if (borrow.length > 16384L) 16384L else borrow.length
144 return checkedStep(sessionStep(nativeHandle(), 2, borrow.pointer(), count), "TLS write")
145 }
147 /**
148 * Consumes up to the requested readable ciphertext bytes, limited by engine capacity, and
149 * advances the input buffer by the accepted count.
150 */
151 public fun receiveCiphertext(buffer: NativeByteBuffer, requested: Long = buffer.readableBytes): Long {
152 if (requested < 0L || requested > buffer.readableBytes) throw IllegalArgumentException(Some("invalid TLS ciphertext count"))
153 val capacity = inputCapacity
154 val count = if (requested < capacity) requested else capacity
155 if (count == 0L) return 0L
156 @Unsafe {
157 val received = buffer.withReadableBytes { pointer, _ ->
158 @Unsafe { return@withReadableBytes tlsValue(ciphertext(nativeHandle(), 1, pointer!!, count), "feed TLS ciphertext").toLong() }
159 }
160 buffer.skip(received)
161 return received
162 }
163 }
165 /**
166 * Appends up to the requested pending ciphertext bytes to writable buffer space and returns
167 * the amount drained.
168 */
169 public fun takeCiphertext(buffer: NativeByteBuffer, requested: Long = buffer.writableBytes): Long {
170 if (requested < 0L || requested > buffer.writableBytes) throw IllegalArgumentException(Some("invalid TLS ciphertext count"))
171 val pending = pendingOutput
172 val count = if (requested < pending) requested else pending
173 if (count == 0L) return 0L
174 @Unsafe { return buffer.withWritableBytes { pointer, _ ->
175 @Unsafe { return@withWritableBytes tlsValue(ciphertext(nativeHandle(), 0, pointer!!, count), "drain TLS ciphertext").toLong() }
176 } }
177 }
179 /**
180 * Marks the ciphertext transport as ended so subsequent steps can distinguish an orderly TLS
181 * close from truncation.
182 */
183 public fun endInput() { @Unsafe { endInput(nativeHandle()) } }
184 /**
185 * Releases the native session without driving a network shutdown. Repeated closes are allowed.
186 */
187 public override fun close() {
188 val owned = handle
189 handle = 0UL
190 if (owned != 0UL) @Unsafe { sessionFree(owned) }
191 }