← XeFM crftwr/xefm on GitHub · craftware

SSH/SFTP Subsystem

XeFM’s remote browsing runs one ssh <host> -s sftp process per host and speaks the SFTP protocol to the server at the other end of its stdin/stdout. This document records why it is built that way and the behaviors that keep it correct and fast, so they aren’t accidentally undone.

Related code:

Related docs:


Why one session, spoken to directly (#532)

XeFM used to run a fresh sftp -b - batch per operation and parse its text output, which only performed because every one of those processes rode an OpenSSH ControlMaster — a shared connection reached over a Unix socket. The OpenSSH built into Windows has no ControlMaster (ControlMaster=yes fails with getsockname failed: Not a socket before connecting), so SSH did not work with it at all, and without sharing, each operation would pay a full login.

Every serious remote client avoids that the same way: hold one connection and multiplex inside it yourself. VS Code Remote-SSH runs its own protocol over one ssh; WinSCP and FileZilla embed SSH. XeFM’s equivalent needs nothing on the server: OpenSSH’s sftp-server is already there, and ssh -s <host> sftp is exactly how sftp itself reaches it. So:

The cost is the protocol client, xefm/sftp_client.py.

The protocol client — SFTPClient

SFTP v3 (draft-ietf-secsh-filexfer-02, what OpenSSH implements). Each packet is uint32 length, byte type, payload; every request carries an id that its reply echoes.

The session — SSHConnection

ssh_command() builds the ssh command line. Its -o options are those sftp passes to the ssh it starts — ForwardX11=no, ForwardAgent=no, PermitLocalCommand=no, ClearAllForwardings=yes (a LocalForward in the user’s config that cannot bind must not become this session’s problem) — plus BatchMode=yes (there is no terminal to prompt on), StrictHostKeyChecking=accept-new, and ServerAliveInterval=15 / ServerAliveCountMax=4, so a dead link ends the session within about a minute instead of leaving requests waiting on it.

_spawn_ssh() starts it with binary pipes on all three streams; on Windows with CREATE_NO_WINDOW, so the GUI app does not flash a console. A thread drains stderr (so it can never fill and stall ssh) and keeps its last lines.

Connecting. connect() starts the process, then the INIT/VERSION handshake, bounded by CONNECT_TIMEOUT (30 s, ProxyCommand and all). If the stream ends before VERSION, the login failed, and what ssh printed is the only account of why: _login_failure() maps “Permission denied” to SSHAuthenticationError, “timed out” / “Connection refused” / “No route to host” to SSHConnectionTimeoutError, and anything else (host key changed, unknown host, …) to an SSHError carrying ssh’s own words.

Default directory. connect() asks REALPATH(".") — where the server starts a session, normally the home directory — and keeps it as default_directory (falling back to / if the server will not say).

Requests. _call() runs one client operation and maps its failures: NO_SUCH_FILE → SSHPathNotFoundError (logged at debug for stat / list_directory, which are often plain existence checks), PERMISSION_DENIED → SSHPermissionDeniedError, other statuses → SSHError with the server’s message, SFTPClosed → SSHConnectionLostError. A timeout drops the session — its state is unknown once a reply has gone missing — and raises SSHConnectionTimeoutError; the next use reconnects.

Liveness is free: is_connected() is “the client is alive and the ssh process has not exited”. The client notices on its own when the stream ends, so there is no periodic check and nothing to cache.

SSHConnectionManager keeps one SSHConnection per host, replaces one that has dropped on the next get_connection(), closes idle ones in cleanup_idle_connections(), and closes them all at exit (registered with atexit when the manager is first created). Even without that, closing XeFM closes ssh’s stdin, which ends the session on both sides.

Packaged-app PATH (macOS DMG)

A DMG-mounted app does not inherit the user’s shell PATH. SSH configs that use a ProxyCommand shelling out to aws, gcloud, etc. therefore can’t find those tools, and the login fails.

macos_app/src/XeFMAppDelegate.m fixes this in setupEnvironmentPath, called before the XeFM module is imported. It prepends the common tool locations — /usr/local/bin, /opt/homebrew/bin, /opt/local/bin, ~/bin, ~/.local/bin, and the ~/Library/Python/3.x/bin dirs — to PATH via setenv, and mirrors the result into Python’s os.environ so the ssh process (and thus the ProxyCommand) can resolve those tools.


Paths and entries

Normalization. list_directory() and stat() run remote_path through posixpath.normpath() before the cache lookup and the request. Search and path-join operations can hand over runaway ./././… or .. segments; normalizing collapses them and keeps equivalent paths on one cache key.

. and .. are dropped by SFTPClient.listdir(). A surviving . would re-enter the current directory, so a recursive walk would loop and a search would return nonsense — the check is on the decoded name, never on text.

Entry records (_entry()): name, size, mtime (seconds, from the server — not a minute-resolution ls date), mode (the full st_mode, so stat.filemode() and S_ISDIR work on it), is_dir, is_file, is_symlink.

Symlinks are described as a local directory listing describes them: by what they point to — a link to a directory is a directory to browse into — but still flagged as a link. READDIR returns lstat attributes, so _resolve_links() sends a STAT for every link in the listing, all in flight at once (stat_many); a broken link keeps its own attributes. stat() is LSTAT, then the same resolution if it is a link.

Requests in flight — CONCURRENCY

The session serves requests side by side, so SSHPathImpl declares CONCURRENCY = 64 — what OpenSSH’s own sftp keeps in flight by default (-R). The model behind the number, and how each operation sizes itself from it, is in STORAGE_CONCURRENCY_SYSTEM.md. What it changes here:

Measured against the Tart VM’s real sshd behind a 40 ms round-trip delay line, 259 directories / 864 files of ~2 KiB, and 400 files of 8 KiB:

  before after
disk usage 22.4 s 0.68 s
content search 302 s 3.2 s
copy 400 files SSH → local 80.3 s 8.9 s
copy 400 files local → SSH 70.4 s 7.5 s

Earlier, against a local sftp-server behind the same delay, the 259-directory walk went from 53.4 s (one directory at a time, four round trips each) to 25.9 s with the READDIR read-ahead and unwaited CLOSE, and 1.8 s with 16 listings in flight (#538).

With several listings in flight, results arrive in the order the listings complete rather than strictly depth-first; each directory’s own entries still come together and in order. A content search hands its results over in that same walk order.

Bulk stat caching during list_directory

A listing already carries every entry’s attributes, so while building it list_directory() also writes each entry into the cache under the key stat() uses — _cache.put(operation='stat', hostname=…, path=…, data=entry) for posixpath.join(remote_path, name). A stat() of any listed file is then a pure cache hit. SSHPathImpl.listdir_attrs() answers a pane’s listing from the same records without a request per entry.

Tests