// SPDX-FileCopyrightText: 2026 Jeffrey C. Ollie // // SPDX-License-Identifier: MIT //! A Hayes-style modem on the end of the Super Serial Card's wire, dialing out //! over the host's TCP rather than a phone line. //! //! A modem is a device on the serial line, not a card: the machine talks to the //! 6551 the same as ever, and this sits at the far end of it where a file //! otherwise would (see `session8.zig`'s serial pump). It has the two states a //! Hayes modem has — **command**, where it reads the machine's bytes as an `AT` //! command line and answers with result codes, and **data** (online), where it //! passes bytes through to and from whatever it has dialed. The `+++` escape, //! with its guard time of silence, is what crosses back from data to command //! without dropping the connection. //! //! What a phone number dials is a host and a port: `ATDT host:port` opens a TCP //! connection there, which is how a machine reaches a telnet BBS. The command //! set, the result codes and the S-registers are the Hayes Smartmodem's, the //! set every terminal program of the era drove (Hayes Microcomputer Products, 1981). The de facto //! standard rather than one primary source, and modeled to what those programs //! expect: `ATE`/`Q`/`V` for echo, quiet and verbose result codes, `ATH` to //! hang up, `ATZ` to reset, `ATA` to answer, `ATO` to go back online, `ATDT`/ //! `ATDP`/`ATD` to dial, and `ATS=`/`ATS?` for the registers. //! //! This is the modem and nothing of the host: the state machine, the command //! line, the result codes and the two byte streams. `Line` below is the host //! end — the TCP socket the streams cross — and the session moves bytes between //! the two and acts on what the modem `wants`. const std = @import("std"); const builtin = @import("builtin"); /// How much the two byte queues hold. The machine-bound one is large because /// data can arrive from the socket faster than a 300-baud line drains it, and /// the modem's own buffer is what stands between the two rates — the session /// stops reading the socket when this is full, which is the modem's flow /// control. const to_machine_capacity = 8192; const to_socket_capacity = 2048; /// The default port a bare host dials, which is telnet — what a BBS listens on /// unless it says otherwise. pub const default_port: u16 = 23; /// The Hayes result codes, with their numeric form and their verbose words. pub const Result = enum { ok, connect, ring, no_carrier, err, no_dialtone, busy, no_answer, fn code(self: Result) u8 { return switch (self) { .ok => 0, .connect => 1, .ring => 2, .no_carrier => 3, .err => 4, .no_dialtone => 6, .busy => 7, .no_answer => 8, }; } fn word(self: Result) []const u8 { return switch (self) { .ok => "OK", .connect => "CONNECT", .ring => "RING", .no_carrier => "NO CARRIER", .err => "ERROR", .no_dialtone => "NO DIALTONE", .busy => "BUSY", .no_answer => "NO ANSWER", }; } }; /// What the modem wants the host end to do, taken by the session once. pub const Wants = union(enum) { nothing, /// Dial out: open a TCP connection to this host and port. dial: struct { host: []const u8, port: u16 }, /// Hang up: close the connection. hangup, /// Answer a call that is ringing. answer, }; const Mode = enum { command, data }; pub const Modem = struct { mode: Mode = .command, /// The command settings: whether typed characters are echoed back, whether /// result codes are sent at all, and whether they are words or a digit. echo: bool = true, quiet: bool = false, verbose: bool = true, /// Whether a connection is up. In command mode with a connection up, `ATO` /// returns to data mode; a dropped connection sends NO CARRIER. online: bool = false, /// The rate to report on CONNECT, set by the session from the card's baud. connect_rate: u32 = 300, /// The S-registers, of which the ones that matter are S0 (rings before /// auto-answer), S2 (the escape character), S3 (carriage return), S4 (line /// feed) and S12 (the escape guard time, in fiftieths of a second). s: [16]u8 = blk: { var d = [_]u8{0} ** 16; d[2] = '+'; d[3] = 13; d[4] = 10; d[5] = 8; d[6] = 2; d[7] = 30; d[12] = 50; break :blk d; }, /// The command line being typed, in command mode. line: [128]u8 = undefined, line_len: usize = 0, /// The escape sequence's progress: how many escape characters have come in /// a row, and the cycle the last byte of any kind arrived on, so the guard /// time of silence around `+++` can be timed. escapes: u8 = 0, last_byte_at: u64 = 0, /// How many cycles a fiftieth of a second is, so S12 can be timed. Set by /// the session from the machine's clock. cycles_per_tick: u64 = 1_020_500 / 50, /// Bytes bound for the machine (result codes, echoes, and data coming in), /// and bytes bound for the socket (data going out). to_machine: [to_machine_capacity]u8 = undefined, to_machine_len: usize = 0, to_socket: [to_socket_capacity]u8 = undefined, to_socket_len: usize = 0, wants: Wants = .nothing, pub fn reset(self: *Modem) void { const cpt = self.cycles_per_tick; const rate = self.connect_rate; self.* = .{ .cycles_per_tick = cpt, .connect_rate = rate }; } fn cr(self: *const Modem) u8 { return self.s[3]; } fn lf(self: *const Modem) u8 { return self.s[4]; } fn toMachine(self: *Modem, bytes: []const u8) void { const room = to_machine_capacity - self.to_machine_len; const n = @min(room, bytes.len); @memcpy(self.to_machine[self.to_machine_len..][0..n], bytes[0..n]); self.to_machine_len += n; } fn toMachineByte(self: *Modem, byte: u8) void { self.toMachine(&.{byte}); } /// Puts a result code on the machine's line, as a word between CR/LF pairs /// or a single digit and a CR, unless quiet. fn respond(self: *Modem, result: Result) void { if (self.quiet) return; if (self.verbose) { self.toMachine(&.{ self.cr(), self.lf() }); if (result == .connect and self.connect_rate > 300) { var buf: [24]u8 = undefined; self.toMachine(std.fmt.bufPrint(&buf, "CONNECT {d}", .{self.connect_rate}) catch "CONNECT"); } else { self.toMachine(result.word()); } self.toMachine(&.{ self.cr(), self.lf() }); } else { self.toMachine(&.{ '0' + result.code(), self.cr() }); } } // -- what the session drives --------------------------------------------- /// A byte from the machine, on the given cycle. pub fn fromMachine(self: *Modem, byte: u8, cycle: u64) void { switch (self.mode) { .command => self.commandByte(byte), .data => self.dataByte(byte, cycle), } self.last_byte_at = cycle; } fn commandByte(self: *Modem, byte: u8) void { if (self.echo) self.toMachineByte(byte); if (byte == self.s[5]) { // backspace if (self.line_len > 0) self.line_len -= 1; return; } if (byte == self.cr()) { self.runLine(); self.line_len = 0; return; } if (byte == self.lf()) return; // ignored; the CR is what acts if (self.line_len < self.line.len) { self.line[self.line_len] = byte; self.line_len += 1; } } fn dataByte(self: *Modem, byte: u8, cycle: u64) void { // The escape sequence: the escape character, three in a row, each // preceded and followed by a guard time of silence, so a chance `+++` // in the data does not drop the line (Heatherington, 1985). The guard // *before* the first is relaxed here, as many terminal programs and // emulators do, but the count and the trailing guard (in `tick`) are kept. if (byte == self.s[2]) { self.escapes += 1; } else { self.escapes = 0; } if (self.to_socket_len < to_socket_capacity) { self.to_socket[self.to_socket_len] = byte; self.to_socket_len += 1; } _ = cycle; } /// Called each frame so the escape sequence's trailing guard time can be /// noticed: three escape characters, then silence, is the way back to /// command mode without dropping the line. pub fn tick(self: *Modem, cycle: u64) void { if (self.mode == .data and self.escapes >= 3 and cycle - self.last_byte_at >= @as(u64, self.s[12]) * self.cycles_per_tick) { // Take the three escape characters back off the outgoing stream — // they were the escape, not data to send. if (self.to_socket_len >= 3) self.to_socket_len -= 3; self.escapes = 0; self.mode = .command; self.respond(.ok); } } /// A settled `AT` line. Everything after the `AT` is a run of commands, /// applied left to right; a dial consumes the rest of the line. fn runLine(self: *Modem) void { const line = self.line[0..self.line_len]; if (line.len < 2 or !std.ascii.eqlIgnoreCase(line[0..2], "AT")) { if (line.len == 0) return; // a bare CR does nothing self.respond(.err); return; } var i: usize = 2; var emitted = false; // a command (dial, answer, online) gave its own result while (i < line.len) { const c = std.ascii.toUpper(line[i]); i += 1; switch (c) { ' ' => {}, 'E' => self.echo = digit(line, &i) != 0, 'Q' => self.quiet = digit(line, &i) != 0, 'V' => self.verbose = digit(line, &i) != 0, 'H' => self.wants = if (digit(line, &i) == 0) .hangup else self.wants, 'Z' => self.reset(), 'A' => { self.wants = .answer; emitted = true; i = line.len; }, 'O' => { if (self.online) { self.mode = .data; self.respond(.connect); emitted = true; } i = line.len; }, 'D' => { self.dial(line[i..]); emitted = true; i = line.len; }, 'S' => if (!self.sregister(line, &i)) { self.respond(.err); return; }, // Letters a modem takes and this does not act on — speaker, // dialing options, the `&` extended set — are accepted so an // initialisation string does not fail on them. 'M', 'L', 'X', 'N', 'W', 'P', 'T', 'C', 'F', 'Y', 'B' => _ = digit(line, &i), '&' => { if (i < line.len) i += 1; // the letter _ = digit(line, &i); }, else => { self.respond(.err); return; }, } } if (!emitted) self.respond(.ok); } /// Reads an optional decimal at `i.*`, advancing past it; no digits is nought. fn digit(line: []const u8, i: *usize) u32 { var value: u32 = 0; var any = false; while (i.* < line.len and line[i.*] >= '0' and line[i.*] <= '9') : (i.* += 1) { value = value * 10 + (line[i.*] - '0'); any = true; } return if (any) value else 0; } /// `S=` sets a register; `S?` reports one. Returns false on a /// malformed one. fn sregister(self: *Modem, line: []const u8, i: *usize) bool { const n = digit(line, i); if (i.* >= line.len) return false; if (line[i.*] == '=') { i.* += 1; const v = digit(line, i); if (n < self.s.len) self.s[n] = @truncate(v); return true; } if (line[i.*] == '?') { i.* += 1; var buf: [8]u8 = undefined; const v: u8 = if (n < self.s.len) self.s[n] else 0; self.toMachine(&.{ self.cr(), self.lf() }); self.toMachine(std.fmt.bufPrint(&buf, "{d:0>3}", .{v}) catch "000"); self.toMachine(&.{ self.cr(), self.lf() }); return true; } return false; } /// The dial string after `ATD`: an optional method (`T`/`P`) and modifiers, /// then a host with an optional `:port`. Sets `wants` to dial it. fn dial(self: *Modem, raw: []const u8) void { var s = raw; // Skip a leading method letter and trim spaces, dashes and parentheses, // which a phone number carries and a host does not. while (s.len > 0 and (s[0] == 'T' or s[0] == 'P' or s[0] == 't' or s[0] == 'p' or s[0] == ' ')) s = s[1..]; var host_buf: [128]u8 = undefined; var n: usize = 0; var port: u16 = default_port; var seen_colon = false; var port_val: u32 = 0; for (s) |ch| { switch (ch) { ' ', '-', '(', ')', ',' => {}, ':' => seen_colon = true, else => if (seen_colon) { if (ch >= '0' and ch <= '9') port_val = port_val * 10 + (ch - '0'); } else if (n < host_buf.len) { host_buf[n] = ch; n += 1; }, } } if (seen_colon and port_val > 0 and port_val <= 65535) port = @intCast(port_val); // The host is copied into the line buffer's tail so the slice in `wants` // outlives this call until the session takes it (which it does at once). const start = self.line.len - n; @memcpy(self.line[start..][0..n], host_buf[0..n]); self.wants = .{ .dial = .{ .host = self.line[start..][0..n], .port = port } }; } pub fn takeWants(self: *Modem) Wants { const w = self.wants; self.wants = .nothing; return w; } /// The session calls these as the socket does its part. pub fn onConnect(self: *Modem, rate: u32) void { self.online = true; self.mode = .data; self.connect_rate = rate; self.escapes = 0; self.respond(.connect); } pub fn onDialFailed(self: *Modem, result: Result) void { self.online = false; self.mode = .command; self.respond(result); } pub fn onCarrierLost(self: *Modem) void { if (self.online) self.respond(.no_carrier); self.online = false; self.mode = .command; } pub fn onRing(self: *Modem) void { self.respond(.ring); } /// Data from the socket, handed to the machine. Only meaningful with a /// connection up; the caller checks `roomForCarrier` first. pub fn onCarrier(self: *Modem, bytes: []const u8) void { self.toMachine(bytes); } pub fn roomForCarrier(self: *const Modem) usize { return to_machine_capacity - self.to_machine_len; } /// Bytes the machine should read, and taking them off the queue. pub fn machineBytes(self: *const Modem) []const u8 { return self.to_machine[0..self.to_machine_len]; } pub fn takeMachine(self: *Modem, count: usize) void { const n = @min(count, self.to_machine_len); std.mem.copyForwards(u8, self.to_machine[0 .. self.to_machine_len - n], self.to_machine[n..self.to_machine_len]); self.to_machine_len -= n; } /// Bytes to send to the socket, and taking them off the queue. pub fn socketBytes(self: *const Modem) []const u8 { return self.to_socket[0..self.to_socket_len]; } pub fn takeSocket(self: *Modem, count: usize) void { const n = @min(count, self.to_socket_len); std.mem.copyForwards(u8, self.to_socket[0 .. self.to_socket_len - n], self.to_socket[n..self.to_socket_len]); self.to_socket_len -= n; } }; /// The host end of the modem: the TCP socket its two byte streams cross. Like /// the LocalTalk and Uthernet backends it talks to the system directly and is /// Linux only, because the standard library has no non-blocking connect or /// accept to offer; on any other system the modem finds no dial tone. pub const Line = struct { const linux = std.os.linux; state: State = .idle, /// The rate reported on CONNECT, from the card's baud. connect_rate: u32 = 2400, /// Set when a dial could not even start (a name that would not resolve, or /// no socket), so `pump` can tell the modem NO CARRIER on the next step. dial_failed: bool = false, const State = union(enum) { idle, connecting: i32, stream: i32, listening: i32, fn fd(self: State) ?i32 { return switch (self) { .idle => null, inline else => |f| f, }; } }; pub fn deinit(self: *Line) void { if (self.state.fd()) |f| _ = linux.close(f); self.state = .idle; } /// Dials out: resolves the host and starts a non-blocking connect. The /// modem is told the outcome through `onConnect`/`onDialFailed` as the /// connect finishes, which `pump` sees. pub fn dial(self: *Line, host: []const u8, port: u16) void { if (comptime builtin.os.tag != .linux) return self.fail(); self.deinit(); const ip = resolve(host) orelse return self.fail(); const fd = socket(linux.SOCK.STREAM) orelse return self.fail(); const to = address(ip, port); const rc = linux.connect(fd, @ptrCast(&to), @sizeOf(linux.sockaddr.in)); switch (linux.errno(rc)) { .SUCCESS => self.state = .{ .stream = fd }, .INPROGRESS, .INTR => self.state = .{ .connecting = fd }, else => { _ = linux.close(fd); self.fail(); }, } } fn fail(self: *Line) void { self.state = .{ .idle = {} }; self.dial_failed = true; } /// Listens for one incoming call. pub fn listen(self: *Line, port: u16) void { if (comptime builtin.os.tag != .linux) return; self.deinit(); 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 or linux.errno(linux.listen(fd, 1)) != .SUCCESS) { _ = linux.close(fd); return; } self.state = .{ .listening = fd }; } pub fn hangup(self: *Line) void { self.deinit(); } pub fn isConnected(self: *const Line) bool { return self.state == .stream; } /// Moves the modem and the socket on a step: finishes a connect, accepts a /// call, and carries bytes each way. Returns nothing; it drives the modem /// through the callbacks. pub fn pump(self: *Line, modem: *Modem) void { if (comptime builtin.os.tag != .linux) return; if (self.dial_failed) { self.dial_failed = false; modem.onDialFailed(.no_carrier); } switch (self.state) { .idle => {}, .connecting => |fd| { if (!writable(fd)) return; 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.state = .{ .stream = fd }; modem.onConnect(self.connect_rate); } else { _ = linux.close(fd); self.state = .idle; modem.onDialFailed(.no_carrier); } }, .listening => |fd| { const got = linux.accept4(fd, null, null, linux.SOCK.NONBLOCK | linux.SOCK.CLOEXEC); if (linux.errno(got) != .SUCCESS) return; _ = linux.close(fd); self.state = .{ .stream = @intCast(got) }; // A call is ringing; the modem answers it (auto-answer or ATA). modem.onConnect(self.connect_rate); }, .stream => |fd| self.carry(fd, modem), } } fn carry(self: *Line, fd: i32, modem: *Modem) void { // Out: whatever the modem has queued for the socket. while (true) { const out = modem.socketBytes(); if (out.len == 0) break; const wrote = linux.write(fd, out.ptr, out.len); if (linux.errno(wrote) != .SUCCESS or wrote == 0) break; modem.takeSocket(@intCast(wrote)); } // In: as much as the modem has room for, so the slow line does not lose // what the socket delivers fast. const room = modem.roomForCarrier(); if (room == 0) return; var buffer: [2048]u8 = undefined; const want = @min(room, buffer.len); const read = linux.read(fd, &buffer, want); switch (linux.errno(read)) { .SUCCESS => if (read == 0) { _ = linux.close(fd); self.state = .idle; modem.onCarrierLost(); } else modem.onCarrier(buffer[0..read]), .AGAIN => {}, else => { _ = linux.close(fd); self.state = .idle; modem.onCarrierLost(); }, } } // -- the small syscalls, as in ltoudp.zig and uthernet.zig --------------- 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 }}; if (linux.errno(linux.poll(&poll, 1, 0)) != .SUCCESS) return false; return poll[0].revents & linux.POLL.OUT != 0; } }; /// Turns a dial string's host into an address: a dotted quad is taken as is, /// and a name is looked up with one A-record query to the first nameserver in /// `/etc/resolv.conf`. Null if it cannot be resolved, which the modem reports /// as NO CARRIER. A small resolver of its own because the binary links no libc /// and the standard library's `resolve` only parses a literal address. fn resolve(host: []const u8) ?[4]u8 { if (comptime builtin.os.tag != .linux) return null; if (parseIp(host)) |ip| return ip; return resolveDns(host); } fn parseIp(text: []const u8) ?[4]u8 { var out: [4]u8 = undefined; var parts = std.mem.splitScalar(u8, text, '.'); for (&out) |*b| { const p = parts.next() orelse return null; b.* = std.fmt.parseInt(u8, p, 10) catch return null; } return if (parts.next() == null) out else null; } fn resolveDns(host: []const u8) ?[4]u8 { const linux = std.os.linux; const ns = nameserver() orelse return null; // The query: a twelve-byte header (one question, recursion desired), then // the name as length-prefixed labels, then QTYPE=A and QCLASS=IN. var query: [512]u8 = undefined; var n: usize = 0; const id: u16 = 0x2665; std.mem.writeInt(u16, query[0..2], id, .big); std.mem.writeInt(u16, query[2..4], 0x0100, .big); // recursion desired std.mem.writeInt(u16, query[4..6], 1, .big); // one question @memset(query[6..12], 0); n = 12; var labels = std.mem.splitScalar(u8, host, '.'); while (labels.next()) |label| { if (label.len == 0 or label.len > 63 or n + 1 + label.len + 5 > query.len) return null; query[n] = @intCast(label.len); n += 1; @memcpy(query[n..][0..label.len], label); n += label.len; } query[n] = 0; n += 1; std.mem.writeInt(u16, query[n..][0..2], 1, .big); // A std.mem.writeInt(u16, query[n + 2 ..][0..2], 1, .big); // IN n += 4; const fd = Line.socket(linux.SOCK.DGRAM) orelse return null; defer _ = linux.close(fd); const to = Line.address(ns, 53); if (linux.errno(linux.sendto(fd, &query, n, 0, @ptrCast(&to), @sizeOf(linux.sockaddr.in))) != .SUCCESS) return null; // Wait up to two seconds for the reply — dialing is a deliberate, one-off // pause, so a short block here is acceptable where it would not be in the // frame loop. var poll = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.IN, .revents = 0 }}; if (linux.errno(linux.poll(&poll, 1, 2000)) != .SUCCESS or poll[0].revents & linux.POLL.IN == 0) return null; var reply: [512]u8 = undefined; const got = linux.recvfrom(fd, &reply, reply.len, 0, null, null); if (linux.errno(got) != .SUCCESS or got < 12) return null; return firstAnswer(reply[0..got]); } /// The first `nameserver` line of `/etc/resolv.conf`, as four bytes. fn nameserver() ?[4]u8 { const linux = std.os.linux; const fd = linux.open("/etc/resolv.conf", .{ .ACCMODE = .RDONLY }, 0); if (linux.errno(fd) != .SUCCESS) return null; defer _ = linux.close(@intCast(fd)); var buf: [4096]u8 = undefined; const got = linux.read(@intCast(fd), &buf, buf.len); if (linux.errno(got) != .SUCCESS) return null; var lines = std.mem.splitScalar(u8, buf[0..got], '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t\r"); const prefix = "nameserver "; if (std.mem.startsWith(u8, trimmed, prefix)) { if (parseIp(std.mem.trim(u8, trimmed[prefix.len..], " \t"))) |ip| return ip; } } return null; } /// Walks a DNS reply's answers and returns the first A record's address. fn firstAnswer(reply: []const u8) ?[4]u8 { const answers = std.mem.readInt(u16, reply[6..8], .big); var at: usize = 12; // Skip the question: a name, then QTYPE and QCLASS. at = skipName(reply, at) orelse return null; at += 4; var i: usize = 0; while (i < answers) : (i += 1) { at = skipName(reply, at) orelse return null; if (at + 10 > reply.len) return null; const rtype = std.mem.readInt(u16, reply[at..][0..2], .big); const rdlen = std.mem.readInt(u16, reply[at + 8 ..][0..2], .big); at += 10; if (at + rdlen > reply.len) return null; if (rtype == 1 and rdlen == 4) return reply[at..][0..4].*; at += rdlen; } return null; } /// Steps past a DNS name at `at`, following a compression pointer if it hits /// one (a pointer ends the name), and returns where the name's field ends. fn skipName(reply: []const u8, start: usize) ?usize { var at = start; while (at < reply.len) { const len = reply[at]; if (len == 0) return at + 1; if (len & 0xc0 == 0xc0) return at + 2; // a pointer, two bytes, ends it at += 1 + len; } return null; } const testing = std.testing; /// Feeds a whole string to the modem as if the machine typed it, then returns /// what the modem put on the machine's line, clearing it. fn typed(m: *Modem, s: []const u8) []const u8 { for (s) |c| m.fromMachine(c, 0); return m.machineBytes(); } test "AT gets an OK, and echo and result codes can be turned off" { var m: Modem = .{}; try testing.expectEqualStrings("AT\r\r\nOK\r\n", typed(&m, "AT\r")); m.takeMachine(m.to_machine_len); // ATE0 turns echo off; ATV0 makes result codes numeric; ATQ1 silences them. _ = typed(&m, "ATE0\r"); m.takeMachine(m.to_machine_len); try testing.expectEqualStrings("\r\nOK\r\n", typed(&m, "AT\r")); // no echo now m.takeMachine(m.to_machine_len); _ = typed(&m, "ATV0\r"); m.takeMachine(m.to_machine_len); try testing.expectEqualStrings("0\r", typed(&m, "AT\r")); // numeric OK } test "a bad command is an ERROR" { var m: Modem = .{}; m.echo = false; try testing.expectEqualStrings("\r\nERROR\r\n", typed(&m, "AT%\r")); } test "ATDT dials a host and a port, and the session is asked to connect" { var m: Modem = .{}; m.echo = false; _ = typed(&m, "ATDT bbs.example.com:6502\r"); const w = m.takeWants(); try testing.expect(w == .dial); try testing.expectEqualStrings("bbs.example.com", w.dial.host); try testing.expectEqual(@as(u16, 6502), w.dial.port); // A bare host dials telnet. _ = typed(&m, "ATDT 10.0.0.1\r"); try testing.expectEqual(@as(u16, 23), m.takeWants().dial.port); } test "connecting goes online and CONNECT reports the rate" { var m: Modem = .{}; m.echo = false; _ = typed(&m, "ATDT 10.0.0.1\r"); _ = m.takeWants(); m.takeMachine(m.to_machine_len); m.onConnect(2400); try testing.expectEqualStrings("\r\nCONNECT 2400\r\n", m.machineBytes()); try testing.expect(m.mode == .data); // In data mode, a byte from the machine is passed to the socket. m.takeMachine(m.to_machine_len); m.fromMachine('X', 100); try testing.expectEqualStrings("X", m.socketBytes()); } test "the +++ escape returns to command mode after the guard time, keeping the line" { var m: Modem = .{}; m.echo = false; m.cycles_per_tick = 1; // a tick is one cycle, so the guard is S12 cycles _ = typed(&m, "ATDT 10.0.0.1\r"); _ = m.takeWants(); m.onConnect(1200); m.takeMachine(m.to_machine_len); // Three escape characters in a row, at cycle 1000. m.fromMachine('+', 1000); m.fromMachine('+', 1000); m.fromMachine('+', 1000); try testing.expect(m.mode == .data); // not yet — the guard has not passed // Before the guard elapses, nothing happens. m.tick(1000 + @as(u64, m.s[12]) - 1); try testing.expect(m.mode == .data); // After it, back to command mode with an OK, and still online. m.tick(1000 + @as(u64, m.s[12])); try testing.expect(m.mode == .command); try testing.expect(m.online); try testing.expectEqualStrings("\r\nOK\r\n", m.machineBytes()); // The three pluses were taken back off the outgoing stream. try testing.expectEqual(@as(usize, 0), m.to_socket_len); // ATO returns online. m.takeMachine(m.to_machine_len); _ = typed(&m, "ATO\r"); try testing.expect(m.mode == .data); } test "a dropped carrier sends NO CARRIER and returns to command mode" { var m: Modem = .{}; m.echo = false; _ = typed(&m, "ATDT 10.0.0.1\r"); _ = m.takeWants(); m.onConnect(300); m.takeMachine(m.to_machine_len); m.onCarrierLost(); try testing.expectEqualStrings("\r\nNO CARRIER\r\n", m.machineBytes()); try testing.expect(m.mode == .command); try testing.expect(!m.online); } test "an S-register can be set and read back" { var m: Modem = .{}; m.echo = false; _ = typed(&m, "ATS0=2\r"); try testing.expectEqual(@as(u8, 2), m.s[0]); m.takeMachine(m.to_machine_len); try testing.expectEqualStrings("\r\n002\r\n\r\nOK\r\n", typed(&m, "ATS0?\r")); } test "a dial to a listening line connects and carries bytes both ways" { if (comptime builtin.os.tag != .linux) return error.SkipZigTest; // A modem answering, and a modem dialing it on the loopback interface. var answerer: Modem = .{ .echo = false }; var answer_line: Line = .{}; defer answer_line.deinit(); answer_line.listen(0); // a free port the system picks var bound: std.os.linux.sockaddr.in = undefined; var len: u32 = @sizeOf(std.os.linux.sockaddr.in); _ = std.os.linux.getsockname(answer_line.state.fd().?, @ptrCast(&bound), &len); const port = std.mem.bigToNative(u16, bound.port); var caller: Modem = .{ .echo = false }; var caller_line: Line = .{}; defer caller_line.deinit(); caller_line.dial("127.0.0.1", port); // Pump both until each is online. var spins: usize = 0; while (spins < 200) : (spins += 1) { caller_line.pump(&caller); answer_line.pump(&answerer); if (caller.online and answerer.online) break; } try testing.expect(caller.online); try testing.expect(answerer.online); // Drop the CONNECT result codes both modems emitted on answering. answerer.takeMachine(answerer.to_machine_len); caller.takeMachine(caller.to_machine_len); // The caller sends "HI" (in data mode); the answerer receives it. caller.fromMachine('H', 0); caller.fromMachine('I', 0); caller_line.pump(&caller); spins = 0; while (spins < 200) : (spins += 1) { answer_line.pump(&answerer); if (answerer.to_machine_len >= 2) break; } try testing.expectEqualStrings("HI", answerer.machineBytes()); }