Skip to content

net

TCP connections and servers, with or without TLS. For HTTP, use the http module, which is built on this one.

Using the network needs a permission, a net.Access value. Only the program’s main file can make one with net.access(); it is then passed to the code that may use the network, which takes &net.Access. A caller can narrow it before handing it on: only(&["api.example.com"]) allows those host names and nothing else, and public_only() refuses this machine, private networks and link-local addresses. The public_only check is made on the address actually connected to, so a host name cannot be pointed at an internal address later.

Every read and write returns ! net.NetError, and what is read arrives as Untrusted<Str>: it came from another machine, so it is turned into a Str only by a check (as_name(), to_i64(), checked(...)) or a visible unchecked(). A timeout, a reset connection or a TLS failure is an error that must be handled; it never looks like a normal end of the data. Reads return None (for lines) or an empty string only when the other side closed the connection properly.

import net
import time
fn ask(access: &net.Access, question: &Str) -> Str ! net.NetError {
let mut conn = try access.connect("localhost", 7000)
conn.set_timeout(Some(time.seconds(5)))
try conn.write(&(*question + "\n"))
match try conn.read_line_max(4096) {
Some(line) => return line.unchecked()
None => return ""
}
}
let access = net.access().only(&["localhost"])
print(try ask(&access, "status"))

connect_tls checks the server’s certificate against the system’s trusted roots and the host name. There is no way to turn the check off. To trust one private CA instead, use open with a Trust from net.ca_file(&files, &path), which needs file permission to read the CA file.

import fs
import net
import time
let access = net.access()
let mut conn = try access.connect_tls("example.com", 443)
try conn.write("HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")
print((try conn.read_all_max(65536)).unchecked())
let how = net.Options { transport: .Tls(try net.ca_file(&fs.files(), &"/etc/myapp/ca.pem")), timeout: Some(time.seconds(10)) }
let mut internal = try access.open("db.internal", 5433, &how)
try internal.write("ping\n")
match try internal.read_line_max(1024) {
Some(line) => print(line.unchecked())
None => print("closed")
}

listen on port 0 picks a free port; port() tells which. Each accept gives a Socket for one client.

import net
import time
let access = net.access()
let mut server = try access.listen("127.0.0.1", 0)
print(f"listening on port {server.port()}")
while true {
let mut conn = server.accept() catch {
net.NetError(e) => {
eprint(e.message)
continue
}
}
conn.set_timeout(Some(time.seconds(30)))
while true {
let line = conn.read_line_max(1024) catch {
net.NetError(_) => break
}
match line {
Some(text) => conn.write(&(text.unchecked() + "\n")) catch {
net.NetError(_) => break
}
None => break
}
}
}

This server handles one client at a time. Sockets and listeners can be moved into thread.join and thread.each to serve several at once.

import net
pub fn access() -> Access

The program’s own network access; the compiler allows this call only in the main file.

pub fn system_roots() -> Trust

The system’s trusted root certificates, as browsers use.

pub fn ca_file(files: &fs.Files, path: &Str) -> Trust ! NetError

Only certificates signed by the CA in this PEM file; reading it needs file permission.

pub fn options() -> Options
pub struct NetError {
pub message: Str
}
pub struct Access {
}

Permission to use the network; only the program’s main file can make one, and passes it on.

It also has 2 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.

pub fn public_only(&self) -> Access

The same access, but never to this machine, private networks or link-local addresses.

Use it for addresses that come from users (webhooks, URL previews), so they cannot reach services on this machine or the internal network.

pub fn only(&self, hosts: &Vec<Str>) -> Access

The same access, limited to these host names (compared without case).

Host names are compared without case, exactly as written: only(&["example.com"]) does not allow www.example.com or the address 93.184.215.14. Narrowing an access that is already narrowed keeps only names allowed by both. An access limited with only cannot listen, since a server accepts connections from anyone.

pub fn allows(&self, host: &Str) -> bool
pub fn connect(&self, host: &Str, port: i64) -> Socket ! NetError

Opens a TCP connection to host (a name or an address) on port.

pub fn connect_tls(&self, host: &Str, port: i64) -> Socket ! NetError

A TLS connection checked against the system’s roots; there is no way to turn the check off.

pub fn open(&self, host: &Str, port: i64, how: &Options) -> Socket ! NetError
pub fn listen(&self, host: &Str, port: i64) -> Listener ! NetError

Listens on host (“” for every address, “127.0.0.1” for this machine only); port 0 picks one.

host is the local address to listen on: "127.0.0.1" for this machine only, "" for every address. Dropping the Listener stops listening.

pub fn listen_tls(&self, host: &Str, port: i64, files: &fs.Files, cert_file: &Str, key_file: &Str) -> Listener ! NetError

A listener whose connections speak TLS with this certificate chain and key (PEM files).

cert_file and key_file are paths to PEM files: the certificate chain and the private key. Both must be allowed by the fs.Files permission passed in. Every accept does the TLS handshake, with a 10 second limit, so a client that connects and says nothing cannot hold the server.

pub struct Trust {
}

Whose certificates a TLS connection accepts; made by system_roots or ca_file.

It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.

pub enum Transport {
Plain
Tls(Trust)
}
pub struct Options {
pub transport: Transport
pub timeout: Option<time.Duration>
}

How to connect; a timeout of None waits as long as it takes.

timeout limits connecting, including the host name lookup, and becomes the socket’s timeout for reads and writes. None waits as long as it takes.

pub struct Socket {
}

A TCP connection; dropping it closes the connection.

It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.

pub fn write(&mut self, text: &Str) ! NetError
pub fn close_write(&mut self)

Tells the other side nothing more will be sent, while still reading its answer.

Tells the other side that nothing more will be sent (a half close), while this side can still read the answer. Needed for protocols where the server reads until the end of input.

pub fn read_line(&mut self) -> Option<Untrusted<Str>> ! NetError

The next line without its line ending; None once the other side finished.

Without a limit, a client that never sends a line break can fill memory. For data from outside, use read_line_max. Lines end at \n; a \r before it is removed too.

pub fn read_line_max(&mut self, max: i64) -> Option<Untrusted<Str>> ! NetError

Like read_line, but a line longer than max bytes is an error.

Text read from a socket is a plain Str, not Untrusted: check it before using it as a path, a name or HTML.

pub fn read(&mut self, max: i64) -> Untrusted<Str> ! NetError

Up to max bytes, waiting only if none have arrived yet; empty once the other side finished.

Returns what has arrived, up to max bytes, waiting only if nothing has. It can return fewer bytes than were sent in one write on the other side; use read_exact for a known size.

pub fn read_exact(&mut self, count: i64) -> Untrusted<Str> ! NetError

Exactly count bytes; the other side finishing sooner is an error.

pub fn read_all(&mut self) -> Untrusted<Str> ! NetError

Everything until the other side finishes.

Reads until the other side closes the connection, with no size limit. For data from outside, use read_all_max.

pub fn read_all_max(&mut self, max: i64) -> Untrusted<Str> ! NetError

Like read_all, but more than max bytes is an error.

pub fn set_timeout(&mut self, timeout: Option<time.Duration>)

Reads and writes waiting longer than this fail with “timed out”; None waits forever.

Applies to every later read and write. A read that waits longer fails with a NetError saying “timed out”. None waits forever. A timeout below one millisecond counts as one millisecond, so a zero Duration never silently means “no timeout”.

pub fn is_tls(&self) -> bool
pub fn peer(&self) -> Str

The other side’s address, like 127.0.0.1:40312.

pub struct Listener {
}

A TCP server socket waiting for connections; dropping it stops listening.

It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.

pub fn accept(&mut self) -> Socket ! NetError

Waits for the next connection.

pub fn port(&self) -> i64

The port it listens on, useful after listen(&host, 0).