Scoop API

scoop:scoop.tls:0.1.0

src/context.scoop

Selected production source · src/context.scoop

1package scoop.tls
3import scoop.crypto.PrivateKey
4import scoop.crypto.native.*
5import scoop.crypto.x509.*
6import scoop.platform.fs.*
7import scoop.tls.native.*
9/**
10 * Reusable client configuration containing trust roots, protocol options, and an optional client
11 * identity. Close the context when no more sessions will be created.
12 *
13 * System trust loading is synchronous here. Event-loop code can use
14 * `scoop.tls.asyncio.openTlsClientContext` to offload that work.
15 */
16public class TlsClientContext private constructor(private val state: ContextState) : Closeable {
17 /**
18 * Factories for client contexts backed by external trust data.
19 */
20 public companion object {
21 internal fun takeOwnership(handle: ULong): TlsClientContext = TlsClientContext(ContextState(handle))
23 /**
24 * Reads a PEM CA file synchronously and builds a client context from its trust store. The
25 * returned context owns its native state and must be closed.
26 */
27 public fun fromCaFile(path: Path, options: TlsOptions = TlsOptions(), identity: TlsIdentity? = None): TlsClientContext =
28 TrustStore.fromPem(path.readText()).use { store -> TlsClientContext(store, options, identity) }
29 }
31 public constructor(trustStore: TrustStore, options: TlsOptions = TlsOptions(), identity: TlsIdentity? = None)
32 : this(storeState(trustStore, options, identity)) {}
34 public constructor(trust: TlsTrustSource = TlsTrustSource.System, options: TlsOptions = TlsOptions(), identity: TlsIdentity? = None)
35 : this(trustState(trust, options, identity)) {}
37 internal fun newSession(peer: TlsPeerName): ULong {
38 val (kind, bytes) = peerData(peer)
39 return state.withHandle { handle ->
40 @Unsafe { return@withHandle bytes.withDataPointer { pointer, count ->
41 @Unsafe { return@withDataPointer tlsValue(sessionNew(handle, 0, kind, Some(pointer), count), "create client TLS session") }
42 } }
43 }
44 }
45 /**
46 * Releases the context's native reference. New sessions cannot be created afterward; repeated
47 * closes are allowed.
48 */
49 public override fun close() { state.dispose() }
52/**
53 * Reusable server configuration built from a certificate chain, matching private key, and protocol
54 * options. The first certificate is the server leaf certificate. Close the context when no more
55 * sessions will be created.
56 */
57public class TlsServerContext private constructor(private val state: ContextState) : Closeable {
58 public constructor(certificates: List<Certificate>, privateKey: PrivateKey, options: TlsOptions = TlsOptions())
59 : this(serverState(certificates, privateKey, options)) {}
61 internal fun newSession(): ULong = state.withHandle { handle ->
62 @Unsafe { return@withHandle tlsValue(sessionNew(handle, 1, 0, None, 0L), "create server TLS session") }
63 }
64 /**
65 * Releases the context's native reference and prevents creation of further sessions.
66 */
67 public override fun close() { state.dispose() }
70private fun trustState(trust: TlsTrustSource, options: TlsOptions, identity: TlsIdentity?): ContextState {
71 when (trust) {
72 case Store(val store) -> return storeState(store, options, identity)
73 case System -> @Unsafe {
74 val work = prepareSystemContext(options, identity)
75 try { runSystemContext(work); return ContextState(takeSystemContextHandle(work)) }
76 finally { freeSystemContext(work) }
77 }
78 }
81private fun storeState(trustStore: TrustStore, options: TlsOptions, identity: TlsIdentity?): ContextState {
82 @Unsafe { return ContextState(clientHandle(trustStoreHandle(trustStore), options, identity)) }
85internal fun clientHandle(store: ULong, options: TlsOptions, identity: TlsIdentity?): ULong {
86 val alpn = encodeOptions(options)
87 @Unsafe {
88 val handle = newContext(false, options, alpn, store)
89 try {
90 identity?.configure(handle)
91 return handle
92 } catch (error: Throwable) {
93 contextFree(handle)
94 throw error
95 }
96 }
99private fun serverState(certificates: List<Certificate>, privateKey: PrivateKey, options: TlsOptions): ContextState {
100 val alpn = encodeOptions(options)
101 return TlsIdentity(certificates, privateKey).use { identity ->
102 val handle = newContext(true, options, alpn, 0UL)
103 try {
104 identity.configure(handle)
105 ContextState(handle)
106 } catch (error: Throwable) {
107 @Unsafe { contextFree(handle) }
108 throw error
109 }
110 }
113private fun newContext(server: Boolean, options: TlsOptions, alpn: Array<Byte>, store: ULong): ULong {
114 @Unsafe { return alpn.withDataPointer { pointer, count ->
115 @Unsafe { return@withDataPointer tlsValue(contextNew(if (server) 1 else 0, versionCode(options.minimum), versionCode(options.maximum), pointer, count, store), "create TLS context") }
116 } }
119private class ContextState(private var handle: ULong) : Disposable {
120 private val held: AtomicBoolean = AtomicBoolean(false)
122 private fun <T> locked(block: () -> T): T {
123 while (!held.compareAndSet(false, true, MemoryOrder.Acquire, MemoryOrder.Relaxed)) { }
124 try { return block() }
125 finally { held.store(false, MemoryOrder.Release) }
126 }
128 fun <T> withHandle(block: (ULong) -> T): T = locked {
129 if (handle == 0UL) throw IllegalStateException(Some("TLS context is closed"))
130 block(handle)
131 }
133 public override fun dispose() {
134 locked {
135 val owned = handle
136 handle = 0UL
137 if (owned != 0UL) @Unsafe { contextFree(owned) }
138 Unit
139 }
140 }