Network connections: tcp

A tcp value is a connection to a program on another computer (or this one): a web server, a database, a mail server. You connect, write what the protocol says, and read the answer.

sock: tcp = tcp.connect("example.com", 80)
sock.write("HEAD / HTTP/1.0\r\nHost: example.com\r\n\r\n")
print(sock.line())   // HTTP/1.1 200 OK
sock.close()

Connecting

sock: tcp = tcp.connect("db.example.com", 5432)     // wait as long as the system does
fast: tcp = tcp.connect("10.0.0.5", 6379, 3)         // give up after 3 seconds

tcp.connect(host, port) connects right away; the optional third argument is how many seconds to wait for it, an int or a float (0.5). The host is a name or an IPv4 address.

If it can’t connect, error 14 is raised: try catches it, so a program can try another server:

err: error = nil
try err {
    sock: tcp = tcp.connect("primary.example.com", 5432, 3)
    print(sock.line())
}
if err != nil {
    print("primary is down: ${err.message}")
}

Writing

write sends a str, a [byte] or a buffer, all of it:

sock: tcp = tcp.connect("localhost", 6379)
sock.write("PING\r\n")
sock.write([1, 0, 0, 4])
packet: buffer = buffer()
packet.write(42, 4)
sock.write(packet)

Lines in network protocols usually end in \r\n.

Reading

CallGives
sock.line()the next line, without its \n (and a \r before it)
sock.read(n)exactly n bytes; it waits until they have all come
sock.read()everything until the other side closes the connection

read gives a str, a [byte] or a buffer, whichever it goes into; a buffer makes binary protocols easy:

sock: tcp = tcp.connect("localhost", 3306)
header: buffer = sock.read(4)
size: int = header.read(3)
body: buffer = sock.read(size)

When the other side closes the connection, read() gives what came until then, and line() gives a last line even without \n. But read(n) raises error 14 if fewer than n bytes came (the connection to db:3306 closed after 2 of 4 bytes), and so does line() when no line came at all.

Timeouts

Without a timeout, reading waits as long as it takes. sock.timeout(seconds) says how long to wait at most, each time something is read or written; you can change it as you go, and timeout(0) takes it away:

sock: tcp = tcp.connect("mail.example.com", 25, 5)
sock.timeout(30)            // the greeting may take a while
greeting: str = sock.line()
sock.timeout(5)             // the answers should come quickly

A wait that takes longer raises error 14: timed out reading from mail.example.com:25.

Secure connections: TLS

sock.secure(host) switches a connection to TLS 1.3: from then on, write, read and line work as before, and everything is encrypted on the way. host is the server’s name, as its certificate has it:

sock: tcp = tcp.connect("192.168.1.20", 6379)
sock.secure("192.168.1.20")
sock.write("PING\r\n")
print(sock.line())

Protocols that start without encryption and switch to it, like PostgreSQL, MySQL and SMTP’s STARTTLS, call secure when the protocol says so. An https request does the same right after connecting.

The server’s certificate is checked as for https: by this computer’s authorities, its name, its dates and its key, and self-signed certificates are accepted on local and private names (localhost, db, *.local, 10.*, 192.168.*, …). Before secure, a connection can be told what else to trust, as a request can:

sock: tcp = tcp.connect("db.example.com", 5432)
sock.trust("certs/db-ca.pem")      // or sock.pin("sha256//..."), or sock.insecure()
sock.secure("db.example.com")
MessageWhen
the certificate of db.example.com isn't signed by an authority this computer trusts (...)self-signed, or an unknown authority: use trust or pin
the certificate of db.example.com isn't for that name (...), ... expired on ...see https
the key of db.example.com is sha256//..., not the pinned ...another key than the pinned one
db.example.com speaks only TLS 1.2 or older, and Luma has TLS 1.3an old server
the TLS handshake with H:P failed: the server said handshake_failure (40): ...no encryption both sides have; Luma has X25519, P-256 and AES-128-GCM
H:P doesn't speak TLS (is it the right port?)the other side isn’t TLS
a TLS record from H:P didn't decrypt: it was changed on the way (bad_record_mac)the data was tampered with
the connection to H:P is already securesecure twice

The encryption and the checks come with Luma, without libraries: X25519 for the keys (or P-256, when the server asks for it), AES-128-GCM for the data (with the processor’s AES instructions), and RSA and ECDSA (P-256, P-384) for certificates. In a compiled program, setting up a connection takes a few milliseconds, checking its certificate about ten more, and the data moves at hundreds of megabytes a second.

Closing

sock.close() ends the connection (a secure one tells the other side first); calling it again does nothing. Reading or writing after it raises error 14. A connection that nothing holds anymore is closed by itself, like any value is freed.

Waiting for connections: a server

A program can be the server too: it listens on a port, and other programs connect to it. That is how to stand in for a device in a test (a robot, a scale, a PLC) while the real application connects to it, or to write a small service of your own.

tcp.serve gives each client a coroutine of its own, so many can be connected at once:

// a stand-in for a device: it answers each line with ACK
fn device(conn: tcp) {
    print("${conn} connected")             // tcp(192.168.1.5:50123)
    while true {
        msg: str = conn.line()
        if msg == "" {
            stop
        }
        conn.write("ACK ${msg}\r\n")
    }
    conn.close()
}

tcp.serve(5000, device)

tcp.listen gives the listener itself, for a program that takes the connections one at a time, or decides when to stop:

l: tcp.listener = tcp.listen("127.0.0.1", 5000)
conn: tcp = l.accept()            // waits for the next client
print(conn.line())
conn.close()
l.close()
Function or methodWhat it does
tcp.serve(port, handler)listens on the port, and runs handler (a fn(tcp)) for each client that connects, each in a coroutine of its own; it doesn’t return
tcp.serve(host, port, handler)the same on one address of this computer: "127.0.0.1" or "localhost" for this computer only, or another IPv4 address of it
tcp.serve(port, handler, n)stops after n clients, once their handlers are done (for tests)
tcp.listen(port), tcp.listen(host, port)listens on the port, and gives a tcp.listener; port 0 lets the system choose a free one
l.port()the port it listens on: the one given, or the one the system chose (for a test, so that two never take the same)
l.accept()waits for the next client, and gives its connection
l.close()stops listening: no one else can connect (connections already made go on). The program’s end stops it too.
l.secure(cert, key)makes it a secure server: the connections it accepts are TLS (see below)
tcp.serve(l, handler)serves on a listener made with tcp.listen (a secure one, or one on port 0)
conn.peer()the other end: a client’s address and port ("192.168.1.5:50123"), or the host and port a program connected to

A secure server

l.secure(cert, key) makes the listener’s connections TLS, as a client’s secure does from the other side. It takes the server’s certificates and key as PEM files, or "" and "" for a self-signed certificate made when the program starts, and then gives that certificate’s key as a pin, which a client checks with pin:

l: tcp.listener = tcp.listen(5443)
pin: str = l.secure("", "")         // or l.secure("cert.pem", "key.pem")
print(pin)                          // sha256//...: for the clients
tcp.serve(l, device)

l.accept() does the TLS handshake before it gives the connection: a client that fails it (one that doesn’t speak TLS, or doesn’t trust the certificate) is error 14. tcp.serve does it in each client’s coroutine instead, so a slow client keeps no one waiting; one that fails is written to stderr (tls: 127.0.0.1:50122 doesn't speak TLS (is it the right port?)), and the others go on. A program has one certificate: a secure listener and an https server in the same program use the last one given. The TLS is the same as the https server’s (TLS 1.3, ECDSA or RSA keys).

A client’s connection is an ordinary tcp: line, read, write, timeout and close work as on a connection the program made. A port that another program already listens on, or that the system keeps for itself (below 1024 on Linux, for programs that aren’t root), is error 14.

Finding the host

A name is looked up as the system does it: localhost, the names in /etc/hosts, then the DNS servers in /etc/resolv.conf. On Windows, Windows looks it up. If it can’t be found: cannot connect to db.example.com:5432: no address found.

Errors

Network errors have code 14:

MessageWhen
cannot connect to H:P: connection refusednothing listens on that port
cannot connect to H:P: timed outno answer within the time given
cannot connect to H:P: the host can't be reachedno way to that computer
cannot connect to H:P: no address foundthe name isn’t known
timed out reading from H:P, timed out writing to H:Plonger than timeout
the connection to H:P closed after 2 of 4 bytesread(n) and the other side closed
cannot read from H:P: the connection was resetthe other side broke it off
the connection to H:P is closedused after close()

Other failures say the system’s error number: error 13.

Details

  • Only IPv4 for now.
  • Each wait (line, read, write) uses the timeout of the connection at that moment.
  • print shows a connection as tcp(host:port).
  • A built program on Windows uses the timeout of tcp.connect when it has coroutines (it serves, or uses spawn or wait(list, f)); otherwise Windows waits as long as it does.

Not available yet

  • TLS 1.2, client certificates, and checking whether a certificate was revoked.
  • UDP, and IPv6.