//! The `hosted` execution profile (spec 11 §8): the real console, file //! system and TCP, the host's monotonic clock and CSPRNG. //! //! Capability scopes are enforced here, before any host call: a path outside //! the scope never reaches the operating system. Host errors are mapped to //! the closed `io_error` set; error numbers never reach the program. const std = @import("std"); const air = @import("../air.zig"); const world = @import("world.zig"); const Io = std.Io; const IoError = world.Error; pub const Handle = union(enum) { file: struct { file: Io.File, pos: u64 }, listener: Io.net.Server, stream: Io.net.Stream, closed, }; pub const Host = struct { arena: std.mem.Allocator, io: Io, handles: std.ArrayList(Handle) = .empty, fn add(h: *Host, x: Handle) !u32 { try h.handles.append(h.arena, x); return @intCast(h.handles.items.len - 1); } /// Host error to `io_error` (spec 06 §7). Unlisted errors are `other`; /// `timed_out` is reserved for explicit timeouts and never produced here. pub fn map(err: anyerror) IoError { return switch (err) { error.FileNotFound, error.NotDir => .not_found, error.AccessDenied, error.PermissionDenied, error.ReadOnlyFileSystem => .permission_denied, error.PathAlreadyExists => .already_exists, error.BadPathName, error.NameTooLong, error.IsDir => .invalid_input, error.NoSpaceLeft, error.DiskQuota => .no_space, error.BrokenPipe => .broken_pipe, error.ConnectionRefused => .connection_refused, error.ConnectionResetByPeer => .connection_reset, error.AddressInUse => .address_in_use, error.AddressUnavailable, error.AddressNotAvailable => .address_unavailable, else => .other, }; } // ------------------------------------------------------------ console pub fn writeOut(h: *Host, err_stream: bool, bytes: []const u8) ?IoError { const f: Io.File = if (err_stream) .stderr() else .stdout(); f.writeStreamingAll(h.io, bytes) catch |e| return map(e); return null; } pub fn readIn(h: *Host, buf: []u8) union(enum) { ok: usize, err: IoError } { const n = Io.File.stdin().readStreaming(h.io, &.{buf}) catch |e| switch (e) { error.EndOfStream => return .{ .ok = 0 }, else => return .{ .err = map(e) }, }; return .{ .ok = n }; } // ------------------------------------------------------------ files pub fn open(h: *Host, scope: ?[]const u8, path: []const u8, mode: air.authority.Resource) !world.Opened { if (!world.World.validPath(path)) return .{ .err = .invalid_input }; if (!world.World.within(scope, path)) return .{ .err = .permission_denied }; const file: Io.File = switch (mode) { .file_read => Io.Dir.openFileAbsolute(h.io, path, .{ .allow_directory = false }), .file_write => Io.Dir.createFileAbsolute(h.io, path, .{}), .file_append => Io.Dir.createFileAbsolute(h.io, path, .{ .truncate = false }), else => unreachable, } catch |e| return .{ .err = map(e) }; var pos: u64 = 0; if (mode == .file_append) { const st = file.stat(h.io) catch |e| { file.close(h.io); return .{ .err = map(e) }; }; pos = st.size; } return .{ .ok = try h.add(.{ .file = .{ .file = file, .pos = pos } }) }; } pub fn fileRead(h: *Host, hd: u32, buf: []u8) union(enum) { ok: usize, err: IoError } { const f = &h.handles.items[hd].file; // Positional reads report end of file as 0 bytes. const n = f.file.readPositional(h.io, &.{buf}, f.pos) catch |e| return .{ .err = map(e) }; f.pos += n; return .{ .ok = n }; } pub fn fileWrite(h: *Host, hd: u32, bytes: []const u8) ?IoError { const f = &h.handles.items[hd].file; f.file.writePositionalAll(h.io, bytes, f.pos) catch |e| return map(e); f.pos += bytes.len; return null; } pub fn sync(h: *Host, hd: u32) ?IoError { h.handles.items[hd].file.file.sync(h.io) catch |e| return map(e); return null; } pub fn close(h: *Host, hd: u32) void { switch (h.handles.items[hd]) { .file => |f| f.file.close(h.io), .listener => |*l| l.deinit(h.io), .stream => |s| s.close(h.io), .closed => {}, } h.handles.items[hd] = .closed; } // ------------------------------------------------------------ TCP fn parseAddr(addr: []const u8) ?Io.net.IpAddress { if (!world.World.validAddr(addr)) return null; const colon = std.mem.lastIndexOfScalar(u8, addr, ':').?; const port = std.fmt.parseInt(u16, addr[colon + 1 ..], 10) catch return null; return Io.net.IpAddress.parseIp4(addr[0..colon], port) catch null; } pub fn listen(h: *Host, addr: []const u8) !world.Opened { const a = parseAddr(addr) orelse return .{ .err = .invalid_input }; const server = a.listen(h.io, .{}) catch |e| return .{ .err = map(e) }; return .{ .ok = try h.add(.{ .listener = server }) }; } pub fn connect(h: *Host, addr: []const u8) !world.Opened { const a = parseAddr(addr) orelse return .{ .err = .invalid_input }; const stream = a.connect(h.io, .{ .mode = .stream }) catch |e| return .{ .err = map(e) }; return .{ .ok = try h.add(.{ .stream = stream }) }; } pub fn accept(h: *Host, hd: u32) !world.Opened { const stream = h.handles.items[hd].listener.accept(h.io) catch |e| return .{ .err = map(e) }; return .{ .ok = try h.add(.{ .stream = stream }) }; } pub fn recv(h: *Host, hd: u32, buf: []u8) union(enum) { ok: usize, err: IoError } { var bufs = [_][]u8{buf}; // `Stream.read` does not compile in Zig 0.17 (it destructures a // struct); `readWithControl` with no control buffer is equivalent. const r = h.handles.items[hd].stream.readWithControl(h.io, &bufs, &.{}) catch |e| return .{ .err = map(e) }; return .{ .ok = r.data_len }; } pub fn send(h: *Host, hd: u32, bytes: []const u8) ?IoError { var buf: [4096]u8 = undefined; var w = h.handles.items[hd].stream.writer(h.io, &buf); w.interface.writeAll(bytes) catch return map(w.err orelse error.Unexpected); w.interface.flush() catch return map(w.err orelse error.Unexpected); return null; } // ------------------------------------------------------------ clock and random pub fn monotonic(h: *Host) u64 { const t = Io.Timestamp.now(h.io, .awake); return @intCast(@max(t.nanoseconds, 0) & std.math.maxInt(u64)); } pub fn fill(h: *Host, buf: []u8) void { h.io.random(buf); } /// Releases host handles left open when the execution instance ends /// (spec 06 §6, invariant 2: not observable by the program). pub fn deinit(h: *Host) void { for (h.handles.items, 0..) |x, i| if (x != .closed) h.close(@intCast(i)); } };