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.
Connect and exchange lines
Section titled “Connect and exchange lines”import netimport 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 with TLS
Section titled “Connect with TLS”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 fsimport netimport 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")}Serve connections
Section titled “Serve connections”listen on port 0 picks a free port; port() tells which. Each accept gives a Socket for one client.
import netimport 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.
Reference
Section titled “Reference”import netFunctions
Section titled “Functions”access
Section titled “access”pub fn access() -> AccessThe program’s own network access; the compiler allows this call only in the main file.
system_roots
Section titled “system_roots”pub fn system_roots() -> TrustThe system’s trusted root certificates, as browsers use.
ca_file
Section titled “ca_file”pub fn ca_file(files: &fs.Files, path: &Str) -> Trust ! NetErrorOnly certificates signed by the CA in this PEM file; reading it needs file permission.
options
Section titled “options”pub fn options() -> OptionsNetError
Section titled “NetError”pub struct NetError { pub message: Str}Access
Section titled “Access”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.
Access.public_only
Section titled “Access.public_only”pub fn public_only(&self) -> AccessThe 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.
Access.only
Section titled “Access.only”pub fn only(&self, hosts: &Vec<Str>) -> AccessThe 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.
Access.allows
Section titled “Access.allows”pub fn allows(&self, host: &Str) -> boolAccess.connect
Section titled “Access.connect”pub fn connect(&self, host: &Str, port: i64) -> Socket ! NetErrorOpens a TCP connection to host (a name or an address) on port.
Access.connect_tls
Section titled “Access.connect_tls”pub fn connect_tls(&self, host: &Str, port: i64) -> Socket ! NetErrorA TLS connection checked against the system’s roots; there is no way to turn the check off.
Access.open
Section titled “Access.open”pub fn open(&self, host: &Str, port: i64, how: &Options) -> Socket ! NetErrorAccess.listen
Section titled “Access.listen”pub fn listen(&self, host: &Str, port: i64) -> Listener ! NetErrorListens 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.
Access.listen_tls
Section titled “Access.listen_tls”pub fn listen_tls(&self, host: &Str, port: i64, files: &fs.Files, cert_file: &Str, key_file: &Str) -> Listener ! NetErrorA 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.
Transport
Section titled “Transport”pub enum Transport { Plain Tls(Trust)}Options
Section titled “Options”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.
Socket
Section titled “Socket”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.
Socket.write
Section titled “Socket.write”pub fn write(&mut self, text: &Str) ! NetErrorSocket.close_write
Section titled “Socket.close_write”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.
Socket.read_line
Section titled “Socket.read_line”pub fn read_line(&mut self) -> Option<Untrusted<Str>> ! NetErrorThe 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.
Socket.read_line_max
Section titled “Socket.read_line_max”pub fn read_line_max(&mut self, max: i64) -> Option<Untrusted<Str>> ! NetErrorLike 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.
Socket.read
Section titled “Socket.read”pub fn read(&mut self, max: i64) -> Untrusted<Str> ! NetErrorUp 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.
Socket.read_exact
Section titled “Socket.read_exact”pub fn read_exact(&mut self, count: i64) -> Untrusted<Str> ! NetErrorExactly count bytes; the other side finishing sooner is an error.
Socket.read_all
Section titled “Socket.read_all”pub fn read_all(&mut self) -> Untrusted<Str> ! NetErrorEverything 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.
Socket.read_all_max
Section titled “Socket.read_all_max”pub fn read_all_max(&mut self, max: i64) -> Untrusted<Str> ! NetErrorLike read_all, but more than max bytes is an error.
Socket.set_timeout
Section titled “Socket.set_timeout”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”.
Socket.is_tls
Section titled “Socket.is_tls”pub fn is_tls(&self) -> boolSocket.peer
Section titled “Socket.peer”pub fn peer(&self) -> StrThe other side’s address, like 127.0.0.1:40312.
Listener
Section titled “Listener”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.
Listener.accept
Section titled “Listener.accept”pub fn accept(&mut self) -> Socket ! NetErrorWaits for the next connection.
Listener.port
Section titled “Listener.port”pub fn port(&self) -> i64The port it listens on, useful after listen(&host, 0).