nish/net/tls-tcp
TLS 1.3 over TCP (WP34 T2): a pool of server connections on nish:net, each a TlsRecordServer driving a TlsServer, for a program that owns its readiness loop; and TlsTcpClient, one client connection that authenticates the server (nish/net/tls/verify) and is driven by the same kind of loop or, through tlsConnect, readWait and writeAll, by none (its own comment, below, says how).
import {
TLS_TCP_POOL_FULL,
TLS_TCP_TIMED_OUT,
TlsTcpClient,
TlsTcpServer,
tlsConnect,
tlsConnectWith,
} from "nish/net/tls-tcp";
const listener = tcpListen("0.0.0.0", 8443, 128);
const tls = new TlsTcpServer(config, listener, 64);
pollAdd(loop, listener, 1, LISTENER);
// when the listener is readable:
const slot: i32 = tls.accept(random32(), random32());
if (slot >= 0) { pollAdd(loop, tls.fd(slot), 1, slot); }
// when a connection's token comes back:
let wants: i32 = (events & 5) !== 0 ? tls.readable(slot) : tls.writable(slot);
if ((wants & TLS_RECORD_SIGN) !== 0) { wants = tls.signP256(slot, leafKey); }
if ((wants & TLS_RECORD_DATA) !== 0) { tls.read(slot, buf, 0, buf.length); ... }
if ((wants & TLS_RECORD_DONE) !== 0) { tls.close(slot); }
else { pollModify(loop, tls.fd(slot), wants & 3, slot); }
tlsConnect
Opens a TLS 1.3 connection to the server at addr (nish:net's 18-byte form) for serverName, offering alpn, authenticated against the system's roots, and waits in a loop of its own until the handshake is done and the client's last flight sent, or it fails, or timeoutMs milliseconds pass, reading the roots included.
tlsConnectWith
tlsConnect under a config and trust of the caller's.
TlsTcpClient
One TLS 1.3 client connection over TCP: a TlsRecordClient driving a TlsClient on a socket tcpConnect opened, for a program that owns its readiness loop, as TlsTcpServer is for a server.
TlsTcpServer
A pool of TLS 1.3 server connections on one listening socket.
The program is the loop
A function is not a value, so there are no
callbacks: every call answers what the connection wants next as the
TLS_RECORD_* bits of nish/net/tls/record-server, and the low two bits
are exactly the events pollModify takes — readable, writable — so the
program re-arms the descriptor with them after each call. The loop stays
level-triggered and never spins: a connection whose application data the
program has not read stops asking to be read, and one with nothing to send
stops asking to be written. An event with the hang-up bit (4) goes to
readable, which is where a closed or failed socket is noticed.
Slots, built on first use; record buffers, borrowed
The pool's size is a
cap: the constructor builds no slot, and the first accept into a slot
builds its handshake state and keys (TLS-3) and keeps them, so a pool sized
for its peak costs at start-up only what does not depend on the size.
accept hands the next connection the slot closed last, or failing that the
next never used, and reuses it once the program closes it (WP34 N9).
The record buffers — the bytes to send, the plaintext waiting for the
program, the record being opened and the record being read — are borrowed
from pools this server owns while a connection uses the slot, and given back
zeroed (BufferPool.giveSecret) when it ends, so a free slot holds none of
them ("What moves between connections" in docs/security/tls.md). When every
slot is busy a new connection is accepted and closed at once, so the listener
does not stay readable; the program sees TLS_TCP_POOL_FULL.
Each slot keeps its own TlsServer, which accept restarts for the
connection, so neither the handshake nor application data allocates anything
that outlives a call: a thousand connections through one slot leave
Arena.mark() where the first left it, under every suite (TLS-3 in
docs/security/tls.md, tests/link/net_tls_memory).
Randomness is the caller's
accept takes the 32-byte server random and
the 32-byte x25519 private key the handshake uses, as TlsServer does, so a
test replays RFC 8448's trace and a server draws them with
crypto.getRandomValues. accept copies both into the slot and wipes the
caller's key array, so one buffer of each refilled for every accept is
safe, and refuses either when it is not 32 bytes before taking a connection;
the slot's copy of the key is wiped once the ServerHello is written, when the
handshake fails, or when the slot is closed.
Signing is the caller's, as TlsServer's is: signP256 signs the
CertificateVerify with a P-256 key the caller holds as a Secret and borrows
for the call, and signatureInput / sign hand the input out and take any
signature back.
Resumption is opt-in, and its keys are the caller's
After
enableTickets, a slot whose interest says TLS_RECORD_TICKET waits on
the program: in the handshake, resume reads the ClientHello's tickets
under the current and previous ticket keys and a strike register the
program lends for the call, and answers the hello resumed or in full; once
the connection is open, issue seals it one ticket. The pool keeps no
ticket key and no register of its own (docs/security/tls.md,
"Resumption").
read, write and close answer as nish:net's calls do — a count, 0
at the end of the stream, -11 to wait — so a program written against a
plain socket moves over with the slot in place of the descriptor.
close frees the slot at once; shutdown sends the close_notify as the
socket takes it, and the slot is done when its interest says so.
A closed connection lingers until the client hangs up
Once a connection
the server closed has sent everything, the slot shuts the socket's write side
— the client reads the response, the close_notify and then the end of the
stream — and reads and throws away what the client still sends, until its own
end of stream, before its interest says TLS_RECORD_DONE (RFC 9112 §9.6's
staged close).
A socket closed with the client's bytes unread, or that the client writes to
after the close, answers with a TCP reset, and a client may report that reset
instead of the response it was sent: Chromium's ERR_CONNECTION_RESET after
an HTTP/2 GOAWAY, when its SETTINGS acknowledgement crossed the server's
close. A lingering slot holds no key and no record buffer, asks only to be
read, and gives up past TLS_TCP_LINGER_LIMIT bytes.
A connection that failed, whose client sent its own close_notify (it writes
nothing after it, RFC 8446 §6.1) or whose client's stream had already ended,
is done at once. A client that never hangs up keeps its slot, as one that
never sends does, until expire finds it idle past idleTimeout
(docs/security/tls.md, TLS-6 and TLS-4).
Written from RFC 8446 and docs/LANGUAGE.md's nish:net, not ported from
another implementation.
Functions
tlsConnect
Opens a TLS 1.3 connection to the server at addr (nish:net's 18-byte
form) for serverName, offering alpn, authenticated against the system's
roots, and waits in a loop of its own until the handshake is done and the
client's last flight sent, or it fails, or timeoutMs milliseconds pass,
reading the roots included. Answers the client either way: open() says
whether it opened; otherwise failure() says why — the TCP failure, the
alert, or TLS_TCP_TIMED_OUT, the client closed.
Nothing is looked up: to reach a name, resolve it first with nish/net/dns's
resolveHost; the name the certificate must carry is always serverName,
never one taken from addr. The open client's socket is in no loop: the
program adds it to its own, or uses writeAll and readWait. The roots are
read on every call; a program that connects often reads them once with
tlsClientSystemTrust and passes them to tlsConnectWith.
const tlsConnect: (
addr: u8[],
serverName: string,
alpn: string[],
timeoutMs: i32,
) => TlsTcpClient
addru8[]requiredThe server's address and port in nish:net's 18-byte form.
serverNamestringrequired
The name the server's certificate must carry, sent as server_name unless it is an
IP literal.
alpnstring[]requiredThe ALPN protocols to offer, most preferred first, each 1 to 255 bytes; empty offers none.
timeoutMsi32requiredHow long the whole connect may take, in milliseconds on the monotonic clock.
returnsTlsTcpClientThe client, open or failed; the caller owns it and calls close when done with it.
tlsConnectWith
tlsConnect under a config and trust of the caller's.
const tlsConnectWith: (
addr: u8[],
config: TlsClientConfig,
trust: TlsClientTrust,
timeoutMs: i32,
) => TlsTcpClient
addru8[]requiredThe server's address and port in nish:net's 18-byte form.
configTlsClientConfigrequiredThe server name, ALPN protocols and the rest of the ClientHello.
trustTlsClientTrustrequiredThe roots the server's chain is checked against, such as one tlsClientSystemTrust read.
timeoutMsi32requiredHow long the whole connect may take, in milliseconds on the monotonic clock.
returnsTlsTcpClientThe client, open or failed; the caller owns it and calls close when done with it.
Classes
TlsTcpClient
One TLS 1.3 client connection over TCP: a TlsRecordClient driving a
TlsClient on a socket tcpConnect opened, for a program that owns its
readiness loop, as TlsTcpServer is for a server.
const client = new TlsTcpClient(addr, new TlsClientConfig("example.com", ["h2"]), trust);
pollAdd(loop, client.fd(), client.interest() & 3, TOKEN);
// when the token comes back:
let wants: i32 = (events & 5) !== 0 ? client.readable() : client.writable();
if ((wants & TLS_RECORD_DATA) !== 0) { client.read(buf, 0, buf.length); ... }
if ((wants & TLS_RECORD_DONE) !== 0) { client.close(); }
else { pollModify(loop, client.fd(), wants & 3, TOKEN); }
The server is always authenticated. When the handshake reaches the
server's certificate chain and CertificateVerify, the client gives its own
verdict at once (tlsClientAuthenticate in nish/net/tls/verify) under
trust and the wall clock, before it reads the server's Finished, so
interest never says TLS_RECORD_AUTH and there is no way to open a
connection to a server the trust does not vouch for. A refusal fails the
connection with its alert sent: failure() names it.
Randomness is the CSPRNG's. The client random and both ephemeral keys
(x25519, and P-256 for a server that asks for that group) are drawn from
crypto.getRandomValues in the constructor; TlsClient copies the keys
into its own Secrets and the arrays they were drawn into are zeroed.
The socket is still connecting when the constructor returns, so the first
interest is writable alone; the first event on it, writable or a hang-up,
says how the connection went (connectResult), and a socket that did not
connect leaves the client done, its failure in failure().
class TlsTcpClient
| Member | |
|---|---|
new TlsTcpClient(addr: u8[], config: TlsClientConfig, trust: TlsClientTrust) |
A connection to the server at addr (nish:net's 18-byte form, which netAddress writes) under config, authenticated against trust. The name the certificate must carry is config.serverName, never one taken from addr. The ClientHello is sealed here and waits for the socket. |
conn: TlsRecordClient |
The TLS record layer over the socket: its tls is the handshake, read for the negotiated suite and alpnChosen. |
close(): void |
Ends the connection at once: a close_notify unless it already failed or closed, one attempt to send what is left, every key wiped and the socket closed, which also takes it out of every loop. |
failure(): i32 |
Why a failed connection failed: the TCP failure when TCP did not connect, else the alert (TlsRecordClient.failure). |
fd(): i32 |
The socket, for pollAdd; -1 when there is none. |
interest(): i32 |
What the connection wants now, as TLS_RECORD_* bits, without touching the socket. |
keyUpdate(requestPeer: boolean): i32 |
Sends a KeyUpdate, asking the server for one too when requestPeer; answers as TlsRecordClient.keyUpdate. |
open(): boolean |
Whether the handshake is done and the server authenticated, so application data flows. |
read(buf: u8[], off: i32, len: i32): i32 |
Application data from the server into buf[off .. off + len): the count, 0 at the end of its stream, -11 when nothing is waiting, -104 once the connection has failed, as TlsRecordClient.read says, and -32 once close has run. What reading makes room for is answered and sent here; re-arm with interest(). |
readable(): i32 |
The socket is readable, or hung up: reads it until it would block or the connection has no room, handing each read to the connection, then sends what that produced. Answers the interest. |
readWait(buf: u8[], off: i32, len: i32, timeoutMs: i32): i32 |
Application data from the server, waiting for it up to timeoutMs milliseconds in a loop of the client's own, for a program with no loop: the count, 0 at the end of the server's stream, TLS_TCP_TIMED_OUT when nothing came in time (the connection stays usable), -104 once it has failed, -32 once it is done otherwise, or the loop's failure. It drives the handshake too, so it may follow new TlsTcpClient directly. |
sending(): boolean |
Whether sealed bytes are still waiting for the socket. |
shutdown(): i32 |
Closes the client's side (§6.1): a close_notify after whatever is already written, sent as the socket takes it. The client does not wait for the server's own close_notify: data already read off the socket still reads, and once the close_notify is sent the interest says TLS_RECORD_DONE and readWait answers -32; call close then. Answers the interest. |
writable(): i32 |
The socket is writable: on the first event, how the connection went; then sends what the connection holds. Answers the interest. |
write(data: u8[], off: i32, len: i32): i32 |
Application data for the server, data[off .. off + len): seals as much as fits and sends what the socket takes, and answers how much was taken, -11 when nothing fits yet or the handshake is under way, -32 once the client has closed, as TlsRecordClient.write says. |
writeAll(data: u8[], off: i32, len: i32, timeoutMs: i32): i32 |
Writes all of data[off .. off + len) and waits up to timeoutMs milliseconds, in a loop of the client's own, until the socket has taken every byte of it: len, or — some of it perhaps sent — TLS_TCP_TIMED_OUT, -32 when the client had closed or failed before the call, -104 when the connection fails during it, -22 for a window outside data, or the loop's failure. It drives the handshake too, so it may follow new TlsTcpClient directly. A timed-out call does not say how much was sent, and the same bytes written again would reach the server twice: once the handshake is done, a timeout leaves the stream unusable, and the client is for close. |
TlsTcpServer
A pool of TLS 1.3 server connections on one listening socket. slots are
the indices accept answers, from 0 to the pool's size; a slot is the
program's from accept until it calls close, and its descriptor is
fd(slot).
class TlsTcpServer
| Member | |
|---|---|
new TlsTcpServer(config: TlsServerConfig, listener: i32, size: i32) |
A pool of size slots, at least one, serving config on listener, a socket tcpListen made. No slot is built here: a slot's handshake state and its server random are allocated by the first accept into it and kept, and its record buffers are borrowed from pools while a connection uses them, so a pool sized for a peak costs at start-up only the read scratch, the signer and the empty pools. |
connections: TlsRecordServer[] |
The connections built so far, slot k's at k: one per slot ever accepted into. connection never adds to it; a slot never built reads one shared vacant connection instead. |
fds: i32[] |
Each slot's descriptor, or -1 while the slot is free, for the slots accepted into so far: its length is the high-water mark, and a slot past it has never been used. |
free: i32[] |
The slots closed since they were used, a stack whose top accept takes before it builds a slot past the high-water mark, so finding one costs the same with every slot free as with all but one busy. |
idleTimeout: i32 |
How long, in milliseconds, a slot may go without activity before expire closes it: a client that opens a connection and sends nothing, stalls its handshake, or never hangs up after the close holds its slot this long and no longer (docs/security/tls.md, TLS-4). 60 seconds by default, as nish/net/http1-server's idleTimeout; 0 or less turns the timeout off. |
peer: u8[] |
The last accepted peer's address, in nish:net's 18-byte form. |
pools: TlsRecordPools |
The pools every slot borrows its record buffers from, each with a ceiling of one per slot: lent() is 0 once every connection has ended, and made() is the most connections that were ever open at once. |
randoms: u8[][] |
Each slot's own copy of its connection's server random: TlsServer keeps the array it is given and writes it into the ServerHello only once the ClientHello arrives, so the program's array may be refilled for the next one. The ephemeral key needs no copy here: TlsServer.restart copies it into the server's own Secret and wipes the array it was handed. |
accept(serverRandom: u8[], ephemeralPrivate: u8[]): i32 |
Accepts the next waiting connection into a free slot and starts its handshake with serverRandom and ephemeralPrivate (32 bytes each), and answers the slot. The peer's address is in peer. Both arrays are copied into the slot, which reads them only when the ClientHello arrives, and the key's array is then wiped, so the program may refill one buffer of each for every call. Answers -11 when no connection is waiting, TLS_TCP_POOL_FULL when one was but every slot is busy (it is closed), or tcpAccept's own failure; and TLS_RECORD_INVALID (-22), before any connection is taken, for a random or key that is not 32 bytes. On any answer but a slot both arrays are left as they were. |
build(): TlsRecordServer |
The next slot's connection and server random, for the slot built next. Called by accept alone, as the pool's high-water mark rises: slot k's entry must sit at index k of connections and randoms. Its handshake is never given a ClientHello: accept restarts it for a connection with real randomness, and every later connection reuses its state. |
busy(): i32 |
How many slots hold a connection. |
close(slot: i32): void |
Ends slot's connection and frees the slot at once: a close_notify unless the connection already failed or closed, one attempt to send what is left, every key wiped, and the descriptor closed, which also takes it out of every loop. A program that must know every byte and the close_notify arrived calls shutdown instead, and close once the slot's interest says TLS_RECORD_DONE. |
connection(slot: i32): TlsRecordServer |
The connection in slot: its state, its handshake (tls: suite, ALPN, server name) and the alerts sent and received. A free slot answers the last connection it held. A slot never accepted into answers one shared vacant connection, failed, as a free slot does, and builds no slot; a slot out of range names slot 0's. |
enableTickets(): void |
Turns session resumption on for every slot (TlsServer.enableTickets): from the next accept, a connection offering a ticket, or one that may be issued one, says TLS_RECORD_TICKET in its interest. A slot built later is built with them on. |
expire(now: i64): i32 |
Closes, as close does, every slot that has had no activity for longer than idleTimeout at now, and answers how many it closed. The pool reads no clock of its own for this: a program calls it from its loop, between pollWaits whose timeout is at most idleTimeout, so a slot idles out within about twice the timeout. Call it once a batch of events from pollWait has been dispatched, not in the middle of one: an event already taken for a slot this closes would otherwise be read as the next connection's, once accept reuses the slot. It is an idle limit, not a handshake deadline: a client that sends a byte inside every idleTimeout keeps its slot. |
fd(slot: i32): i32 |
The descriptor of slot, for pollAdd; -1 for a free or unknown slot. |
flush(slot: i32): i32 |
Writes the connection's output until the socket would block or it is all sent, and answers its interest; once the connection is over and the program has read what the client sent, the slot lingers (lingering). A free slot answers TLS_RECORD_DONE. |
holds(slot: i32): boolean |
Whether slot is a slot of this pool that holds a connection. |
interest(slot: i32): i32 |
What slot's connection wants now, without touching the socket; TLS_RECORD_DONE for a free slot. |
issue(slot: i32, key: Secret<u8[]>, info: TlsTicketKeyInfo, now: i64): i32 |
While slot's interest says TLS_RECORD_TICKET on an open connection: seals one ticket under the borrowed key and sends its NewSessionTicket (TlsRecordServer.issue). Answers the slot's interest. |
keyUpdate(slot: i32, requestPeer: boolean): i32 |
Sends a KeyUpdate on slot, asking the client for one too when requestPeer; answers as TlsRecordServer.keyUpdate. |
lingering(slot: i32): boolean |
Whether slot lingers: its connection is over and it waits for the client to hang up. A carrier's idle clock does not move for what a lingering slot drains, so its idle timeout bounds the wait. |
read(slot: i32, buf: u8[], off: i32, len: i32): i32 |
Application data from slot's client into buf[off .. off + len): the count, 0 at the end of its stream, -11 when nothing is waiting, -104 once the connection has failed, as TlsRecordServer.read says. Reading makes room, and the records that were waiting for it may be handled and answered (a KeyUpdate), which is sent here; the connection may then want the socket read again, so re-arm it with interest(slot). |
readable(slot: i32): i32 |
The socket of slot is readable: reads it until it would block or the connection has no room, handing each read to the connection, then sends what that produced. Answers the connection's interest, or, while the slot lingers (lingering), TLS_RECORD_WANT_READ until its linger is over and then TLS_RECORD_DONE; a free slot answers TLS_RECORD_DONE. |
resume(slot: i32, current: Secret<u8[]>, currentInfo: TlsTicketKeyInfo, previous: Secret<u8[]>, previousInfo: TlsTicketKeyInfo, strikes: TlsTicketStrikes, now: i64): i32 |
While slot's interest says TLS_RECORD_TICKET in the handshake: reads its ClientHello's tickets under current and previous, with what each info says of them, records the one it resumes in strikes, and sends the flight that answers the hello, resumed or in full (TlsRecordServer.resume). The keys and the register are borrowed for the call. Answers the slot's interest. |
shutdown(slot: i32): i32 |
Closes the server's side of slot's connection (§6.1): a close_notify after whatever is already written, sent as the socket takes it. The slot stays the program's until its interest says TLS_RECORD_DONE — every byte is sent and, once the slot lingers (lingering), the client has hung up — and the program calls close. Meanwhile the interest asks for the socket to be read. Answers the interest. |
sign(slot: i32, signature: u8[]): i32 |
Hands slot the signature over signatureInput(slot), seals the rest of its flight and sends it. Answers its interest. |
signatureInput(slot: i32): u8[] | null |
What slot's CertificateVerify signs, while its interest says TLS_RECORD_SIGN; null otherwise. |
signP256(slot: i32, key: Secret<u8[]>): i32 |
Signs slot's CertificateVerify with the P-256 private key key and hands it over, as sign does, through the pool's TlsP256Signer, so a handshake's signature keeps nothing. The key is borrowed: the caller made the Secret, and wipes it. A malformed key fails the connection with internal_error. |
size(): i32 |
How many slots the pool has, built or not. |
writable(slot: i32): i32 |
The socket of slot is writable: sends what the connection holds. Answers its interest. |
write(slot: i32, data: u8[], off: i32, len: i32): i32 |
Application data for slot's client, data[off .. off + len): seals as much as fits and sends what the socket takes, and answers how much was taken, -11 when nothing fits yet or the handshake is under way, -32 once the server has closed, as TlsRecordServer.write says. |
Constants
-105
TLS_TCP_POOL_FULL: i32
What accept answers when every slot is busy: the connection was accepted and closed. Linux's ENOBUFS.
-110
TLS_TCP_TIMED_OUT: i32
What tlsConnect answers when the connection did not open within its timeout. Linux's ETIMEDOUT.

