chronytop replaced repeated chronyc subprocesses with a direct Go client for chronyd's command protocol. The interesting parts are its reply matching, persistent sessions, pagination, and race-resistant Unix socket setup.
· 7 min read

Inside chronytop's direct chronyd client


chronytop is a btop-style terminal dashboard for the chrony NTP daemon. Its first implementation ran chronyc for each refresh and parsed CSV. The version reviewed here had already removed that backend.

Instead, chronytop implements the read-only parts of chronyd’s version 6 command protocol in Go. It keeps persistent Unix datagram sessions, encodes requests itself, validates every response, and creates the reply sockets chronyd needs without leaving an obvious symlink or rename race.

This article is pinned to chronytop commit 6ec85de, the latest upstream revision when this post was raised. That matters because the project was changing quickly.

Make the command set an allowlist

The protocol client does not accept an arbitrary command number and hope the caller behaves. query starts with an allowlist of the five report commands the dashboard understands:

size := 0
switch command {
case cmdSources:
	size = 32
case cmdSource:
	size = 76
case cmdTracking:
	size = 104
case cmdServer:
	size = 196
case cmdClients:
	size = 520
default:
	return nil, 0, errors.New("unsupported chrony command")
}

Those sizes are not just buffer choices. Chrony’s protocol version 6 expects requests to be padded according to the largest supported reply for that command. The code writes the protocol version, packet type, command and sequence number in big-endian order, then places any 32-bit arguments at the protocol’s fixed offset.

The client list deserves its own safety check. Chronyd’s clients command includes a reset argument; chronytop always sends zero:

// reset=0 is essential: monitoring must never reset chronyd's counters.
b, _, err := c.query(cmdClients, index, maxClients, uint32(minPackets), 0)

The internal API therefore exposes reports, not a general command channel. A future caller cannot accidentally turn this monitoring process into an administrative client without first extending the allowlist.

Match replies before decoding them

A datagram arriving on the socket is not automatically the answer to the most recent request. It may be delayed or unrelated. chronytop increments a sequence number per query and checks both that number and the command before it decodes anything:

if wire.Uint32(buf[16:]) != c.sequence || wire.Uint16(buf[4:]) != command {
	continue // An unrelated or delayed reply must not become a sample.
}
if buf[0] != 6 || buf[1] != 2 || buf[2] != 0 || buf[3] != 0 {
	return nil, 0, errors.New("unsupported chrony reply header or protocol version")
}

It then validates the status, reply kind and minimum payload length. Server statistics need extra care because chrony 4.0, 4.2 and 4.3 use three different reply layouts. The decoder accepts those known layouts explicitly instead of treating one version’s bytes as another’s counters.

Chrony’s floating-point format is another place where a normal decoder would be wrong. It is not IEEE 754: it stores a signed seven-bit exponent and a signed 25-bit coefficient. chronytop sign-extends both fields and uses math.Ldexp to reconstruct the value.

This is the unglamorous part of binary protocol work: validate the envelope first, select a known layout, and only then assign meaning to offsets.

Give each worker its own persistent session

Regular samples and the potentially long client list run at different cadences. They also use separate chronySession values, each owning one persistent socket:

sampler := &chronySession{network: a.network, address: a.address}
clientSession := &chronySession{network: a.network, address: a.address}

That separation prevents multi-page client retrieval from blocking the normal tracking, source and server-stat samples. It also keeps each socket serial: there is no request multiplexer and no mutex around a shared connection.

chronySession.run sets one deadline for the complete query group. The normal sample gets two seconds; the entire client list, including every page, gets ten. If the caller’s context has an earlier deadline, that wins.

Cancellation uses context.AfterFunc to close the connection and unblock any pending I/O. The deferred cleanup waits for a cancellation callback that has already started, so that callback cannot race with a later query and close a replacement socket. Transport and protocol failures discard the session, while a valid command rejection does not: a daemon saying “not authorised” does not prove the socket is broken.

On UDP, the client retries a timed-out request at most twice without extending the group’s original deadline. It also randomises the initial sequence number. The source comments are precise about what that buys: connected UDP filters the sender address and the random sequence makes off-path guessing harder, but neither is authentication.

Paginate defensively

The offenders panel can represent a busy public server, so the clients command returns at most eight records per response. chronytop keeps asking from the returned next index until it reaches total or gets a short page.

Two checks stop a bad response from turning that loop into a memory or CPU problem:

if count > maxClients {
	return nil, errors.New("invalid chrony client count")
}
// Decode at most count records...
if next <= index {
	return nil, errors.New("chrony client pagination did not advance")
}

The minimum-packet filter is sent to chronyd rather than applied after downloading every client. That keeps the result smaller at the source. The code also rejects values outside an unsigned 32-bit integer before encoding them, so converting the flag to the wire type cannot silently wrap.

Build Unix reply sockets without trusting pathnames

Unix datagram clients need a local address for replies. chronytop creates that socket beside chronyd’s socket because /tmp may live in a different mount namespace under systemd’s PrivateTmp.

Creating a predictable directory and cleaning it up by pathname would open several races, especially when chronytop is running with elevated privileges. prepareChronySocket instead:

  1. Opens the parent directory with O_PATH, pinning that directory even if its name is later replaced.
  2. Creates a random outer directory with mode 0700 using Mkdirat.
  3. Reopens it relative to the parent descriptor with O_NOFOLLOW and verifies its owner and mode using Fstat.
  4. Creates a second, secret directory name inside it and opens that directory by descriptor too.

The socket is bound inside the secret directory. After binding, the code makes the socket writable and both directories searchable so chronyd’s user can traverse the path and send a response, without granting directory listing or modification to other users.

Cleanup remains descriptor-anchored. It removes the socket with Unlinkat, removes the inner directory through /proc/self/fd, and checks os.SameFile before removing the outer pathname. It never recursively deletes a directory that another process may have swapped into place.

The general lesson is broader than chrony: once an attacker can rename a directory between “check” and “use,” repeating pathname checks is not enough. Open the directory, operate relative to its descriptor, and make cleanup non-recursive.

Keep UI state in one goroutine

The transport has two sessions, but the dashboard state still has one owner. App.run selects over the sample timer, client results, keypresses and signals. Only the client fetch runs as a worker, and it sends a value back rather than mutating a.stats itself.

if !fetching && a.visible["3"] && time.Now().After(nextClients) {
	fetching = true
	workers.Add(1)
	go func() {
		defer workers.Done()
		c, err := clientSession.clients(ctx, minPackets)
		results <- clientsResult{c, err}
	}()
}

The fetching flag prevents overlapping client queries. On shutdown, the main goroutine cancels the context, waits for that worker, and only then closes both sessions. A zero-duration timer triggers the first sample immediately; subsequent resets use the current UI interval.

SIGWINCH causes a redraw, while the other registered signals exit. Because drawing happens after the select, a resize or keypress updates the screen without waiting for the next metrics sample.

For another compact Go TUI to read alongside this one, see the Heimdall hardware dashboard.

Treat root-owned settings as a separate boundary

The command socket is not the only sensitive path. chronytop is commonly started with sudo, so its settings loader refuses to use a config directory or file unless Lstat says it is the expected type and its owner matches the process’s effective UID. A non-root HOME inherited through sudo therefore does not receive root-owned files.

Saving uses a temporary file in the verified directory, checks the write and close errors, then renames it over the destination:

f, err := os.CreateTemp(dir, ".chronytop-*.tmp")
if err != nil {
	return err
}
defer os.Remove(f.Name())
if _, err := f.WriteString(s.String()); err != nil {
	_ = f.Close()
	return err
}
if err := f.Close(); err != nil {
	return err
}
return os.Rename(f.Name(), filepath.Join(dir, configName))

The explicit close matters because some write failures only surface there. Renaming before checking it could replace a good config with an incomplete one. CreateTemp also avoids following an existing destination symlink, and the same-directory rename makes the final replacement atomic.

None of these techniques is novel alone. The interesting part is how they fit together: a narrow command allowlist, strict reply matching, one connection per worker, bounded pagination, descriptor-relative filesystem operations, and a single owner for UI state. Removing chronyc made chronytop more than a parser, but it also made those boundaries visible enough to audit.