Modern Zig TN5250 + TN3270/TN3270E terminal client (clean-room)
  • Zig 96.5%
  • Shell 2.7%
  • Objective-C 0.6%
  • jq 0.1%
  • Makefile 0.1%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Sean OMeara 84047933c7
All checks were successful
binjovi/ci Binjovi completed the frozen plan
Suppress Read Modified nulls, clear on CLEAR, add NVT scrolling margins
Four protocol fixes, each with a failing test first:

- Operator Enter and PF keys on a formatted 3270 screen sent each null
  cell as a space (0x40), because the builder encoded field cells from
  their glyphs. IBM GA23-0059 Read Modified suppresses nulls anywhere in
  the field data, and the host Read Modified path already did. The
  builder now skips a null cell with the rule the unformatted builder
  uses. A typed space is EBCDIC 0x40 and stays. A field that Erase EOF
  cleared now goes out as its SBA alone. Seven tests had synthetic cells
  with a glyph and no raw byte; they now carry real raw bytes.
- CLEAR in an LU-LU session sent the short-read AID but kept the screen,
  the field attributes and the cursor. After the AID is sent, the session
  now returns to the default size, fills the buffer with nulls, removes
  every field attribute and moves the cursor to address 0. A failed send
  leaves the session as it was.
- Insert Line and Delete Line in embedded NVT data kept the cursor
  column. ECMA-48 8.3.67 and 8.3.32 move it to the line home position.
- Embedded NVT data now honors the DEC top and bottom scrolling margins
  (CSI Pt ; Pb r). Line feed, index, next line, reverse index, auto-wrap,
  insert line, delete line, scroll up and scroll down act inside the
  region; a line feed below it does not scroll. The margins are clamped
  where they are used, so a screen resize cannot index outside the
  screen. The fuzz entry for the parser still holds.

Not fixed: the parser wraps at once at the last column instead of
deferring the wrap to the next character, as a VT100 does.

Checks in the zig-builder:v22 image: zig fmt --check, zig build check,
the package contract and target selection scripts (full check profile),
and 60 s of zig build test --fuzz with no crash.
2026-10-26 11:55:39 +01:00
ci Reject misplaced terminal markers after ten scoped audit rounds 2026-10-18 06:42:45 +02:00
docs Keep audit evidence independent of CI provider names 2026-10-18 06:43:34 +02:00
macos fix: retain protocol-specific GUI status during Zig migration 2026-10-17 05:11:47 +02:00
packaging build(packaging): add nfpm spec for .deb/.rpm 2026-06-19 11:42:20 +02:00
scripts Support compound ICU DBCS mappings 2026-10-14 21:47:00 +02:00
src Suppress Read Modified nulls, clear on CLEAR, add NVT scrolling margins 2026-10-26 11:55:39 +01:00
windows fix: retain protocol-specific GUI status during Zig migration 2026-10-17 05:11:47 +02:00
.gitattributes fix(cicd): auto-resolve CHANGELOG land conflicts via .gitattributes merge=union 2026-07-05 12:14:45 +00:00
.gitignore adding .DS_Store to gitignore 2026-06-23 10:13:51 +02:00
AGENTS.md Keep CLI invocation headless and give the macOS app an explicit entry point 2026-10-18 06:30:06 +02:00
build.zig Reject misplaced terminal markers after ten scoped audit rounds 2026-10-18 06:42:45 +02:00
build.zig.zon fix: update Zelnet build modes for Zig 0.17 2026-10-17 04:25:24 +02:00
CHANGELOG.md Suppress Read Modified nulls, clear on CLEAR, add NVT scrolling margins 2026-10-26 11:55:39 +01:00
CLAUDE.md feat: zelnet foundation — TN5250 + TN3270 protocol core (red/green TDD) 2026-06-17 17:48:35 +02:00
Makefile Add a std.testing.fuzz entry for the ECMA-48 parser 2026-10-26 11:05:25 +01:00
README.md Keep CLI invocation headless and give the macOS app an explicit entry point 2026-10-18 06:30:06 +02:00
STYLE.md Upgrade Zelnet to Zig 0.17.0 2026-10-17 03:54:16 +02:00

zelnet(1)

zelnet is a terminal client for IBM systems, written in idiomatic Zig. It is a clean-room replacement for tn5250. It also drives tn3270 mainframe screens. zelnet includes the IBM i Host Server data layer in the same binary. This layer covers IFS, SQL, CL, data queues, and source export.

NAME

zelnet — a terminal client for TN5250, TN3270, and plain telnet, and an IBM i Host Server client

SYNOPSIS

zelnet [options] <host> [port]
zelnet --tn3270 [--model N] [options] <host> [port]
zelnet --nvt [options] <host> [port]
zelnet <verb> [args ...]
zelnet --demo | --probe <host> [port] | --version

where <verb> is one of auth ifs sql xfer cmd dq pgm src.

DESCRIPTION

zelnet is one statically-linked Zig 0.17 binary. It has two forms:

  • an interactive full-screen terminal for both IBM screen protocols
  • a set of scriptable IBM i Host Server verbs

The verbs are a clean-room build of the ACS data layer. Both forms share the same EBCDIC codec and TLS transport.

The zelnet command runs as the terminal CLI, including when stdin is a pipe or a file. Use --gui to request a native window in a build with -Dgui. The macOS app has a separate entry point that opens its native window when started without arguments. App invocations with arguments also use CLI mode. Use --cli to force terminal mode from the app. Windows GUI builds use --gui to open a window.

TN5250 supports IBM i and other midrange systems in the AS/400 lineage. It follows RFC 1205, RFC 2877, and RFC 4777. It uses GDS 12A0 records. It uses plain (row, col) buffer addressing. It supports field attributes, colour, and DBCS (double-byte) text through Shift-Out and Shift-In codes. It supports concealed password fields. zelnet negotiates IBM-3179-2 for a 24×80 colour display. It negotiates IBM-3477-FC for a wide 27×132 display.

TN3270 supports IBM z/OS mainframes. It follows RFC 1576 and RFC 2355. It uses 12-bit or 14-bit buffer addressing. It uses the extended 3270 data stream. This data stream supports colour and extended highlighting: blink, reverse, underscore, and intensify. It supports Query Reply. It supports alternate screen sizes for models 2 through 5: 24×80, 32×80, 43×80, and 27×132. zelnet negotiates terminal types from IBM-3278-2-E through IBM-3278-5-E. TN3270E negotiates the RFC 2355 option, device type and functions. It supports record headers, positive and negative responses, sequence numbers, BIND/UNBIND, SSCP-LU input, NVT records and basic TN3270 fallback. Use --lu NAME to request a device or pool. The native connect dialog uses its Device type / LU field for the same request. An explicit resource requires TN3270E; it cannot fall back to an unnamed basic session. In an interactive terminal or native window, Ctrl-F1 sends ATTN and Ctrl-F2 sends SYSREQ. Scripts use attn and sysreq.

--printer-output FILE connects as an IBM-3287-1 TN3270E printer. It accepts 3270 and SCS printer streams and writes a lossless spool archive. If an archive write fails, it sends the RFC 2355 printer error response, retries the complete record, and sends ERR-COND-CLEARED only after that retry succeeds. It retains later records during recovery. Use --lu NAME to select a printer device or pool. The archive starts with ZELNET-TN3270E-PRINT-1 and a newline. Each record then has a one-byte RFC 2355 data type, a four-byte big-endian payload length, and the unchanged host payload. Type 0 is 3270 data, type 1 is SCS data, and type 8 is a zero-length PRINT-EOJ job boundary. The raw spool sink answers Read Partition Query with a Null Query Reply because it advertises no extended display facilities.

NVT means plain telnet under RFC 854. Every telnet session starts here. --nvt gives a byte-level pass-through, like telnet(1). The enclosing terminal renders the screen. zelnet answers the telnet negotiation: remote ECHO, SGA, RFC 856 Binary in each direction, the local TERM value as TERMINAL-TYPE, and NAWS window reports. Binary mode preserves all eight data bits and still doubles IAC on the wire. Press Ctrl-] to disconnect. Interactive pass-through works in POSIX and Windows consoles.

The default 5250 path can select NVT from the host's option requests. Examples are WILL ECHO and DO NAWS. This is a detection rule, not a guarantee for every host. Use --nvt to select plain Telnet explicitly. See the protocol audit for supported options and gaps.

TLS is implicit. This is sometimes called "telnets". TLS is on by default for terminal port 992 and for every Host Server port. By default, zelnet verifies the certificate against the OS trust store. Use --self-signed or --no-verify to relax this check for hosts whose certificate is not publicly chained.

OPTIONS

Terminal-client options (the zelnet <host> [port] form):

Option Description
<host> [port] Host to connect to. port defaults to 23.
--tls / --no-tls Force the transport on or off. By default, zelnet picks automatically. It uses TLS only when port == 992.
--no-verify Encrypt the connection. Skip certificate verification.
--self-signed Accept a valid self-signed certificate. This is the default cert on IBM i.
--tn3270 Open an interactive TN3270 terminal for mainframes. Default is TN5250. Add --probe to read one screen and exit.
--nvt Use plain telnet as a pass-through. Common targets are Cisco devices, BBSes, and Unix telnetd.
--model N TN3270 screen model: 2, 3, 4, or 5. Each larger model gives an alternate screen size and the -E type. Default is 2.
--printer-output <file> Connect as an IBM-3287-1 TN3270E printer and write a lossless spool archive.
--demo Show a recorded pub400 sign-on transcript. It needs no network connection.
--probe Run a non-interactive connectivity check. It needs no credentials. Use it for diagnostics.
--login Run the sign-on, main-menu navigation, and sign-off check using ZELNET_USER and ZELNET_PW.
--play <script> Run a scripted TN5250 session. It signs on, then drives and checks panels. With --nvt, it runs a headless expect and send gate: expect <t>; send <t>; type <t>; enter; pause <ms>; dump.
--drive <script> Run a scripted TN3270 session. This implies --tn3270.
--record <file> Write an asciicast recording of a scripted session, from --play or --drive. zelnet uses this for the release reel.
--ccsid <n> Set the terminal display code page by CCSID. The default is 37. An unsupported CCSID is an error.
--devname <name> Request an IBM i display device name, up to 10 characters.
--kbdtype <type> Set the IBM i keyboard type, with 3 characters.
--host-codepage <n> / --host-charset <n> Set host device attributes. Both require --kbdtype. Set the matching local display page with --ccsid.
--assoc-printer <name> Associate an existing IBM i printer device with the display.
--auto-signon <method> Sign on during IBM i negotiation. Select des, sha1, or pwl4. Reads ZELNET_USER and ZELNET_PW; requires TLS with OS trust-store verification.
--current-library <name> / --initial-menu <name> / --initial-program <name> Set IBM i startup names, up to 10 characters each.
--gui / --cli Force the GUI or terminal launch mode.
--help, -h Print the option list. Then exit.
--version, -v Print the build banner and version. Then exit.

Terminal commands exit non-zero when connection setup fails. The 5250 probe requires a sign-on screen and a reply to its empty Enter; a plain NVT host is an error for that probe. A 3270 script action must receive a reply, and read must receive a record. Missing data or a closed connection fails the script. --probe and --login require a host; --login also requires credentials. IBM i device options require an explicit 5250 host. They also work when the CLI launches a native window. The client sends these options before terminal-type negotiation completes. It requests a startup response and retains the assigned device name, system name, and response code. A rejected device stops the connection.

--auto-signon sends a password substitute during the RFC 4777 seed exchange. Select des for host password levels 0 or 1, sha1 for 2 or 3, or pwl4 for 4. The host does not negotiate this method. The client uses fresh secure randomness, checks the startup response, and makes one sign-on attempt. A rejection stops the connection. This option works with a live terminal, a native window launched from the CLI, --login, and --play. It cannot be used with the credential-free --probe. With enhanced sign-on, --play starts its script at the configured initial screen.

The DES and SHA-1 wire tests use the published RFC 4777 examples. PWL4 uses the same tested password substitute as the Host Server client. Credentialed live enhanced sign-on has not yet been verified.

In an interactive session, use Tab or Shift-Tab to move between fields. Press Enter to transmit. F1 through F24 are the function keys. PgUp and PgDn perform Roll. Insert toggles Insert mode. Typed characters shift later field data to the first available null. Ctrl-R performs the IBM Reset key function. It leaves Insert mode and clears a local operator error. It does not clear a host command lock. The operator information area shows INSERT while Insert mode is active, IDEOGRAPHIC while the current 5250 position accepts double-byte input, and INPUT INHIBITED while a local error or host lock prevents input. The terminal, macOS, and Windows interfaces use the same state and text. Delete removes the character at the cursor. End performs Erase EOF in a 5250 or 3270 input field. Shift-Home enters Field Mark, and Shift-Insert performs Dup. Ctrl-^ is a portable text-terminal alternative for Field Mark. Press F3, or a lone Esc, to exit or go back. Press Ctrl-C to quit. Password fields do not display typed characters. In application-keypad mode, keypad Enter, plus, and minus perform 5250 Field Exit, Field+, and Field-. A play script can use insert, reset, delete, eraseeof, fieldmark, dup, fieldexit, fieldplus, and fieldminus for the same actions. In an ideographic either field, press Ctrl-K at the first enterable position to switch between alphanumeric and double-byte mode. In an ideographic open field, Ctrl-K inserts or removes an empty SO/SI subfield on blank cells, or moves past a populated subfield.

COMMANDS

These are the IBM i Host Server verbs. Credentials come from the environment only. Do not pass credentials on the command line. See ENVIRONMENT for details. Each verb signs on, runs, and prints a result. Each verb exits non-zero on failure. This lets you use them as CI gates, for example zelnet cmd "…" || exit 1.

Command Description
auth [host] Sign on. Print the system VRM, server level, and password level.
ifs ls <path> List an IFS directory on the file server.
ifs get <remote> <local> Download a file from the IFS.
ifs put <local> <remote> Upload a file to the IFS.
ifs mkdir <path> / rmdir <path> Create or remove a directory.
ifs rm <path> Delete a file.
ifs mv <src> <dst> Rename or move a path.
ifs stat <path> [--json] Show type, size, attributes, and timestamps. With --json, write a zelnet.ifs-stat.v1 result to stdout. Absence and failure exit nonzero; only status: absent with error_kind: absent proves absence.
sql "<SELECT ...>" Run a query. Print the rows. If the statement is not SELECT, zelnet runs it as EXECUTE IMMEDIATE. It then reports the rows affected.
xfer <table|"SELECT ..."> <file.csv> Export a table or query result to CSV. This is the Data Transfer function.
cmd "<CL COMMAND>" Run a CL command on the remote-command server. Print its messages.
dq write <lib/queue> <data> Write to a data queue.
dq writek <lib/q> <key> <data> Write a keyed entry.
dq read|peek <lib/q> [wait] Read the next entry and remove it, or peek at the next entry without removing it. wait sets how many seconds to block for an entry.
dq readk <lib/q> <EQ|NE|LT|LE|GT|GE> <key> Read by key comparator.
dq clear <lib/q> / attr <lib/q> Clear a queue, or show its attributes.
pgm rtvsysval <SYSVAL> Call the QWCRSVAL program for a system value. Examples: QMODEL, QCCSID, QDATE.
src export <lib> [--out <dir>] [--srcfiles QDDSSRC,QRPGLESRC,QCLSRC] [--filter PART*] [--strict] Pull a library's source members into a local Git layout: <out>/<srcfile>/<member>.<type>. This is a "reverse deploy".

IFS open, read, and write operations use the layout for the negotiated file server data-stream level. Levels below 16 use 32-bit sizes and offsets. Level 16 and later use 64-bit large-file fields.

Remote commands use the layout for the negotiated command-server data-stream level. Levels below 10 send CP 0x1101 in the server job EBCDIC CCSID. Level 10 and later send CP 0x1104 as UTF-16BE CCSID 1200. Returned messages always use the server job CCSID. Zelnet supports its shipped single-byte and mixed double-byte EBCDIC tables, including SO/SI runs and compound mappings. It parses fixed CP 0x1102 replies from older levels, CP 0x1106 replies from level 10, and the 26-field CP 0x1107 reply from level 11 and later.

ENVIRONMENT

Variable Meaning
ZELNET_USER / ZELNET_PW Credentials for the Host Server verbs, --login, and --play. You must not pass these on the command line.
ZELNET_AUTH_FACTOR Optional UTF-8 additional authentication factor for IBM i Host Server MFA. Zelnet sends it only in authentication requests.
ZELNET_HOST Default host for the verbs. Default value is pub400.com.
ZELNET_ALLOW_PLAINTEXT=1 You must set this to use --no-tls on a Host Server verb. Without it, zelnet refuses to send your password substitute and data in the clear.
ZELNET_DUMP=1 Hex-dump every inbound 3270 record. Use this for wire debugging.

EXAMPLES

Terminal sessions:

zelnet pub400.com 992          # IBM i over TLS (auto-on for 992), then sign on
zelnet pub400.com 23           # plain telnet
zelnet --self-signed host      # IBM i with its default self-signed cert
zelnet --tn3270 --model 4 host 23   # interactive 43×80 mainframe terminal
zelnet --probe --tn3270 host 23     # read one mainframe screen, then exit
zelnet --demo                  # offline render of a captured sign-on
zelnet --probe pub400.com 992  # connectivity check, no credentials

IBM i Host Server (credentials in the environment):

export ZELNET_USER=you ZELNET_PW=secret ZELNET_HOST=pub400.com
zelnet auth                                    # sign on, print V7R5M0 etc.
zelnet ifs ls /home/YOU                         # list a directory
zelnet sql "SELECT SCHEMA_NAME FROM QSYS2.SYSSCHEMAS FETCH FIRST 10 ROWS ONLY"
zelnet cmd "DSPSYSVAL SYSVAL(QDATE)"            # run a CL command
zelnet xfer "QSYS2.SYSSCHEMAS" /tmp/schemas.csv # export to CSV
zelnet pgm rtvsysval QMODEL                      # program-call a system value
zelnet src export MYLIB --out ./MYLIB --filter PART*   # pull source into Git

For live Host Server checks, set the credential variables and ZELNET_TEST_LIBRARY to a library where the test can create queues, then run make host-server-check. The check uses SQL, IFS, a system-value program call, and keyed and non-keyed queues. It tests maximum-size entries and removes the queues that it creates. A cleanup failure reports each queue name.

Scripted and headless (CI):

zelnet --play  signon.zts pub400.com 992   # drive + assert a 5250 panel flow
zelnet --drive logon.z3270 mainframe 23     # drive a 3270 panel flow

EXIT STATUS

0 means success. Any sign-on, connection, or operation failure prints a diagnostic message. zelnet then exits non-zero. This lets a verb gate a script or CI step.

TLS AND SECURITY

  • By default, TLS verifies the server certificate against the OS trust store. pub400.com's publicly-trusted certificate validates cleanly under this check. --self-signed accepts a valid self-signed certificate. --no-verify encrypts the connection without authenticating the peer.
  • Implicit TLS runs on terminal port 992. It also runs on the Host Server ports: sign-on 9476, file 9473, database 9471, command 9475, and data-queue 9472. The matching 84xx ports are plaintext.
  • The Host Server verbs refuse --no-tls unless you set ZELNET_ALLOW_PLAINTEXT=1. This stops a stray flag from silently leaking your password substitute and data.

BUILDING

zelnet needs Zig 0.17. The make targets are thin wrappers around zig build:

make build      # native CLI binary -> zig-out/bin/zelnet
make run ARGS="pub400.com 992"
make gui        # native GUI (macOS AppKit / Windows Win32, -Dgui)
make app        # assemble zig-out/zelnet.app (macOS bundle)
make ci         # what CI runs: fmt-check + tests (debug + safe)
make test       # unit tests
make smoke      # live pub400.com sign-on smoke (needs ZELNET_USER / ZELNET_PW)
make dist       # cross-compile every platform -> dist/

make ci includes the package entry-point contract. make terminal-status-check checks the actual CLI with local TCP peers. It requires no host account. This check also runs from zig build check.

You can also run zig build directly. Examples: zig build -Doptimize=safe, zig build run -- <host> [port], zig build -Dgui, and zig build check. zig build check is the CI-parity preflight. It runs zig fmt --check and all unit tests. Cross-compile targets are: x86_64-windows, x86_64-linux-musl, aarch64-linux-musl, aarch64-macos, x86_64-macos.

Zig 0.17 names its optimization modes with lower-case values: debug, fast, safe, and small.

DISTRIBUTION AND RELEASING

A pull-request check compiles all five shipping targets in debug mode. It also runs the format check, the unit tests and the package contract. It makes no packages.

A release cross-compiles the merged revision in safe mode with the release version:

  • Linux ARM64 and AMD64: DEB and RPM packages.
  • macOS ARM64 and x86_64: a universal desktop app as a .zip, and a .pkg installer with the app and command-line executable.
  • Windows x86_64: one .exe.

ci/package.sh is the package entry point. The macOS build needs the macOS SDK archive. Its SHA-256 must match the pinned hash.

Before publication, the release runs the TN3270 (Gibson), TN5250 (pub400.com) and NVT (Telehack) protocol checks. Each check has a 45-second limit. A failed or unavailable host fails the release.

The release then publishes an immutable version repository at pkg.sean.farm. It installs the DEB and RPM packages from that repository on Debian 13 and AlmaLinux 10, on ARM64 and AMD64. Each install checks the package SHA-256, the installed version and the help command. A release promotes the packages only after all install tests pass. Until then, the stable and latest channels stay on the previous release.

CAVEATS

  • This software is unstable. It is written in an unstable language, Zig. The people who wrote it are also unstable. Opus 4.8, an AI model, generated most of the code in a few days. Few human eyes have reviewed the code so far. It seems to work, for now.
  • Do not use this software for anything important. We do not know what problems it might cause on your system.
  • TN3270E display sessions negotiate BIND-IMAGE, RESPONSES and SYSREQ. Printer sessions negotiate BIND-IMAGE, DATA-STREAM-CTL, RESPONSES and SCS-CTL-CODES. Graphic Escape supports CP310 APL and line graphics. SA, SFE and MF can select CP310 for characters and fields. Basic TN3270 can also use full-screen TSO/E logon.

SEE ALSO

tn5250(1), x3270(1). RFC 1205, RFC 2877, RFC 4777 (TN5250). RFC 1576, RFC 2355 (TN3270, TN3270E). RFC 854 (Telnet). docs/HOSTSERVER.md describes the Host Server wire protocol. It includes live pub400.com verification notes.

Strict source capture

Use strict capture before source enters a recovery or release candidate:

zelnet src export SOMEARA1 --srcfiles QDDSSRC,QRPGLESRC --filter LEM* --out capture-001 --strict

The output directory must be new and its parent must exist. Every named source file must be accessible. Strict capture reads the complete selected member set twice and compares names, byte counts, and SHA-256 hashes. A missing file, failed read, unknown source kind, or changed member fails the command. Member lists can exceed 1,024 entries. Individual exported members have a 64 MiB size limit.

capture.json uses schema zelnet.source-capture.v1. It contains the library, relative member paths, byte counts, hashes, and an explicit complete flag. It becomes complete only after both passes succeed. A failed capture can leave partial files and an incomplete manifest. Consumers must check the process status, manifest, and file hashes before using the output. Authentication or local filesystem failures can prevent even an incomplete manifest from being written. A missing manifest is a failed capture.

Two matching reads detect changes; they do not create an atomic snapshot across an application. Stop edits to the selected sources while making a release snapshot. The manifest covers only the selected source files and filter. It does not prove that every application dependency has source or that the captured source produced the running programs.

Source text is converted to UTF-8 with LF line endings. File extensions are inferred from source-file names and DDS content; type_origin records this. QRPGSRC becomes .rpg, QRPGLESRC becomes .rpgle, QSQLSRC becomes .sql, and QCLSRC becomes .clle. Validate the stored member type and compile recipe separately, especially for mixed CL/CLLE and RPGLE/SQLRPGLE files. Unrecognized source files use .src and fail strict capture. Sequence numbers, line dates, and the original source-file attributes need a separate metadata capture.

For a custom source file with a known type, use --source-type SQL (or RPG, RPGLE, SQLRPGLE, CLP, CLLE, DSPF, PF, LF, or BND). This applies to every member in the selected scope. The manifest records type_origin: caller_declared. It does not claim that the type came from member metadata. Unknown types fail before a connection is opened.

Library Session3270 callers must keep the session at a stable address after its first readFrame call. Call deinit() before closing the transport. A read timeout leaves its read task pending; the next call receives that task's result. The reader is canceled only at shutdown. EOF is terminal. The CLI uses these rules for both its probe and scripted driver.

TLS permits one reader and one writer through Transport. Shared cipher state is locked, including read-side changes to write keys. The lock is released while fetching encrypted socket bytes, then reacquired before TLS processing resumes. Direct calls through TlsConn.client must hold TlsConn.state.mutex after the handshake. Conn sets up this state; custom TLS transports must supply it too.

Zelnet includes a TLS client adapted from Zig 0.16 for Zig 0.17 in src/tls. It replies to TLS 1.3 KeyUpdate requests, handles fragmented post-handshake messages, validates record lengths and retains full output across buffer boundaries. Signature and CA checks use the upstream code. Service identity checks use subjectAltName: DNS names match DNS entries, and IP literals match exact IP entries. A common name alone is not accepted. DNS names must use ASCII A-labels; a final root dot is removed. IPv6 host arguments use the unbracketed address. IP literals send no SNI. Run zelnet --licenses for the TLS source's MIT notice and the CP310 map's Apache-2.0 license. The CP310 Unicode map comes from IBM/tnz. The source copy, its original hash and its changes are documented in src/tls/README.md.

bash ci/test-tls-keyupdate-live.sh checks repeated key updates against a local OpenSSL peer with a verified self-signed localhost certificate. It needs OpenSSL development files, pkg-config and timeout. The test creates its key in memory and sends synthetic data only.

bash ci/test-tls-identity-live.sh uses the same tools to check DNS/IP identities, certificate rejection, and TLS 1.2/1.3 shutdown against a local OpenSSL peer. TLS 1.2 replies to peer shutdown immediately and discards queued plaintext. TLS 1.3 permits the local write side to remain open until the caller ends it.

To check real TLS fragmentation without credentials, set ZELNET_TLS_HOST to an HTTPS host and run bash ci/test-tls-read-lifetime-live.sh. It uses verified TLS and a HEAD request. It splits encrypted input at four boundaries and checks that timeouts retain the read while writes remain available. The test maps the received data to a fixed 3270 record; it does not test the peer's terminal protocol.

SQL row output preserves character values beyond 512 bytes. Inline and locator CLOB, BLOB and DBCLOB values are supported. Locator values stream in bounded chunks without the old 8192-byte cutoff. XML locators use the same bounded path. BLOBs and binary XML render as hex. Text uses the returned CCSID, including UTF-8, UTF-16BE and UCS-2BE. Invalid text, unsupported CCSIDs, incomplete replies and changes in a value's length or CCSID return errors. Values outside the protocol's signed 32-bit offset range return LobTooLarge. CSV text LOBs use two passes to decide quoting and formula protection before output. Both passes must have matching lengths, encodings and content hashes; a changed value returns LobChanged. TSV and BLOB output need one pass. Scalar CHAR, VARCHAR, DATALINK and Unicode GRAPHIC values use their declared CCSID. CCSID 65535 character values render as hex without trimming bytes. Fixed text fields trim trailing spaces; variable text retains them. Scaled integers and packed/zoned decimals retain their fractional digits. DECFLOAT supports the IEEE decimal64 and decimal128 Densely Packed Decimal forms, including infinity and NaN. BOOLEAN accepts the IBM 0xF0 and 0xF1 values. Invalid numeric metadata, digits or signs return Protocol; unsupported SQL types return UnsupportedSqlType instead of placeholder values. SQL statements use UTF-8 input and CCSID 13488 (UCS-2) on the wire. Invalid UTF-8, characters outside the Basic Multilingual Plane, and statements that exceed 8192 encoded bytes fail before any statement request. OPEN, FETCH, and LOB errors stop the result stream; the diagnostic API retains their status. SQL result formats and row blocks must agree on their column count, row width and consistency token. Incomplete descriptions, rows and variable-length cells return Protocol; more than 256 columns return TooManyColumns. A malformed block is rejected before any of its rows are written. The client accepts both extended CP 0x380C and super-extended CP 0x3812 column formats. It validates all super-extended descriptor offsets and LL-CP variable metadata, and it rejects duplicate or conflicting format parameters. Library callers must handle errors from database.parseFormat and database.decodeCell. The latter returns OutputTooSmall for a short output buffer. Cells must have exactly the width in their column metadata. Set Column.ccsid for text; the redundant Column.page field was removed.

Library data queue reads with peek=false require an output buffer of at least dataqueue.receive_capacity (65536 bytes). A smaller buffer returns OutputTooSmall before removal. Peeks can use smaller buffers, but also return OutputTooSmall if the entry does not fit. No read returns a partial entry.

Host Server library request builders use Zig errors for short buffers and values that exceed wire fields. Callers must handle these errors before transmission. Data queue names must be valid ASCII system names, with at most ten characters. The library selectors *LIBL and *CURLIB are supported. Keys must contain 1–256 bytes. Both write variants support entries up to 64512 bytes, as specified by IBM CRTDTAQ.

TN3270 handles Read Buffer, Read Modified, Read Modified All, and Erase All Unprotected in field reply mode. When BINARY or EOR is withdrawn, the same session shows basic ASCII NVT output and sends NVT input. It returns to 3270 when both options are enabled in both directions. This follows RFC 1576 section 4. The NVT display within a 3270 session interprets a bounded ECMA-48 display profile. It supports cursor movement and save/restore, erase, insert/delete, scroll, and the shared foreground-color and emphasis styles. Parser state stays valid when a control sequence is split across Telnet reads or TN3270E records. Unsupported and private controls are consumed and do not enter display cells. Use --nvt when the local terminal must process a larger terminal profile.

Replace a 5250 field in a test

In a --play script, field 0; fill BUY replaces the complete visible field. For 5250 and 3270, type and typepw decode UTF-8 into characters before EBCDIC conversion. They reject malformed UTF-8, unsupported characters, and text that exceeds the remaining field space before changing the field. The terminal defaults to CCSID 37. Use --ccsid 273 for a German host display, or another supported numeric CCSID. Match the host display code page; this flag does not change the IBM i job or database encoding. The generated ICU tables retain reverse-fallback aliases for host data and good one-way mappings for operator input. Encoding selects a roundtrip mapping when one exists. CCSIDs 1390 and 1399 also retain ICU two-scalar DBCS mappings. Display, search, copy, scripted input, interactive input, and host replies keep both Unicode scalars in each mapped pair. fill with no text clears it. This removes old characters when the new value is shorter. It accepts UTF-8, refuses hidden fields, and checks the complete text and required cell count before editing. Double-byte characters use two cells. Use typepw for a password field. The field-fill helpers used for sign-on apply the same validation and return an error for invalid input.

Unknown script verbs now fail before a connection opens. Use pf 3 for F3; pf3 is an error. This check applies to 5250, 3270, and NVT scripts. The insert verb toggles Insert mode. In 5250, data shifts across continued field segments and the last segment must end in a null. In 3270, data shifts through the active field, including across row and circular-buffer boundaries. The edit preserves character pairs and cell styles. A full field is unchanged. Press Insert again before you leave a 5250 field. The reset verb performs the Reset key function. It leaves Insert mode and clears an operator error. A Reset discards input that was queued before it. The host must still restore a keyboard that a command or AID locked. The delete verb removes the character at the cursor and shifts later data left. The Delete key performs the same action. The eraseeof verb clears the active 5250 or 3270 input field from the cursor through its end. It keeps the cursor at the same position. The fieldmark verb enters the Field Mark byte in either protocol. A 5250 field must permit Dup or Field Mark in its FFW. The dup verb performs the protocol's Dup key action. A 5250 field must permit Dup in its FFW.

Host-driven 5250 updates

The POSIX and Windows terminals and the native windows receive 5250 updates while the user is idle. The session acknowledges Cancel Invite (RFC 1205 section 4.2) and blocks another AID until the host sends a new Read. Network reads only supply bytes. The UI thread owns screen changes and writes.

The 5250 play runner accepts pause <milliseconds> and await <milliseconds> <screen text>. Both continue to process host output. Waits are limited to 60 seconds. Invalid waits fail before sign-on. A timed script records elapsed time; older scripts retain their fixed frame delay. The Windows console uses the same persistent host reader as the POSIX terminal. It checks console input without blocking after each host event or 25 ms heartbeat. Unit tests cover the Windows polling seam, and the Windows package target compiles it. A native Windows runtime check remains separate.

5250 Save Screen and Restore Screen retain native screen bytes, fields, format controls, and cursor state. The sysreq script command sends System Request. A pub400 check confirms Save, Restore, Cancel Invite, and execution of text entered before the exchange. It does not claim ACS parity. Roll, Erase to Address, and extended primary, color, and ideographic attributes are supported. Write Data handles ordinary and continued fields, word wrap, and null fill. Continued field replies contain one logical value, one SBA, and one trailing-null trim. Keyboard and scripted edits cross segment boundaries, share MDT state, and navigate the set as one field. Alternate modified reads retain leading and embedded nulls for ordinary fields. Word-wrap reads remove line-padding nulls; Read Input restores the logical field length with trailing nulls. Field replies preserve native bytes and explicit trailing spaces. Keyboard and scripted replacement reflow whole single-byte words at row and continued-segment boundaries. If padding alone prevents a fit, editing uses the unwrapped value. Transparency entry fields keep every native byte. Read Input returns the exact field contents. Modified reads return one length-delimited TD order for each ordinary or continued logical field, including nulls and bytes that otherwise have display-control meanings. When the SOH selects read resequencing, Read Input, modified reads, alternate reads, and immediate reads follow the 80nn FCW chain. Continued fields count as one field. Bypass fields can direct the chain but do not return data. FFW keyboard classes reject characters that the field does not accept. Field Mark enters raw byte 1E, sets MDT, and moves like one data character. It displays as a blank in 5250 and as a semicolon in 3270. A 5250 field accepts the key only when its FFW enables Dup or Field Mark. Save and Restore retain the bit for ordinary and continued fields. Dup fills a 5250 field from the cursor through its last ordinary or continued position with raw byte 1C, sets MDT, and performs forward field exit. Pure double-byte fields retain their shift controls and use 1C1C for each remaining character. An ideographic open field accepts Dup only at its first position. In 3270, Dup stores one raw 1C marker and tabs to the next input field. On an unformatted 3270 screen, it clears the presentation space and moves the cursor to address zero. An unformatted 3270 presentation space accepts text, Field Mark, Backspace, Erase EOF, and cursor movement across the full buffer. Enter returns data from address zero with nulls suppressed and without SBA orders. Double-byte input stays in complete pairs and does not split across the buffer end. Erase EOF writes nulls from the cursor through the end of an active input field, resets character attributes in those positions, sets MDT, and keeps the cursor fixed. Continued 5250 fields clear through their final segment. Reserved ideographic shift positions stay in place. Monocase converts keyed ASCII and the supported German, Danish, Norwegian, Finnish, Swedish, and Spanish national letters to uppercase. Signed numeric fields reserve the final display cell for the sign and right-adjust digits on Field Exit, Field+, or Field-. Reads remove that sign cell and apply the IBM D zone to a negative low-order digit. Transparent reads remain byte exact. Field-exit-required fields keep the cursor on the last entered position until the operator uses a nondata key. Mandatory-enter fields must have their MDT set before an AID can be sent after any field or selection control has changed. A blank character counts as entry. A rejected AID moves the cursor to the first missing mandatory-enter field. Pointer and selection AIDs use the same checks as keyboard AIDs. The FFW Auto Enter bit sends the SLP Auto Enter AID when input fills the last enterable position or a forward field-exit action completes the field. FCW 8501 uses the same edge rules and sends its Forward Edge Trigger AID. Other 85nn values are invalid. A continued field triggers only at the end of its last segment. Single-byte, double-byte, open, and word-wrap fields use their actual final data position. Field-exit-required delays the automatic AID until the operator uses an explicit field-exit action. Interactive input and the type and typepw script commands wait for the host reply after either automatic AID. Interactive input starts forward field exit after it fills the last enterable position. Normal, word-wrap, ideographic, open, and continued fields advance in field order or through 88nn cursor progression. Field-exit-required and failed field validation keep the cursor on the final position. Batch field replacement does not run this interactive cursor action. FCW 88nn changes forward field exit to field number nn. Numbering includes bypass fields, counts a continued set or selection field once, and excludes scroll bars. Backward field exit follows the first reverse link. Target zero and undefined targets use normal field order. An SOH read-resequencing request disables cursor progression, as required by IBM SC30-3533. Progression can place the cursor on a bypass field without making that field editable. FCW 89nn changes an active entry field to the requested display attribute and restores the host attribute when the cursor leaves. Continued fields change every segment. Zelnet applies color and common controls and ignores monochrome and reserved controls. An invisible cursor is valid only for a reader I/O field without an 81xx attention control. Its inbound cursor address is the first field position. The wrapped row-one, column-one field is not highlighted. FCWs B1A0 and B140 enforce the IBM modulus 10 and modulus 11 self-check algorithms when active input exits or sends an AID. The rightmost data position is the check digit. Signed fields exclude their display sign. Nonnumeric EBCDIC bytes use their low nibble when it is 0 through 9 and otherwise use zero. All-null fields are valid. Self-check fields are limited to 33 positions and cannot be continued or combined with word wrap. Ideographic FCWs retain their only, data, either, or open field type. Field creation rejects reserved types, invalid lengths, unsupported data fields, off-screen spans, invalid open-field line portions, and the prohibited word-wrap combinations from IBM SC30-3533. On DBCS code pages, 5250 SO and SI bytes occupy their specified screen-buffer positions. Field discovery, rendering, screen reads, and field replies retain those positions and native shift bytes. Ideographic-only fields initialize with in-field SO and SI cells. Ideographic data fields initialize with extended-plane SO and SI markers and decode raw DBCS pairs. Field modifications restore these boundaries and retain existing field data. Operator and scripted input in these two field types accepts only double-byte characters and cannot overwrite the reserved shift boundaries. An ideographic either field starts in alphanumeric mode. Ctrl-K or the kanji script command switches its mode at the first enterable position. The change clears the field, updates its SO and SI cells, moves the cursor, and sets MDT. Native CJK input can select the initial double-byte mode directly. Scripted input in an ideographic open field accepts mixed text. It adds a balanced SO and SI pair around each adjacent group of double-byte characters and checks all required buffer positions before it changes the field. Continued fields close and reopen a subfield when a segment cannot hold the next complete double-byte character. A malformed host-written shift sequence is not changed. Native CJK input inserts an open-field subfield and extends it while space is available. Single-byte input continues after SI. Backspace removes a complete double-byte character and moves SI left, so later CJK input can extend the same subfield. Moving onto a DBCS character and typing replaces the complete pair. Ctrl-K and the kanji script command insert or remove an empty SO/SI subfield on blank cells. In a populated subfield, they move the cursor after SI and do not change its data or MDT. Word-wrap reads remove SBCS padding nulls from open fields. They keep null positions inside SO/SI subfields, so the DBCS portion does not change length. During input, word wrap moves only SBCS words. SO/SI subfields and DBCS pairs stay in their fixed buffer positions. Replacement, Backspace, and empty- subfield removal use null padding, so later input can use the released SBCS cells. Character-cell windows support custom borders, titles, footers, pull-down borders, and cursor limits. Save/Restore retains these attributes and window controls; Restore removes cursor restrictions. Partial Save takes a full-screen snapshot at its command position. It sends that image after later display commands finish. Partial Restore accepts following display and Read commands. Unknown commands prevent a new Save; other unsupported structured fields return an error. Text terminals show column separators as underlines. Native windows draw vertical separators. Grid-line structured fields draw and erase lines, boxes, and ruled boxes. Native windows show all sixteen colors and seven line styles. Text terminals and recordings show line glyphs in blank cells; this is an approximation. Grid lines stay separate from field text and are included in Save/Restore. The version-seven saved image reader also accepts version-two through version-six images. Version seven retains pending field-exit validation. Read Screen supports raw text, extended attributes, print data, and grid data (commands 62, 64, 66, 68, 6A, and 6C). The Query Reply reports one type-one grid buffer. Offline tests cover these formats; a live host grid program has not been tested. Character-cell scroll bars support vertical and horizontal layouts, custom indicators, and scaled sliders. Native windows and SGR terminals accept arrow clicks, page clicks, and slider drags. The reply contains the scroll increment and can identify the control by its cursor position. Scroll fields share the format table limit with entry fields and are included in Save/Restore. Remove GUI Scroll Bar leaves character-cell controls unchanged, as specified for NWS displays. Offline tests cover these controls; a live scroll-bar program has not been tested. Character-cell selection fields support menus, single and multiple choices, lists, pull-down fields, push buttons, mnemonics, one- and two-digit numeric selection, pointer input, auto-enter, cursor-sensitive roll requests, and attached scroll bars. Entry, selection, and scroll data share address order and the 256-entry format-table limit. Save/Restore retains selection state and clears pull-down cancel mode. Remove GUI Selection Field leaves NWS character cells and definitions unchanged. Offline tests cover these controls; a live host selection-field program has not been tested. Programmable mouse buttons support single events, queued clicks, and two-event replies. FCW 8Ann entry fields return their configured AID on a left click. Native windows show a marker box; text terminals show an inverse cell. An unbound left click places the cursor; its double click sends Enter. Terminal input uses XTerm SGR mouse reports and a 500 ms double-click interval. AID data rules and SOH function-key masks retain the cursor and AID while omitting field data when required. Save/Restore retains mouse definitions and clears partial gestures. Offline tests cover the wire formats; a live host program with these mouse controls has not been tested. See the RPG audit for limits and native evidence.