szn

Bug 448 — handleClient .command case writes the response to fd before re-validating that the client still exists

448. The #443 guard runs after the switch, too late for the .command branch

Severity: MEDIUM Status: Fixed

Symptoms

None observable today. cmdDetachClient returns .stop (which merely emits an .exit response) and no current command calls removeClient, so the .command branch never hits the stale-fd window in production. The window opens the moment a command, or a keybinding-to-command path, is extended to remove the client the way executeAction(.detach) already does via stdin_data.


Root Cause Analysis

Bug #443 hardened handleClient against the client being removed during message dispatch by adding, after the switch:

// src/server/server.zig:2595
if (!self.client_readers.contains(fd)) return;

But the .command case (server.zig:2459-2492) does its post-dispatch work before that guard:

  1. dispatch.dispatchCommand(...) runs the command (line 2461) — the only dispatch site that can, via a future command, trigger removeClient(fd).
  2. The is_display scan over display_clients (lines 2465-2471).
  3. The response write: queueToClientUrgent(fd, ...) (line 2482) or dispatch.sendResponse(fd, ...) (line 2484) — on a fd that may have just been closed by a client-removing command.

The stdin_data route was the trigger for #428/#443 precisely because its handler (processInput → executeAction(.detach)) can free the reader inside the switch body; the .command body has the same property, it just lacks a today-reachable destroyer. The guard is a defence that is logically correct for the loop as a whole but arrives one dispatch too late for the .command case’s response write.


Solution

Re-validate the client at the top of each case (or immediately after dispatchCommand) before touching fd:

.command => {
    var result = dispatch.dispatchCommand(self.allocator, self, pkt.data);
    if (!self.client_readers.contains(fd)) return; // client removed mid-command
    // ... response write on a still-live fd ...
}

Keeping the existing post-switch guard as defence-in-depth for the remaining cases. A regression test handleClient .command early returns if client removed mid-dispatch — bug #448 verifies that if a client is removed during command dispatch, the response write and reader consume are skipped without touching the closed fd or destroyed reader.