Skip to content
You are reading next, which describes the unreleased compiler. Khora is unstable before v1: syntax, standard-library APIs and behavior may change. The current release is documented under v0.4.

std::net::socket

Sockets: listening, connecting, and moving bytes.

Three files and one module – socket_linux.kh, socket_macos.kh and socket_windows.kh – of which exactly one is ever in a build; khora_db::selected_for_target is the rule and the file’s name is where it is written. The API below is the same on all three, and the sections at the end of this page are what differs underneath it.

No struct crosses the boundary. bind wants a sockaddr_in, which is sixteen bytes; those sixteen bytes are laid out in Khora, in an Array<U8>, and lent as a Ptr for exactly the duration of the call. That is what The ffi design note says a pointer is for, and it is why binding a socket needs nothing added to the runtime.

Nothing to start up, the handle is a small int rather than a pointer-sized one, and the call that closes it is close.

Two differences from Linux, both of them BSD’s rather than Apple’s: a sockaddr_in begins with a length byte where the Linux one puts the low half of the family, and the socket-option numbers are the BSD ones. Everything else – the calls, the sizes, the byte order – is the same, which is why this file is otherwise a copy of socket_linux.kh.

A copy, and that is the mechanism working as designed. A file suffix selects a whole file, so a target that differs in two lines still needs a file of its own. _posix exists for the case where Linux and macOS agree completely, and sockets are not that case. The cost is that a fix to one of these usually belongs in both.

The Berkeley names with Winsock’s differences: WSAStartup before anything else – which is what start is for, and why it is not a no-op here – closesocket rather than close, and a SOCKET that is a pointer-sized handle rather than a small int.

Types: SocketError

Functions: invalid_handle · start · listen_on · accept_on · set_receive_timeout · set_deadline · expired · timed_out · receive · transmit · connect_to · connect_by · accepted_open · connected_to · transmit_bytes · shut · receive_now · nothing_yet

derive(Show, Eq)
pub type SocketError =
| Denied(host: String)
| Unreachable(host: String)
| TimedOut(host: String);

Why connect_to, connect_by or listen_on has no socket to give.

What this prevents: a refusal read as a socket. A failure answered as a negative number is a failure every caller has to remember to test for, and one that tests the wrong number carries on with a handle that is not one. Raised, it cannot be missed, and the handle a connect does give back is always a connected socket. listen_on raises only the refusal: a bind the operating system refuses is still invalid_handle.

host is name:port, as the caller wrote the name, which is what a grant in [permissions] network is written against; for listen_on it is 0.0.0.0:<port>, the address a grant in [permissions] listen covers.

The value does not say which key refused it; the call does. A refused connect_to or connect_by is [permissions] network, and a refused listen_on is [permissions] listen, and Denied(0.0.0.0:8080) prints the same from either. A caller that reports one should name the key from the call it made.

| Denied(host: String)

The manifest does not grant this, so nothing was looked up, dialed or bound: from a connect, [permissions] network does not grant host; from listen_on, [permissions] listen does not grant the address.

Its own case rather than Unreachable, for the reason IoError::Denied is: Unreachable sends the reader to DNS or a firewall, and this one is a line in khora.toml.

| Unreachable(host: String)

The name did not resolve, or nothing at any address it resolved to accepted the connection.

| TimedOut(host: String)

The deadline given to connect_by passed before the connection was made.

Only when the deadline is what ended it, as the runtime reports it, so a refusal that arrives in the deadline’s last millisecond is still Unreachable. Separate because a caller acts on it differently: a host that refused may refuse again, while a call that ran out of time mostly wants a longer budget.

pub fn invalid_handle() -> Int

A failed call returns -1, and a handle is never negative.

pub fn start() -> Bool

Nothing to start on Linux and macOS, where this is true and no more.

It is here because the Windows file’s start is not a no-op: Winsock has to be told which version of itself to be, once per process, and a caller that skipped this would work everywhere except there. Call it anyway.

pub fn listen_on(port: Int) -> Int raises SocketError

A socket listening on port on every IPv4 interface, or invalid_handle when the bind or the listen fails or port is not 0 to 65535.

[permissions] listen governs this, and is checked before anything is made, against 0.0.0.0:<port>: the address as it is bound, every interface, so 8080 and 8000-8099 in a manifest cover it. Port 0, which lets the operating system choose, is covered by 0 or * alone. A refusal raises SocketError::Denied with that address – the same case a refused connect raises, so the key to change is listen because this is the call that raised it – and no socket is made, so nothing is bound and the port stays free.

A port outside 0 to 65535 binds nothing, under any grant: it is not a port, and the sixteen bits a socket address holds would have bound another one (70000 is 4464) that * then covered.

Nothing that can stop runs after the socket is made, so a fiber canceled inside this call either has no socket yet or gets it back, and acquire(listen_on(port)!, fn s => shut(s)) always closes what it opened. The socket is made last, inside the lambdas that lend the two buffers it needs, because each of those lambdas checks for a cancellation when it is entered. The check raises before either.

pub fn accept_on(server: Int) -> Int

Waits for a connection. invalid_handle if the wait failed.

pub fn set_receive_timeout(handle: Int, millis: Int) -> Bool

How long a read will wait before giving up, in milliseconds.

See the note on the Windows one for why a server cannot do without it.

No longer SO_RCVTIMEO, and it could not be. The kernel’s option applies to a call that would have blocked, and a socket the reactor drives never has one — so it goes silently inert the moment the socket is prepared, and the slow client it exists to shed would park a fiber for ever. The runtime keeps the deadline and a scheduler timer enforces it. A read that runs out still comes back negative, which is what every caller here already treats as a connection to give up on.

pub fn set_deadline(handle: Int, deadline: Int) -> Bool

Holds every later read and write on handle to clock.monotonic_millis() reaching deadline. Negative clears it.

One bound for a whole exchange, where set_receive_timeout bounds each read on its own and is renewed by every byte, so a peer that sends one byte a second never trips it. Both apply when both are set: a read gives up at whichever comes first, and comes back negative.

pub fn expired(handle: Int) -> Bool

Whether the deadline from set_deadline is what ended a read or write on this connection.

The read’s own account, not the clock’s. A read that came back negative just after the deadline may have failed for another reason – the peer reset the connection in the last millisecond – and a caller telling a timeout from a broken peer by the time would call that a timeout. This says what the read itself gave up on. It stays true until the deadline is set again.

pub fn timed_out(handle: Int) -> Bool

Whether a limit is what ended a read or write on this connection: the per-read limit from set_receive_timeout or the deadline from set_deadline.

expired answers for the deadline alone. A connection held to a per-read limit and nothing else needs this one to tell that limit running out from a peer that closed or reset, which are a negative read too. Setting either limit again starts the account again.

pub fn receive(connection: Int, buffer: Array<U8>) -> Int

Reads what has arrived into buffer, and says how many bytes that was.

Zero means the other end closed; negative means the read failed.

pub fn transmit(connection: Int, text: String) -> Int

Writes all of text, waiting for room when the peer is slow, and says how many bytes went: every one of them, or a negative number if the write failed. After a failure some of text may have gone, so the connection is no longer in step with its peer.

A peer that has reset the connection (a killed client, a load balancer) is a failed write like any other: the write returns a negative number, and no SIGPIPE stops the program.

pub fn connect_to(host: String, port: Int) -> Int raises SocketError

Opens a connection to host on port, and answers the connected socket.

Raises SocketError::Denied when [permissions] network does not grant the host, and SocketError::Unreachable when the name does not resolve or nothing at any of its addresses accepts. Every failure raises, so the handle that comes back is always a socket and no caller has a number to test.

The first thing here that starts a conversation. Everything else in this module grew from serving: listen_on, accept_on, and nothing that dials. A database driver is the first caller that needs the other direction.

[permissions] network is checked first, against host:port as written, with the rule HttpClient::send uses: a grant with no port covers every port, and * spans dots. A refused host is not looked up and not dialed, so nothing on the network hears what the program wanted.

host may be a name or an address, and an IPv6 address may be written in brackets as a URL writes it – [::1] – or without; [::1]:5432 in a manifest covers both. Resolution, address family and the platform’s own resolver are the runtime’s, which is why this is one extern rather than getaddrinfo and two sockaddr layouts written three times. The ffi design note is the boundary and khora_net_connect is on the far side of it. Every address the name resolves to is tried in turn, and the first that accepts is the connection.

A cancellation point, and it costs the fiber’s worker nothing while it waits. The connect waits on the reactor, as accept_on does, so a fiber canceled while dialing a host that never answers stops at once rather than when the operating system gives up, which can be minutes. A name lookup cannot be waited on that way; it runs on the blocking pool, and a canceled caller stops waiting for it and leaves it to finish alone.

pub fn connect_by(host: String, port: Int, deadline: Int) -> Int raises SocketError

connect_to, giving up once clock.monotonic_millis() reaches deadline, which raises SocketError::TimedOut.

The deadline covers the lookup and the connect. It is an instant rather than a length, so that a caller with one budget for several steps hands each the same number. Negative means none. The connection that comes back carries no deadline; set_deadline puts one on it.

[permissions] network governs this, as it does connect_to: a refusal is SocketError::Denied before anything is looked up.

pub fn accepted_open() -> Int

How many connections accept_on has returned that nothing has closed yet, across the whole program.

For a test that a connection it refused was closed. A handle dropped without shut shows only in the process’s descriptor table, which Windows cannot list; this count is kept by the runtime on every system.

What it costs: nothing extra, since the runtime keeps the count for every accept anyway. It counts every fiber’s accepts, so a test reads it where nothing else is accepting.

pub fn connected_to(accepted: Int, dialed: Int) -> Bool

Whether accepted, a connection accept_on returned, is the other end of dialed, a connection this program made with connect_to or connect_by.

What this prevents: a program that dials its own listener being handed somebody else’s connection as its own. macOS and Windows let a wildcard listener share a port with another program’s specific one, so what the listener accepts need not be what this program dialed. The two are one connection exactly when the accepted end’s peer port is the dialed end’s own port. False for a handle that is not a connected socket.

What it costs: two system calls, getpeername and getsockname.

pub fn transmit_bytes(connection: Int, bytes: Array<U8>) -> Int

Writes all of bytes, and says how many went: every one of them, or a negative number if the write failed, as for transmit.

transmit takes a String, which is right for a protocol made of text and wrong for one made of bytes: a wire protocol frames its messages with a length nobody wrote as characters. Postgres is the first caller, and a String would have meant deciding what its bytes mean on the way through.

pub fn shut(handle: Int) ->()

Closes a connection, letting the other end finish first.

The same reasoning as the Windows file, and the same shape: closing while the peer is still writing sends an RST, which discards the answer the peer had not read yet. SHUT_WR is 1 here too.

The drain takes what has already arrived and never waits for more. A peer that holds the connection open and says nothing would otherwise hold shut until the kernel abandoned the half-closed connection by itself, which here is tcp_fin_timeout — sixty seconds by default.

pub fn receive_now(connection: Int, buffer: Array<U8>) -> Int

Reads what has already arrived, without waiting for more.

Zero means the other end closed. Negative means nothing can be read now: -1 because nothing has arrived yet, anything lower because the read failed (the peer reset the connection, say). A caller that only wants to stop reading treats every negative alike; one checking whether a connection is still usable tells them apart with nothing_yet.

pub fn nothing_yet(read: Int) -> Bool

Whether a receive_now result means only that nothing has arrived yet.

What this prevents: a reset connection taken for a quiet one. Both answer receive_now with a negative; only this one is still usable, and writing to the other ends the process on the platforms that raise SIGPIPE.

Khora 0.4.0built fromee766ae43388on 2026-11-26 22:56ZVersioningSecurityContributingReleasesSource