Chapter 19
tsrvd Daemon FamilyIn This Chapter
tsrvd serves$mail and checkmailChapter 16 gave you tcpserver — a server written in the cshw scripting language, running inside your shell process. That's perfect for quick, interactive work: spin one up, hit it from another shell, cocancel it when you're done. But it has a ceiling. The server lives and dies with the shell that launched it. Close the window and the server is gone. And because the handler runs in the shell's own process, a bug in the handler can take the whole shell down with it.
For servers you want to keep running — a mail server, a file server, anything with uptime expectations — cshw has a heavier-duty answer: the tsrvd daemon family. tsrvd runs each server in a separate, isolated process that cshw supervises. A crash in the server can't touch your shell. You can start it, walk away, and cshw will restart it if it falls over. And it ships with real, ready-to-run protocol servers: SMTP, POP3, IMAP, FTP, and HTTP.
This is the chapter where cshw stops being "a shell that can serve a socket" and becomes "a shell that can run your mail server."
tcpserver (Chapter 16) and tsrvd solve the same shape of problem — accept connections, handle each one — but they make opposite tradeoffs.
tcpserver (Ch 16) |
tsrvd (this chapter) |
|
|---|---|---|
| Runs where | Inside your shell process | A separate tsrvd.exe process |
| Handler language | cshw script (or /mthread coroutine) |
cshw script (relay) OR a native DLL |
| Survives shell exit | No | Yes (cshw supervises; can restart) |
| Crash isolation | None — a bad handler can crash the shell | Full — the worker crashes alone |
| Best for | Quick, interactive, throwaway servers | Long-running services you rely on |
The key word is isolation. When you run tsrvd, cshw becomes a master that launches and watches over a worker process — tsrvd.exe — which does the actual accepting and serving. The worker never runs cshw scripts of its own; it's a pure network engine. If it crashes, cshw notices and (unless you say otherwise) starts a fresh one. If cshw exits, the worker notices its master is gone and shuts itself down cleanly — no orphaned processes.
TECHNICAL STUFF
tsrvd.exe is built on the same cshw::net::CServer engine that powers tcpserver, but as a standalone executable. Launched by itself with no cshw master, it does nothing (except a --selftest echo mode used for development). It's driven entirely over a control pipe by the cshw tsrvd command. You never invoke tsrvd.exe directly; you drive it through the shell.
The simplest tsrvd server is a relay handler: a cshw procedure that takes a request line and returns a response. tsrvd accepts the connection in its own process and relays the bytes to your handler.
proc echo_handler(req)
return "You said: $req"
endproc
tsrvd start 8086 echo_handler
tsrvd start launches a worker on port 8086, wired to echo_handler. It sets $result to the new daemon's ID (save it — you'll need it to stop the server) and returns to your prompt. The server is now running in its own process; your shell is free.
Test it from another shell with the tcpclient from Chapter 16:
tcpclient localhost 8086 /send:"hello" /recv
echo "$result" # "You said: hello"
For each connection, tsrvd reads one request line, hands it to echo_handler, and writes back whatever the handler returns. The handler is ordinary cshw — it can read files, call genai, do arithmetic, anything.
REMEMBER
Save the ID that tsrvd start puts in $result. set srv = $result right after starting is the habit; tsrvd stop $srv is how you shut it down later. tsrvd list will also show you every running daemon and its ID if you lose track.
tsrvd is a single command with subcommands:
tsrvd start <port> [handler] [flags...] # launch a daemon; $result = its ID
tsrvd status <id> # STAT <accepted> <active> <running>
tsrvd stop <id> # graceful shutdown
tsrvd list # ID PORT PID STATE RST LAST-STAT
tsrvd start blocks just long enough for the worker to come up and announce itself, then returns with the ID in $result. tsrvd list is your dashboard — it shows every daemon, its port, its OS process ID, its state, how many times it's been restarted (RST), and its last status line.
The flags on start control how the server runs:
/dll:<path> — run a native protocol plugin (a DLL) instead of a script handler/dllcfg:<file> — the config file to hand that plugin/workers:N — how many connections the worker handles concurrently (default 128)/stream — use a streaming handler instead of request/response (covered later)/norestart — don't auto-restart this daemon if it crashes/onrestart:<proc> — call this procedure when the daemon restarts or failsWe'll meet each of these as we go.
A tsrvd daemon gets its behavior one of two ways, and the distinction shapes everything else in this chapter.
Relay handlers are cshw procedures, like echo_handler above. The worker relays each connection's bytes to your script over an internal pipe; your script does the logic. Great for glue, prototypes, and moderate-volume custom protocols — anything where "a cshw proc per request" is fast enough.
Native plugins are DLLs that implement a whole protocol in the worker process, in compiled C++. cshw only supervises; it never sees the individual requests. This is how the real servers — SMTP, POP3, IMAP, FTP — are built. They're fast, they're self-contained, and they handle their own protocol state.
tsrvd start 8086 my_handler # relay: script handles each request
tsrvd start 25 /dll:smtp.dll /dllcfg:smtp.conf # native: the DLL is the whole server
TECHNICAL STUFF
A relay handler pins one worker slot for as long as your script is running on that request. That's fine for moderate volume, but it means a slow handler limits throughput (there's a watchdog to keep a wedged handler from pinning a slot forever — more later). Native DLLs have no such limit: they run the protocol directly on the worker's thread pool. Rule of thumb: relay for glue and low volume; DLLs for the real servers.
The headline feature of the daemon family is a working mail server — three protocols that cooperate over one shared mailbox store.
smtp.dll receives mail (SMTP, RFC 5321) and writes it to the spool.pop3.dll lets a client download and delete mail (POP3, RFC 1939).imap.dll lets a client browse and manage mail on the server (IMAP4rev1, a practical subset).All three read and write the same on-disk format: a Maildir spool. Understanding that shared spool is the key to understanding the mail stack.
Every mailbox is a directory with three subdirectories — tmp, new, and cur:
tmp\ first, then atomically moved to new\. That two-step is what makes delivery crash-safe: a reader never sees a half-written message.new\ to cur\ and picks up a flag suffix (;2,S for "Seen", and so on).This is the same Maildir scheme Dovecot and Courier use, adapted for Windows: because NTFS won't allow a colon in a filename, cshw uses a semicolon — ;2,<flags> — where classic Unix Maildir uses :2,<flags>.
REMEMBER
SMTP delivers into the spool; POP3 and IMAP serve from it. Point all three at the same spool directory and you have a complete mail loop: mail arrives via SMTP, and your client reads it via POP3 or IMAP. The spool is the contract between them.
smtp.dlltsrvd start 25 /dll:smtp.dll /dllcfg:smtp.conf
A minimal smtp.conf:
# smtp.conf
host = mail.example.com
format = maildir
spool = C:\cshw-mail\spool
peruser = on
With peruser = on, a message addressed to alice@… is delivered into spool\alice\ — one mailbox per recipient. The SMTP server speaks the modern ESMTP dialect: it advertises SIZE, 8BITMIME, PIPELINING, and enhanced status codes, and (when you configure them) STARTTLS and AUTH.
The full set of smtp.conf keys: host, spool, mbox, format (maildir/mbox/both), peruser, maxsize (default 25 MiB, 0 = unlimited), maxrcpt, timeout, auth, authrequired, user, pass, and the TLS keys covered later.
pop3.dll and imap.dllPOP3 is the download-and-delete protocol. Point it at the same spool:
tsrvd start 110 /dll:pop3.dll /dllcfg:pop3.conf
# pop3.conf (serves the smtp Maildir)
spool = C:\cshw-mail\spool
user = alice
pass = changeme
IMAP keeps mail on the server and lets the client browse folders, search, and set flags. Its config keys are identical to POP3's (there's no separate imap.conf.example shipped — just copy the POP3 shape):
tsrvd start 143 /dll:imap.dll /dllcfg:imap.conf
# imap.conf
spool = C:\cshw-mail\spool
user = alice
pass = changeme
The IMAP server implements a genuinely useful slice of IMAP4rev1: SELECT/EXAMINE, FETCH (envelopes, body structures, sections, partial fetches, \Seen-on-fetch), SEARCH (flags, sets, header/body text, dates), STORE, APPEND, CREATE/DELETE/RENAME for folders, IDLE, and the UID variants — enough for a real mail client to connect and work.
TECHNICAL STUFF
IMAP folders use the Maildir++ convention: INBOX is the spool root, and other folders are dot-prefixed sibling maildirs (.Sent, .Drafts). Message UIDs are persistent — the server keeps a .uidlist file per mailbox so a client's cached UIDs stay valid across sessions. IDLE is the poll-based minimal form: new mail surfaces when the client ends its IDLE or issues a NOOP, not as an instant server push.
Here's the whole stack — receive on SMTP, serve on POP3 — sharing one spool:
# mailserver.cshw — a tiny mail server
set spool = "C:\cshw-mail\spool"
tsrvd start 2525 /dll:smtp.dll /dllcfg:smtp.conf
set smtp = $result
tsrvd start 2110 /dll:pop3.dll /dllcfg:pop3.conf
set pop = $result
echo "Mail server up. SMTP on 2525, POP3 on 2110."
tsrvd list
# ... runs until you stop it ...
# tsrvd stop $smtp
# tsrvd stop $pop
(Both smtp.conf and pop3.conf set spool = C:\cshw-mail\spool.) Mail that arrives on port 2525 lands in the spool; a POP3 client on port 2110 downloads it. Two daemons, one shared folder, a working mail server in a dozen lines of cshw.
TRY IT
Start the SMTP daemon from the example, then send it a message with a raw tcpclient conversation (HELO, MAIL FROM:, RCPT TO:, DATA, your text, ., QUIT). Look in C:\cshw-mail\spool\<recipient>\new\ — your message is sitting there as a Maildir file. That's the delivery half of a mail server, working on your machine.
ftp.dll is a full FTP server with explicit FTPS (AUTH TLS) support. It serves files out of a single sandboxed root directory:
tsrvd start 21 /dll:ftp.dll /dllcfg:ftp.conf
# ftp.conf
root = C:\ftp-root
user = bob
pass = changeme
# writable = on # uncomment to allow uploads/deletes/renames
Two things worth knowing up front. First, the server is read-only by default — writable starts off, so clients can browse and download but can't change anything until you explicitly turn writes on. Second, everything is sandboxed to root: no path a client sends can climb above the served directory. It speaks the modern FTP verbs (passive and active mode, EPSV/EPRT, MDTM, SIZE, UTF8) and, with TLS configured, wraps both the control and data channels.
The full ftp.conf key set: root (required), user, pass, anonymous, writable, pasvaddress, pasvmin, pasvmax, banner, and the TLS keys.
WARNING
Plain FTP sends credentials and data in the clear, exactly as noted back in Chapter 16. For anything over an untrusted network, configure FTPS (the TLS keys below) or don't use FTP at all. The writable = on switch is genuinely powerful — a writable FTP root is a writable directory exposed to the network, so scope root tightly and keep authentication on.
http.dll is a real web server: it serves a document root as static files, speaks HTTP/1.1 with keep-alive, can run behind TLS (HTTPS), negotiates HTTP/2 over ALPN, and can route a URL prefix to CGI-style cshw scripts for dynamic content and APIs. For HTTP/3 there's a sibling worker, quicsrv, that runs the same document root and CGI over QUIC/UDP — covered at the end of this chapter.
Point it at a folder and it serves it:
tsrvd start 8080 /dll:http.dll /dllcfg:http.conf
# http.conf
root = C:\www # document root
index = index.html # default file for a directory
Now http://localhost:8080/ serves C:\www\index.html, /style.css serves that file with the right Content-Type, and so on. The server handles GET and HEAD, sets Content-Length and Last-Modified, answers conditional requests with 304 Not Modified, supports Range requests (206 Partial Content, so media seeking works), and returns proper 404/403/405 codes. Every path is sandboxed to root — no .. can climb out of it. Set listing = on for an auto-generated directory index when a folder has no index file.
Content types are inferred from the file extension (html, css, js, json, png, svg, woff2, and the rest of the usual suspects), so a static site — an SPA build, a docs tree, a bundle of assets — just works.
Add a certificate and the same server speaks TLS:
root = C:\www
tls = on
tlscert = C:\certs\server.pfx
tlspfxpass = <password>
That's HTTPS on the port you started tsrvd with, using the same SChannel TLS layer as the mail and FTP servers (tlsstore = MY uses a certificate from the Windows store instead of a .pfx, by subject or thumbprint).
For anything beyond static files — a form handler, a JSON API, a small dashboard — route a URL prefix to CGI scripts run through cshw:
root = C:\www
cgiprefix = /api/
cgidir = C:\www\api
A request to /api/status.cshw runs C:\www\api\status.cshw through cshw.exe, with the request available as standard CGI environment variables — REQUEST_METHOD, QUERY_STRING, CONTENT_TYPE, CONTENT_LENGTH, and HTTP_* for each header — and the request body on standard input. Whatever the script prints becomes the response. A minimal JSON endpoint:
# C:\www\api\status.cshw
echo "Content-Type: application/json"
echo ""
echo "{\"status\": \"ok\", \"time\": \"$(say datetime)\"}"
The script prints a header block, a blank line, then the body — classic CGI. Add a Status: 404 Not Found header line to set the status code; omit it and you get 200. So your API endpoints are ordinary .cshw scripts: read the query string and body, call genai or bc or a database, and print a response. The whole toolkit from the rest of the book, behind an HTTP endpoint.
TECHNICAL STUFF
CGI runs one cshw.exe per request — simple and robust, but not free. It's ideal for low-to-moderate traffic (internal tools, webhooks, small services); for a high-traffic API you'd feel the per-request process spawn, and the right answer there is a native handler DLL against the tsrvd ABI, the way smtp.dll and friends are built. Static files, by contrast, are served straight from the worker with no per-request process.
WARNING
A CGI script is code the server runs on request, with the server's privileges. Only point cgidir at scripts you trust, and validate anything that comes from the client (query string, body, headers) before acting on it — especially before feeding request data into genai (the prompt-injection caution from Chapter 17 applies double when the "user" is anyone on the network).
The same document root and CGI scripts are reachable over the newer protocols — the only change to your config is turning them on.
HTTP/2 rides on the HTTPS listener you already have. With TLS enabled, http.dll offers h2 and http/1.1 by ALPN and serves whichever the client negotiates; modern browsers pick h2 on their own:
tls = on
tlscert = C:\certs\server.pfx
tlspfxpass = changeme
alpn = h2 http/1.1 # the default -- set "http/1.1" to force HTTP/1.1
HTTP/3 runs over QUIC, which is UDP rather than TCP — a different transport, so it's a separate worker: quicsrv, the UDP sibling of tsrvd. Point it at the same kind of config (cert + root, and optional cgiprefix/cgidir) and it serves HTTP/3 through the very same static-file + CGI core:
quicsrv start 443 /dllcfg:site.conf
quicsrv is supervised exactly like tsrvd — quicsrv status <id>, quicsrv stop <id>, quicsrv list, and the same auto-restart on unexpected death. Because HTTP/3 is discovered rather than requested directly, add an altsvc line to the http.dll config so its HTTP/1.1 and HTTP/2 responses advertise the h3 endpoint and browsers upgrade to it:
altsvc = 443 # emits `Alt-Svc: h3=":443"` from http.dll
Whatever you tested over HTTP/1.1 works unchanged over HTTP/2 and HTTP/3 — one serving core, three wire protocols.
TECHNICAL STUFF
HTTP/2 and HTTP/3 aren't hand-rolled: http.dll uses nghttp2 for h2 framing, and quicsrv pairs msquic (the QUIC transport, the same one Windows' own HTTP.sys uses) with nghttp3 for h3 framing and QPACK. cshw ships those DLLs alongside the workers, the way it ships pcre2 for the shell. QUIC is UDP/443, which locked-down networks sometimes block; clients that can't reach h3 simply fall back to h2 or h1.1, which is expected and fine.
The reason to run a server under tsrvd rather than tcpserver is that cshw watches over it. Here's what that supervision actually does.
By default, if a worker dies unexpectedly, cshw relaunches it — with backoff, so a server that's crash-looping doesn't spin the CPU. The policy: within a 10-second window it will restart up to 5 times, with a growing delay between attempts; if it blows past that, cshw marks the daemon failed and stops trying. tsrvd list shows the restart count in its RST column and failed in the state column, so a flapping server is visible at a glance.
If you don't want a particular daemon restarted — say it's a one-shot or you're debugging its startup — pass /norestart:
tsrvd start 8086 my_handler /norestart
To react when a daemon restarts or fails, register a callback with /onrestart:<proc>:
proc on_restart(id, event, count)
echo "Daemon $id: $event (count $count)"
# e.g. log it, send an alert, page someone
endproc
tsrvd start 8086 my_handler /onrestart:on_restart
cshw calls your procedure with the daemon's ID, the event ("restarted" or "failed"), and the restart count. This is your hook for logging, alerting, or metrics.
WARNING
An /onrestart callback must never stop its own daemon. The callback runs on the supervisor's own thread; calling tsrvd stop on the daemon that's restarting from inside its restart callback deadlocks the supervisor. Log, alert, count — but don't tear down from in there.
Relay handlers have one failure mode native DLLs don't: a handler script can hang, pinning a worker slot forever. So for request/response relay daemons, cshw runs a watchdog — if a handler doesn't reply within a timeout (default 60 seconds, set via the CSHW_TSRVD_HANDLER_TIMEOUT_MS environment variable, 0 for unlimited), the worker closes that client connection and reclaims the slot. Streaming handlers are intentionally exempt (they're expected to run for the life of a connection).
tsrvd stop <id> is a clean shutdown, not a kill: cshw signals the worker over the control pipe, the worker stops accepting new connections and drains the ones in flight, then exits and is reaped. And the safety net already mentioned: if cshw itself exits while daemons are running, each worker sees its control pipe break and shuts itself down. You never leak orphaned tsrvd.exe processes.
Every mail and FTP plugin can run encrypted, and each takes the same TLS keys in its config file:
tls = on
tlscert = C:\certs\server.pfx
tlspfxpass = <pfx-password>
# or, to use a certificate from the Windows store instead of a .pfx:
# tlsstore = MY
The mail plugins (smtp/pop3/imap) also accept tlsrequired = on to insist on TLS, and the SMTP/POP3/IMAP dialects negotiate it the standard way (STARTTLS/STLS). FTP uses explicit FTPS — AUTH TLS upgrades the control channel and PROT P wraps each data connection.
Authentication is deliberately simple: set a user and pass in the config and clients must present those credentials. SMTP gates AUTH with auth = on (and authrequired = on to make it mandatory).
REMEMBER
Authentication here is single-credential: one user/pass per server (or a shared-password mode where any username maps to one fixed mailbox). These daemons are built for personal servers, small teams, lab setups, and appliance-style deployments — not multi-tenant hosting. There's no per-account user database. Size the tool to the job: it's a sharp little mail server, not a replacement for a hosting provider.
Because the spool is just a Maildir on disk, cshw can watch it directly — no server round-trip needed. The $mail variable turns on mailbox monitoring, csh-style:
set mail = (60 C:\cshw-mail\spool\alice)
The first number is a poll interval in seconds (0 disables); the rest are mailbox paths. Before each prompt, cshw checks each one, and when new mail appears it prints a line:
You have new mail for user: alice
Because the mailbox is a Maildir, "new" means unread — a message that POP3 or IMAP has already moved from new\ to cur\ correctly stops counting, so you're not nagged about mail you've read elsewhere. The checkmail command forces an immediate check without waiting for the next prompt:
checkmail
TRY IT
set mail = (5 C:\cshw-mail\spool\alice), then drop a file into …\spool\alice\new\. Within five seconds — or immediately, if you run checkmail — the shell tells you there's new mail for alice. That's the same biff-style notification Unix shells have had for decades, reading a real Maildir on Windows.
Request/response relay handles "read one line, write one reply." For protocols that need a back-and-forth conversation — read, decide, read again — use a streaming handler with /stream. Inside a streaming handler you drive the connection yourself with tsrvd recv, tsrvd send, and tsrvd close:
proc chat(conn)
tsrvd send $conn "Welcome. Type 'bye' to leave.\n"
while (1) then
tsrvd recv $conn
if ($? != 0) then
break # client disconnected
endif
set line = $result
if ("$line" == "bye") then
tsrvd send $conn "Goodbye.\n"
break
endif
tsrvd send $conn "You said: $line\n"
end
tsrvd close $conn
endproc
tsrvd start 8087 chat /stream
The handler gets a connection handle instead of a single request, and it lives for the whole session. This is how you'd write a line-oriented interactive protocol — a MUD, a REPL-over-TCP, a chat server — in pure cshw.
The daemon family is an optional component of the cshw installer. Choose the full install (or tick the "server" component in a custom install) and you get, sitting alongside cshw.exe:
tsrvd.exe — the worker executablesmtp.dll, pop3.dll, imap.dll, ftp.dll — the protocol servershttp.dll — the reference plugin(The development-only echo.dll is deliberately not shipped.) A compact install gives you just the shell. So if tsrvd start /dll:smtp.dll reports it can't find the DLL, you likely did a compact install — re-run the installer and include the server component.
These are real, useful servers — and they're scoped on purpose. Know the edges:
user/pass per server, no multi-account database. Fine for a personal or small-team server; not multi-tenant hosting.SEARCH is a subset, and IDLE is poll-based rather than instant push.http.dll speaks HTTP/1.1 and HTTP/2; HTTP/3 is served by the quicsrv worker (QUIC/UDP). All three share one serving core, so a static site or a CGI API behaves identically whichever protocol a client negotiates. CGI spawns one cshw.exe per dynamic request, so very high-traffic endpoints want a native handler DLL instead — static files are served straight from the worker with no per-request process.tsrvd start /dll: like rcl (Chapter 18): the same "what you load is what runs" model.For a personal mail server, a lab file server, a custom line protocol, or an appliance you control end to end, that's a genuinely capable toolkit — and it's all driven from the same prompt you've been using all book.
You can now run real, supervised, out-of-process servers from cshw — a mail stack, an FTP server, and any custom protocol you care to write as a relay handler or a native plugin. Between tcpserver (in-process, quick) and tsrvd (out-of-process, supervised), cshw covers the whole range from "test a socket" to "run a service."
That closes the server story. One feature chapter remains, and it is the most down-to-earth in the book: Chapter 20 covers PRINTING — lp, lpr and the queue commands, plus how to turn a document into a PDF, an XPS file or a stack of images without a printer being involved at all.
After that, Part V is the wrap-up: three Top Tens (the daily-driver commands, the things cshw does that cmd.exe doesn't, and the tricks for when you're stuck) and a cheat-sheet appendix.
You started the book opening a shell and typing ls. You're ending it able to stand up a mail server. That's a distance worth noticing.