// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! The host end of an Uthernet II: four of the machine's sockets standing in //! for the four the W5100 has. //! //! The chip (`w5100.zig`) has the whole TCP/IP stack, so this does not build //! packets — it opens a host socket for each of the chip's, connects it or //! listens on it as the chip asks, and moves bytes between the chip's rings and //! the socket. That is why the Uthernet II is the card to have in a terminal: //! what the chip does maps one to one onto what the operating system does, with //! no raw Ethernet to bridge and no privilege to ask for. //! //! `pump` is called once a frame, the way the serial and MIDI lines are pumped: //! it takes what each of the chip's sockets wants, does it, and hands back what //! came in. It is Linux only and talks to the system directly, for the same //! reason `ltoudp.zig` does — the standard library's I/O has no non-blocking //! connect or accept to offer — and on any other system it is simply quiet, a //! card with nothing on the other end of the wire. const std = @import("std"); const builtin = @import("builtin"); const linux = std.os.linux; const w5100 = @import("w5100.zig"); /// How many bytes are moved between a socket and its ring in one pump. A whole /// socket buffer, so a burst does not take several frames to clear. const chunk = 2048; pub const Ports = struct { hosts: [4]Host = .{ .idle, .idle, .idle, .idle }, /// A host socket standing in for one of the chip's, in whichever of the /// states the chip's commands put it through. const Host = union(enum) { idle, /// A TCP connect the system has not finished making. connecting: i32, /// A connected TCP socket, a client's or a server's. stream: i32, /// A TCP listener waiting for one connection. listening: i32, /// A bound UDP socket. datagram: i32, fn fd(self: Host) ?i32 { return switch (self) { .idle => null, inline else => |f| f, }; } }; pub fn deinit(self: *Ports) void { for (&self.hosts) |*host| { if (host.fd()) |f| _ = linux.close(f); host.* = .idle; } } /// Moves each of the four sockets on a step: acts on any new command, then /// drives whatever the socket is in the middle of doing. pub fn pump(self: *Ports, chip: *w5100.W5100) void { if (comptime builtin.os.tag != .linux) return; inline for (0..4) |i| self.pumpSocket(i, chip); } fn pumpSocket(self: *Ports, comptime i: usize, chip: *w5100.W5100) void { switch (chip.take(i)) { .nothing => {}, .connect => |c| self.beginConnect(i, c.ip, c.port), .listen => |port| self.beginListen(i, port), .bind => |port| self.beginBind(i, port), .close => self.shut(i), } switch (self.hosts[i]) { .idle => {}, .connecting => |fd| self.driveConnecting(i, fd, chip), .listening => |fd| self.driveListening(i, fd, chip), .stream => |fd| self.driveStream(i, fd, chip), .datagram => |fd| self.driveDatagram(i, fd, chip), } } // -- starting a socket off ------------------------------------------------ fn beginConnect(self: *Ports, comptime i: usize, ip: [4]u8, port: u16) void { self.shut(i); const fd = socket(linux.SOCK.STREAM) orelse return; const to = address(ip, port); const rc = linux.connect(fd, @ptrCast(&to), @sizeOf(linux.sockaddr.in)); switch (linux.errno(rc)) { // Non-blocking, so it almost always says "in progress"; a // connection to something on this very machine can finish at once. .SUCCESS => self.hosts[i] = .{ .stream = fd }, .INPROGRESS, .INTR => self.hosts[i] = .{ .connecting = fd }, else => _ = linux.close(fd), } } fn beginListen(self: *Ports, comptime i: usize, port: u16) void { self.shut(i); const fd = socket(linux.SOCK.STREAM) orelse return; reuse(fd); const on = address(.{ 0, 0, 0, 0 }, port); if (linux.errno(linux.bind(fd, @ptrCast(&on), @sizeOf(linux.sockaddr.in))) != .SUCCESS) { _ = linux.close(fd); return; } if (linux.errno(linux.listen(fd, 1)) != .SUCCESS) { _ = linux.close(fd); return; } self.hosts[i] = .{ .listening = fd }; } fn beginBind(self: *Ports, comptime i: usize, port: u16) void { self.shut(i); const fd = socket(linux.SOCK.DGRAM) orelse return; reuse(fd); const on = address(.{ 0, 0, 0, 0 }, port); if (linux.errno(linux.bind(fd, @ptrCast(&on), @sizeOf(linux.sockaddr.in))) != .SUCCESS) { _ = linux.close(fd); return; } self.hosts[i] = .{ .datagram = fd }; } fn shut(self: *Ports, comptime i: usize) void { if (self.hosts[i].fd()) |f| _ = linux.close(f); self.hosts[i] = .idle; } // -- driving a socket that is under way ----------------------------------- fn driveConnecting(self: *Ports, comptime i: usize, fd: i32, chip: *w5100.W5100) void { if (!writable(fd)) return; // Writable means the connect has finished, one way or another; the // pending error says which. var err: u32 = 0; var len: u32 = @sizeOf(u32); _ = linux.getsockopt(fd, linux.SOL.SOCKET, linux.SO.ERROR, @ptrCast(&err), &len); if (err == 0) { self.hosts[i] = .{ .stream = fd }; chip.connected(i); } else { _ = linux.close(fd); self.hosts[i] = .idle; chip.timedOut(i); } } fn driveListening(self: *Ports, comptime i: usize, fd: i32, chip: *w5100.W5100) void { const got = linux.accept4(fd, null, null, linux.SOCK.NONBLOCK | linux.SOCK.CLOEXEC); if (linux.errno(got) != .SUCCESS) return; // nobody yet _ = linux.close(fd); // one connection to a socket, the way the chip has it self.hosts[i] = .{ .stream = @intCast(got) }; chip.connected(i); } fn driveStream(self: *Ports, comptime i: usize, fd: i32, chip: *w5100.W5100) void { // Out: whatever the chip has queued, until the ring is empty or the // socket will take no more. while (true) { const out = chip.sent(i); if (out.len == 0) break; const wrote = linux.write(fd, out.ptr, out.len); if (linux.errno(wrote) != .SUCCESS) break; if (wrote == 0) break; chip.didSend(i, @intCast(wrote)); } // In: as much as is waiting, into the receive ring. var buffer: [chunk]u8 = undefined; const read = linux.read(fd, &buffer, buffer.len); switch (linux.errno(read)) { .SUCCESS => if (read == 0) { // The peer closed. _ = linux.close(fd); self.hosts[i] = .idle; chip.disconnected(i); } else { _ = chip.receive(i, buffer[0..read]); }, .AGAIN => {}, else => { _ = linux.close(fd); self.hosts[i] = .idle; chip.disconnected(i); }, } } fn driveDatagram(self: *Ports, comptime i: usize, fd: i32, chip: *w5100.W5100) void { _ = self; // Out: each burst the chip queued goes as one datagram to the // destination the driver set. const out = chip.sent(i); if (out.len > 0) { const dest = chip.destination(i); const to = address(dest.ip, dest.port); const rc = linux.sendto(fd, out.ptr, out.len, 0, @ptrCast(&to), @sizeOf(linux.sockaddr.in)); if (linux.errno(rc) == .SUCCESS) chip.didSend(i, @intCast(out.len)); } // In: one datagram, wrapped in the header the W5100 puts on it. var buffer: [chunk]u8 = undefined; var from: linux.sockaddr.in = undefined; var from_len: u32 = @sizeOf(linux.sockaddr.in); const read = linux.recvfrom(fd, &buffer, buffer.len, linux.MSG.DONTWAIT, @ptrCast(&from), &from_len); if (linux.errno(read) == .SUCCESS) { const ip: [4]u8 = @bitCast(from.addr); const port = std.mem.bigToNative(u16, from.port); _ = chip.receiveDatagram(i, ip, port, buffer[0..read]); } } // -- the small syscalls --------------------------------------------------- fn socket(kind: u32) ?i32 { const created = linux.socket(linux.AF.INET, kind | linux.SOCK.NONBLOCK | linux.SOCK.CLOEXEC, 0); if (linux.errno(created) != .SUCCESS) return null; return @intCast(created); } fn reuse(fd: i32) void { const one: u32 = 1; _ = linux.setsockopt(fd, linux.SOL.SOCKET, linux.SO.REUSEADDR, @ptrCast(&one), @sizeOf(u32)); } fn address(ip: [4]u8, port: u16) linux.sockaddr.in { return .{ .port = std.mem.nativeToBig(u16, port), .addr = @bitCast(ip) }; } fn writable(fd: i32) bool { var poll = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.OUT, .revents = 0 }}; const rc = linux.poll(&poll, 1, 0); if (linux.errno(rc) != .SUCCESS) return false; return poll[0].revents & linux.POLL.OUT != 0; } }; const testing = std.testing; test "a loopback connection carries bytes both ways through the chip" { if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // Two chips and two sets of ports: one listens, the other connects to it, // exactly as two Apple IIs on a network would. var server_chip: w5100.W5100 = .{}; var server: Ports = .{}; defer server.deinit(); var client_chip: w5100.W5100 = .{}; var client: Ports = .{}; defer client.deinit(); // The server listens. A port of 0 lets the system pick a free one, which we // then read back to point the client at. server.beginListen(0, 0); var bound: linux.sockaddr.in = undefined; var len: u32 = @sizeOf(linux.sockaddr.in); _ = linux.getsockname(server.hosts[0].fd().?, @ptrCast(&bound), &len); const port = std.mem.bigToNative(u16, bound.port); // The client connects to 127.0.0.1 at that port. client.beginConnect(0, .{ 127, 0, 0, 1 }, port); // Pump both until the server has accepted and the client is established. var spins: usize = 0; while (spins < 100) : (spins += 1) { server.pump(&server_chip); client.pump(&client_chip); if (server.hosts[0] == .stream and client.hosts[0] == .stream) break; } try testing.expect(server.hosts[0] == .stream); try testing.expect(client.hosts[0] == .stream); // The client sends: put bytes in its transmit ring and move the write // pointer past them, which is all a SEND turns into, then drive the socket. @memcpy(client_chip.memory[0x4000..][0..5], "hello"); client_chip.setWord(0x0400 + 0x24, 5); // Sn_TX_WR = 5 client.driveStream(0, client.hosts[0].fd().?, &client_chip); // The server receives it. var spins2: usize = 0; while (spins2 < 100) : (spins2 += 1) { server.pump(&server_chip); if (server_chip.word(0x0400 + 0x26) >= 5) break; // Sn_RX_RSR } try testing.expectEqual(@as(u16, 5), server_chip.word(0x0400 + 0x26)); try testing.expectEqualSlices(u8, "hello", server_chip.memory[0x6000..][0..5]); }