unit netfs; // Importable network-filesystem client for user mounts (M22.3, spec 0032; // ADR 0065). Ordinary `/lib` module source: no `main`, no top-level `var` // state and no stream endpoint. The kernel knows nothing about this protocol; // this file and `scripts/netfs_host.py` are its two halves. // // st := netfs.list(ip, port, path, index, name, kind, size); // st := netfs.read(ip, port, path, offset, want, data, got); // st := netfs.write(ip, port, path, offset, payload, count); // // # Transport // // One TCP connection per mount operation: the guest connects to `:`, // writes one request frame, reads one response frame and closes. The kernel's // mount seam already serializes operations (one in flight per mount), so the // protocol has no request ids and no pipelining. The server closes the // connection after one exchange. // // # Frames // // Fields are separated by single spaces. The path is the LAST field, so a name // that contains spaces is not special. A request is one header line ending in // `\n`, followed by exactly `` raw bytes when the op carries a payload: // // LIST \n // STAT \n // READ \n // WRITE \n // TRUNCATE \n // REMOVE \n // MKDIR \n // RENAME \n\n // // The empty path is the mount root. Paths are mount-relative: no leading `/`, // no `.`/`..` component. A response is one status line, then optional extra // lines, then the optional payload: // // \n // [\n] LIST with status Ok only // [] READ when len > 0 // // `status` uses the `Status` ordinals unchanged (0 Ok, 3 NotFound, 4 Invalid, // 5 Full, 6 CapacityExceeded, 7 IoError); the server never sends 1 or 2. // `len` is the READ payload length, the WRITE byte count (the requested // length, all-or-nothing) and 0 for the other ops. `kind`/`size` answer // LIST/STAT: kind 0 file, 1 directory, 2 other. A LIST name is at most 64 // bytes, never contains `\n`, and is valid UTF-8. A READ answer is at most // [abi::fs::READ_CHUNK] (256) bytes because the kernel never asks for more; // a server MAY answer fewer bytes than requested, as at end of file. // // # Draining and failure // // Every response frame is read whole before this module returns, even when the // frame answers a status other than Ok and even when the mount app's // `mount_reply` will reject a stale token afterwards: a half-read frame would // desynchronize a later exchange. A single connection is closed by the server // after the exchange, so a framing error is recovered by closing it. The // transport statuses this module adds are: // // Ok/normal statuses the server's own answer (including its IoError) // WouldBlock the transport deadline expired (8 s) // Closed open/send/receive/framing/UTF-8 failure: lost link // // The mount application must treat `Closed` and `WouldBlock` as a lost // connection (unmount and report), and every other non-Ok as an ordinary // per-operation answer to relay through `syslib.mount_reply`. uses core, stdlib, lib.socket; const // One whole mount write, equal to `abi::mount::IO_MAX`. IoMax = 131072; // One READ answer, equal to `abi::fs::READ_CHUNK`. ReadChunk = 256; // A mount name, equal to `abi::fs::NAME_CAP`. NameCap = 64; // Request header + two 256-byte paths; 1024 is comfortably larger. HeaderCap = 1024; // One response status line. ` ` is short. LineCap = 128; // One socket receive and one send slice (`lib/socket`'s fixed capacity). ChunkCap = 1024; // The whole exchange (open, send, receive, close) must finish inside this // window; the kernel's own per-operation deadline is 10 s. DeadlineNs = 8000000000; // Bounded retry cap, so a dead peer cannot spin the task. MaxAttempts = 200000; // One exchange's connection and receive stream. type Conn = record id: int; open: bool; // Bytes received but not consumed; a 1024-byte recv may carry the status // line, the LIST name line and a short READ payload in one go. buf: bytes[ChunkCap]; pos: int; len: int; deadline: uint; end; // Opens the TCP connection and arms the transport deadline. Every failure is // `Closed`: the caller sees "lost link", never a server status. function begin_conn(ip: uint; port: uint; c: var Conn): Status; var st: Status; begin c.id := 0; c.open := false; c.pos := 0; c.len := 0; c.deadline := uint(0); st := socket.tcp(ip, port, c.id); if st <> Ok then return Closed; c.open := true; c.deadline := core.clock() + uint(DeadlineNs); st := socket.set_timeout(c.id, uint(8000)); if st <> Ok then begin socket.close(c.id); c.open := false; return Closed; end; return Ok; end; procedure finish_conn(c: var Conn); begin if c.open then begin socket.close(c.id); c.open := false; end; end; // Sends `count` raw bytes in at most 1024-byte slices. A partial TCP send // advances the source offset, so the whole payload always leaves in order. function send_raw(c: var Conn; data: const bytes[0]; count: int): Status; var at: int; take: int; copied: int; sent: int; attempts: int; st: Status; pending: bytes[ChunkCap]; begin at := 0; while at < count do begin take := count - at; if take > ChunkCap then take := ChunkCap; copied := core.substr_into(pending, data, at, take); if copied <> take then return Closed; sent := 0; attempts := 0; while sent = 0 do begin st := socket.send(c.id, pending, sent); if st = Ok then begin if sent <= 0 then return Closed; end else if st = WouldBlock then begin if core.clock() >= c.deadline then return WouldBlock; attempts := attempts + 1; if attempts > MaxAttempts then return WouldBlock; end else return Closed; end; at := at + sent; end; return Ok; end; // Stage a header (at most 1024 bytes) and send it. function send_text(c: var Conn; text: const string[0]): Status; var length: int; copied: int; stage: bytes[ChunkCap]; begin length := int(core.len(text)); if length > ChunkCap then return CapacityExceeded; copied := core.substr_into(stage, text, 0, length); if copied <> length then return Closed; return send_raw(c, stage, length); end; // Refills the receive buffer. `Ok` with zero bytes is end of file. function fill(c: var Conn): Status; var st: Status; attempts: int; begin c.pos := 0; c.len := 0; attempts := 0; while c.len = 0 do begin st := socket.recv(c.id, c.buf, c.len); if st = Ok then begin if c.len = 0 then return Closed; c.pos := 0; return Ok; end else if st = WouldBlock then begin if core.clock() >= c.deadline then return WouldBlock; attempts := attempts + 1; if attempts > MaxAttempts then return WouldBlock; end else return Closed; end; return Closed; end; function read_byte(c: var Conn; value: var byte): Status; var st: Status; begin if c.pos >= c.len then begin st := fill(c); if st <> Ok then return st; end; value := c.buf[c.pos]; c.pos := c.pos + 1; return Ok; end; // Reads up to and including one `\n`; the newline is not stored. function read_line(c: var Conn; line: var bytes[LineCap]; got: var int): Status; var value: byte; count: int; st: Status; begin count := 0; while true do begin st := read_byte(c, value); if st <> Ok then return st; if value = byte(10) then begin got := count; return Ok; end; if count >= LineCap then return Closed; line[count] := value; count := count + 1; end; return Closed; end; // Discards exactly `count` payload bytes. Used to finish a frame whose answer // this client cannot accept, so the connection never carries a partial frame. function drain(c: var Conn; count: int): Status; var at: int; value: byte; st: Status; begin at := 0; while at < count do begin st := read_byte(c, value); if st <> Ok then return st; at := at + 1; end; return Ok; end; // Copies the space-delimited token starting at `at` into `token`. Returns the // position after it, or -1 when there is no such token. A token longer than // the 32-byte buffer is -1 as well. function take_token(text: const string[0]; at: int; token: var string[32]): int; var length: int; start: int; stop: int; copied: int; begin length := int(core.len(text)); start := at; while start < length and text[start] = byte(32) do start := start + 1; if start >= length then return -1; stop := start; while stop < length and text[stop] <> byte(32) do stop := stop + 1; copied := core.substr_into(token, text, start, stop - start); if copied <> stop - start then return -1; return stop; end; // Parses ` \n` and writes the four fields only on // `Ok`. A malformed line, an unknown status ordinal or a fifth token is a // framing error (`Closed`). function read_header(c: var Conn; out_status: var Status; out_len: var uint; out_kind: var uint; out_size: var uint): Status; var line: bytes[LineCap]; got: int; text: string[LineCap]; copied: int; at: int; t1: string[32]; t2: string[32]; t3: string[32]; t4: string[32]; t5: string[32]; sval: int; lval: int; kval: int; zval: int; st: Status; begin st := read_line(c, line, got); if st <> Ok then return st; copied := core.substr_into(text, line, 0, got); if copied <> got then return Closed; at := take_token(text, 0, t1); if at < 0 then return Closed; at := take_token(text, at, t2); if at < 0 then return Closed; at := take_token(text, at, t3); if at < 0 then return Closed; at := take_token(text, at, t4); if at < 0 then return Closed; if take_token(text, at, t5) >= 0 then return Closed; st := stdlib.parse_int_into(t1, sval); if st <> Ok or sval < 0 or sval > 7 then return Closed; st := stdlib.parse_int_into(t2, lval); if st <> Ok or lval < 0 then return Closed; st := stdlib.parse_int_into(t3, kval); if st <> Ok or kval < 0 then return Closed; st := stdlib.parse_int_into(t4, zval); if st <> Ok or zval < 0 then return Closed; out_status := Status(sval); out_len := uint(lval); out_kind := uint(kval); out_size := uint(zval); return Ok; end; // Reads exactly `count` (<= 256) payload bytes into `data`. function read_payload(c: var Conn; data: var bytes[ReadChunk]; count: int): Status; var at: int; value: byte; st: Status; begin at := 0; while at < count do begin st := read_byte(c, value); if st <> Ok then return st; data[at] := value; at := at + 1; end; return Ok; end; // ---- the eight operations ------------------------------------------------ // `LIST `: one entry, or `NotFound` past the end. `kind`/`size` // are written only on `Ok`. function list(ip: uint; port: uint; path: const string[0]; index: uint; name: var string[NameCap]; kind: var uint; size: var uint): Status; var c: Conn; st: Status; hs: Status; rlen: uint; rkind: uint; rsize: uint; header: string[HeaderCap]; num: string[32]; line: bytes[LineCap]; got: int; copied: int; begin st := begin_conn(ip, port, c); if st <> Ok then return st; copied := core.format_int_into(num, int(index), uint(10), uint(0)); header := "LIST " + num + " " + path + "\n"; st := send_text(c, header); if st = Ok then st := read_header(c, hs, rlen, rkind, rsize); if st = Ok and hs = Ok then begin st := read_line(c, line, got); if st = Ok then begin if got > NameCap then st := Closed else if core.substr_into(name, line, 0, got) <> got then st := Closed; end; end; finish_conn(c); if st <> Ok then return st; if hs = Ok then begin kind := rkind; size := rsize; end; return hs; end; // `STAT `: kind and size. Both are written only on `Ok`. function stat(ip: uint; port: uint; path: const string[0]; kind: var uint; size: var uint): Status; var c: Conn; st: Status; hs: Status; rlen: uint; rkind: uint; rsize: uint; header: string[HeaderCap]; begin st := begin_conn(ip, port, c); if st <> Ok then return st; header := "STAT " + path + "\n"; st := send_text(c, header); if st = Ok then st := read_header(c, hs, rlen, rkind, rsize); // A scalar answer never carries a payload, but drain a frame that claims one // so the connection is never left mid-frame. if st = Ok and rlen > uint(0) then begin if rlen > uint(IoMax) then st := Closed else st := drain(c, int(rlen)); if st = Ok and hs = Ok then st := Closed; end; finish_conn(c); if st <> Ok then return st; if hs = Ok then begin kind := rkind; size := rsize; end; return hs; end; // `READ `: at most `want` (and 256) bytes into `data`. // `got` is written only on `Ok` and never exceeds `want`. function read(ip: uint; port: uint; path: const string[0]; offset: uint; want: uint; data: var bytes[ReadChunk]; got: var int): Status; var c: Conn; st: Status; hs: Status; rlen: uint; rkind: uint; rsize: uint; header: string[HeaderCap]; off: string[32]; num: string[32]; copied: int; begin got := 0; if want > uint(ReadChunk) then return Invalid; st := begin_conn(ip, port, c); if st <> Ok then return st; copied := core.format_int_into(off, int(offset), uint(10), uint(0)); copied := core.format_int_into(num, int(want), uint(10), uint(0)); header := "READ " + off + " " + num + " " + path + "\n"; st := send_text(c, header); if st = Ok then st := read_header(c, hs, rlen, rkind, rsize); if st = Ok then begin if rlen > uint(IoMax) then st := Closed else if hs = Ok and rlen <= want and rlen <= uint(ReadChunk) then begin st := read_payload(c, data, int(rlen)); if st = Ok then got := int(rlen); end else begin // The whole frame is drained before the failure is reported: an error // status with a payload, or a READ that answered more than it was asked. st := drain(c, int(rlen)); if st = Ok and hs = Ok then st := Closed; end; end; finish_conn(c); if st <> Ok then return st; return hs; end; // `WRITE ` + payload. The server answers the count, which // must be exactly `count`; a different count is a protocol violation (`Closed`). function write(ip: uint; port: uint; path: const string[0]; offset: uint; data: const bytes[0]; count: uint): Status; var c: Conn; st: Status; hs: Status; rlen: uint; rkind: uint; rsize: uint; header: string[HeaderCap]; off: string[32]; num: string[32]; copied: int; begin if count > uint(IoMax) then return CapacityExceeded; st := begin_conn(ip, port, c); if st <> Ok then return st; copied := core.format_int_into(off, int(offset), uint(10), uint(0)); copied := core.format_int_into(num, int(count), uint(10), uint(0)); header := "WRITE " + off + " " + num + " " + path + "\n"; st := send_text(c, header); if st = Ok then st := send_raw(c, data, int(count)); if st = Ok then st := read_header(c, hs, rlen, rkind, rsize); finish_conn(c); if st <> Ok then return st; // `len` in a WRITE answer is the accepted byte count, not a payload. if hs = Ok and rlen <> count then return Closed; return hs; end; // The scalar operations (`TRUNCATE`, `REMOVE`, `MKDIR`, `RENAME`): one header, // one status, no payload. function scalar(ip: uint; port: uint; header: const string[0]): Status; var c: Conn; st: Status; hs: Status; rlen: uint; rkind: uint; rsize: uint; begin st := begin_conn(ip, port, c); if st <> Ok then return st; st := send_text(c, header); if st = Ok then st := read_header(c, hs, rlen, rkind, rsize); if st = Ok and rlen > uint(0) then begin if rlen > uint(IoMax) then st := Closed else st := drain(c, int(rlen)); if st = Ok and hs = Ok then st := Closed; end; finish_conn(c); if st <> Ok then return st; return hs; end; // `TRUNCATE `. function truncate(ip: uint; port: uint; path: const string[0]; size: uint): Status; var header: string[HeaderCap]; num: string[32]; copied: int; begin copied := core.format_int_into(num, int(size), uint(10), uint(0)); header := "TRUNCATE " + num + " " + path + "\n"; return scalar(ip, port, header); end; // `REMOVE `. function remove(ip: uint; port: uint; path: const string[0]): Status; var header: string[HeaderCap]; begin header := "REMOVE " + path + "\n"; return scalar(ip, port, header); end; // `MKDIR `. function mkdir(ip: uint; port: uint; path: const string[0]): Status; var header: string[HeaderCap]; begin header := "MKDIR " + path + "\n"; return scalar(ip, port, header); end; // `RENAME \n\n`: two lines, because a path may contain spaces and // neither path may be split by a numeric field. function rename(ip: uint; port: uint; from: const string[0]; to: const string[0]): Status; var header: string[HeaderCap]; begin header := "RENAME " + from + "\n" + to + "\n"; return scalar(ip, port, header); end;