Scoop API

scoop:scoop.tls:0.1.0

src/stream.scoop

Selected production source · src/stream.scoop

1package scoop.tls
3import scoop.platform.io.*
4import scoop.platform.memory.*
5import scoop.tls.native.TlsEngine
7/**
8 * A synchronous TLS byte stream that owns its transport and native TLS state. Construction
9 * completes the handshake. Operations must not overlap.
10 *
11 * [close] releases local resources; [shutdownGracefully] exchanges TLS close notifications before
12 * closing the transport. A failed I/O operation closes owned resources.
13 */
14public class TlsStream internal constructor(private val pump: SyncPump, private val owner: Closeable)
15 : ByteSource, ByteSink, Closeable {
16 /**
17 * Factories that complete a TLS handshake over an existing duplex transport.
18 */
19 public companion object {
20 // Completes the handshake; ownership transfers after session creation, before buffer allocation.
21 /**
22 * Creates a client session and completes its handshake, verifying the supplied peer
23 * identity. Transport ownership transfers after session creation and before buffer
24 * allocation; later failure closes the transport.
25 */
26 public fun <T> takeOwnershipAsClient(transport: T, context: TlsClientContext, peer: TlsPeerName): TlsStream
27 where T : ByteSource, T : ByteSink, T : Closeable = adoptSync(TlsEngine.client(context, peer), transport)
29 // Completes the handshake; ownership transfers after session creation, before buffer allocation.
30 /**
31 * Creates a server session and completes its handshake. Transport ownership transfers
32 * after session creation and before buffer allocation; later failure closes the transport.
33 */
34 public fun <T> takeOwnershipAsServer(transport: T, context: TlsServerContext): TlsStream
35 where T : ByteSource, T : ByteSink, T : Closeable = adoptSync(TlsEngine.server(context), transport)
36 }
38 private var closed: Boolean = false
39 private var active: Boolean = false
40 /**
41 * Whether local transport, engine, and buffer cleanup has begun.
42 */
43 public val isClosed: Boolean get() = closed
44 /**
45 * The negotiated version and ALPN. Reading this property requires an open, idle stream.
46 */
47 public val connectionInfo: TlsConnectionInfo get() { requireIdle(); return pump.engine.connectionInfo }
49 private fun requireIdle() {
50 if (closed) throw IllegalStateException(Some("TLS stream is closed"))
51 if (active) throw IllegalStateException(Some("TLS stream operation is active"))
52 }
54 internal fun handshake() {
55 requireIdle()
56 active = true
57 try { pump.drive(0, None) }
58 catch (error: Throwable) { abort(error) }
59 finally { active = false }
60 }
62 /**
63 * Reads decrypted bytes into writable buffer space and advances the buffer by the returned
64 * count. A zero count request performs no transfer.
65 */
66 public override fun readInto(buffer: NativeByteBuffer, count: Long): Long = transfer(buffer, count, true)
67 /**
68 * Writes readable plaintext and advances the buffer by the accepted count. A call may accept
69 * only a prefix, at most 16,384 bytes.
70 */
71 public override fun writeFrom(buffer: NativeByteBuffer, count: Long): Long = transfer(buffer, count, false)
73 private fun transfer(buffer: NativeByteBuffer, count: Long, read: Boolean): Long {
74 requireIdle()
75 val available = if (read) buffer.writableBytes else buffer.readableBytes
76 if (count < 0L) throw IllegalArgumentException(Some("negative TLS transfer count"))
77 if (count > available) throw IndexOutOfBoundsException()
78 if (count == 0L) return 0L
79 val prefix = if (!read && count > 16384L) 16384L else count
80 @Unsafe {
81 val borrow = if (read) buffer.borrowWritable(prefix) else buffer.borrowReadable(prefix)
82 active = true
83 try { return pump.drive(if (read) 1 else 2, Some(borrow)) }
84 catch (error: Throwable) { abort(error) }
85 finally { active = false; borrow.complete(pump.progress) }
86 }
87 }
89 /**
90 * Drains pending TLS ciphertext and flushes the underlying byte sink.
91 */
92 public override fun flush() {
93 requireIdle()
94 active = true
95 try { pump.drain(); pump.sink.flush() }
96 catch (error: Throwable) { abort(error) }
97 finally { active = false }
98 }
100 /**
101 * Completes the TLS close handshake, then closes the owned transport and local state. Use this
102 * when the peer must receive an orderly TLS shutdown.
103 */
104 public fun shutdownGracefully() {
105 requireIdle()
106 active = true
107 try { pump.drive(3, None) }
108 catch (error: Throwable) { abort(error) }
109 finally { active = false }
110 closeOwned()
111 }
113 private fun abort(error: Throwable): Nothing {
114 active = false
115 try { closeOwned() }
116 catch (cleanup: Throwable) { throw ResourceUseException(error, cleanup) }
117 throw error
118 }
120 private fun closeOwned() {
121 if (closed) return
122 closed = true
123 val resources: Array<Closeable> = [owner, pump.engine, pump.input, pump.output]
124 when (closeAll(resources)) {
125 case Some(val error) -> throw error
126 case None -> return
127 }
128 }
130 // Releases local resources; use shutdownGracefully for the TLS close handshake.
131 /**
132 * Closes the owned transport and releases local state without performing a TLS close
133 * handshake. It rejects an overlapping stream operation.
134 */
135 public override fun close() {
136 if (active) throw IllegalStateException(Some("TLS stream operation is active"))
137 closeOwned()
138 }
141internal fun closeAll(resources: Array<Closeable>): Throwable? {
142 var failure: Throwable? = None
143 for (resource in resources) {
144 try { resource.close() }
145 catch (error: Throwable) {
146 failure = Some(when (failure) {
147 case None -> error
148 case Some(val primary) -> ResourceUseException(primary, error)
149 })
150 }
151 }
152 return failure