fix(ports): devvm ports says why a listed port isn't forwarded; a relay ends with its forward

The forwarder recorded every listed port it couldn't take on one line,
and devvm ports warned ports_taken ("in use on this machine") for all of
them, even a port past its limit of 256 forwards or one the host refused,
such as EACCES below 1024 on Linux. It now records why: in use
(EADDRINUSE), past its limit, or refused (EACCES, EPERM), each on a line
of its own in run/ports.forwarded (pid, forwarded, in use, limit,
refused). Any other listen error (EMFILE, ENOBUFS, EADDRNOTAVAIL...) says
nothing of the port: it's logged, not recorded, and tried again at the
next report, the log's limit capping the repeats. A port past the limit
is tried again at the next report once the forwarder is below it. An
older devvm's three-line record, whose third line held every failure,
is read as giving no reason, so it warns of none rather than call a
refused port in use; its forwarded ports still count.

A forward's close closed its accepted connections, but each relay's ssh
(-W) waited for the VM's sshd to end the channel, so a VM that ignored
EOF kept that ssh process and one of the forwarder's 256 relay slots
until the forwarder ended. Each relay now gets its own context, cancelled
by the forward's close under mu, so CommandContext kills its ssh; a relay
that ends by itself releases its context.

- vmssh: failure (in use, limit, refused) and failedPorts; failureOf's
  ok for errors that are the port's; Forwarder.try; apply clears limit
  failures below the limit; Note takes failedPorts;
  Forwards.Unforwarded replaces Taken; record writes five lines
  (recordLines); MaxForwards exported for ports_limit; forward.conns
  holds each relay's cancel
- messages ports_limit (count, limit, ports, vm) and ports_refused
  (count, ports, vm), linked to troubleshooting's listed-port section;
  devvm ports warns each by why
- --json unchanged: it never listed failed ports
- tests: TestForwarderFailures (EACCES, EPERM and EADDRINUSE through
  Listen, EMFILE tried again unrecorded, the limit and its retry once
  below it), TestForwarderEndsStuckRelay (an ssh stand-in on PATH that
  never exits: the relay ends, the process is gone, the slot is free),
  TestForwardsHeld's record round trip, older and foreign records, and
  ports.txtar's three warnings from a record and none from an older one
- docs: internals/ports (record lines, relays, when it can't forward and
  what's retried), the design note (how many, each connection, the
  below-1024 lead, the stuck relay as confirmed and fixed, channels a VM
  never closes as listed), ports-size, troubleshooting, CHANGELOG Fixed

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
w3cjandClaude Opus 5.5 committed 2026-11-13 07:38:42 -07:00
1 parent 54cce97049
commit f76b2fa2a4
16 files changed
+443 -116

No files matched your search

+2
View File
@@ -32,6 +32,8 @@
### Fixed
- **`devvm ports` says why a listed port isn't forwarded:** it said that a program on this machine had every listed port the VM's forwarder couldn't take, even when the VM already forwarded 256 ports, the most it can at once, or when this machine refused the port, as Linux does for ports below 1024. Each reason now gets its own warning, and a port past the limit is forwarded once the VM forwards fewer ([a listed port isn't forwarded](https://next.devvm.dev/docs/using/troubleshooting/#a-listed-port-isnt-forwarded)).
- **A forwarded connection ends with its port:** when devvm stopped forwarding a port, a connection whose other end the VM kept open kept its ssh process, and one of the 256 connections that a VM's forwarder carries at once, until the forwarder ended. devvm now ends that connection's ssh along with the port's forward ([how it reaches the VM](https://next.devvm.dev/docs/internals/ports/#how-it-reaches-the-vm)).
- **Cursor's CLI couldn't chat:** `cursor-agent` kept reconnecting to its agent's host, because Cursor sends its agent's stream with gzipped messages, which the VM's proxy refused. The proxy now reads such a stream message by message, decompressing each to check it for a token before it passes ([Cursor CLI login](https://next.devvm.dev/docs/using/coding-agents/#cursor-cli-login)).
- **A stopped VM no longer keeps its listed ports from other VMs:** when one VM lists a port, such as 5173, and stops, another VM forwards that port meanwhile. Only a running VM holds a port. When the first VM starts again, devvm warns that the other VM has the port, `devvm ports` says so too, and its `--json` has the other VM in `held_by`. The first VM forwards the port within about 20 seconds of the other one stopping, without a restart. While the first VM is stopped, the other VM's app on that port shares its place in your browser, its site data and service workers included, as two projects on one port would ([two VMs and one port](https://next.devvm.dev/docs/using/ports-size/#two-vms-and-one-port)).
- **opencode's links at `devvm agent import`:** a link in `~/.config/opencode` was dropped without a word. It now gets what the other agents' links get: a link to a file inside the folder is copied as that file, and any other link is left out with a warning that names it ([importing from this machine](https://next.devvm.dev/docs/using/coding-agents/#importing-from-this-machine)).
+5 -3
View File
@@ -43,9 +43,9 @@ These settings guard against the host's ssh asking for a forward that devvm's en
- **A forwarder per VM, on the host.** The forwarder is `vmssh.Forwarder`, which isn't a backend's. Its owner, `vmssh.Forwards`, runs it detached as `devvm _ports`, one per VM, for project VMs alone, because only a project VM's start goes through it, and builds' starts don't. The owner starts it once the backend's `Start` returns, and again on a running VM when its ports change, each after stopping any forwarder the VM had, which ends the connections open through it. devvm finds that one by its pid file, which it checks against the process's arguments, as it does for the proxy. It sends that forwarder SIGTERM and kills it if it hasn't ended within 2 s, so its ports are free before devvm asks which listed ports a host program has. devvm holds a lock of the VM's own (`ports.lock`, beside its pid file `ports.pid` in the VM's run folder) from stopping the old forwarder until the new one has started, so two devvm runs at once, such as a start and `devvm ports`, leave one forwarder, the one its pid file names. The owner waits up to 10 s for the forwarder to say it forwards while it runs. The forwarder says so in a status file of its own beside its pid file (`ports.status`), which holds its pid and which devvm removes before each start. If it doesn't, devvm warns with `ports_forward_failed`, naming its log, and leaves it to keep trying while the VM runs on.
- **Reaching the VM.** The forwarder makes one ssh connection, a master (`ssh -F none -M -S <socket>`), to the VM's sshd on Lima's ssh port on the host's loopback. Lima's `SSH` gives the port with the user and the key, the first `IdentityFile` of Lima's ssh config, and devvm refuses that target unless the config names `127.0.0.1` (`vmssh.FromTarget`, the check links and the ssh config use too). It logs in as Lima's user with Lima's key alone (`IdentitiesOnly`, `IdentityAgent=none`), `_config/user` in devvm's Lima home, which every VM there authorizes, and never with the user's agent. The master reads none of the user's configuration and forwards nothing either way, with `ClearAllForwardings`, `PermitRemoteOpen none`, `ProxyCommand none`, and no agent, X11 or tunnel. The VM's sshd allows local forwarding, and remote forwards only to `127.77.0.0/16` for [links](#links-between-vms) (`base.sh`), and `-W` is local forwarding. Its control socket is in `~/.local/share/devvm/run` (mode 700) and is named by a hash of the VM's name, because a socket's path has fewer than 104 characters. When the connection is lost, the forwarder closes its forwards and makes the connection again every 2 s while the lifeline holds.
- **What listens.** The master's session runs `ports.sh` (`assets/guest/ports.sh`) as the VM's user (`sh -s`). It prints the local addresses of the VM's listening TCP sockets, which are the state `0A` lines of `/proc/net/tcp` and `tcp6`, whenever they change and every 10 s regardless, so it ends soon after the connection does. The forwarder treats the report as untrusted. A line over 128 bytes or a report over 4096 lines ends the connection, and anything that isn't a hex address and port is skipped. Reports are applied at least 500 ms apart, and one that comes sooner waits, holding up the VM's ssh channel with it, so the VM can't make the forwarder bind, dial and read devvm's state at its own pace. The VM can make the forwarder write to its log, with ports coming and going and with the session's stderr, so the log takes 200 writes at once and then one every 10 s. Each write is at most 512 bytes, without control characters but newlines and tabs, C1 included, and a start empties the log once it's over 1 MiB. A forwarded port's connections go to `127.0.0.1` for a server on all IPv4 addresses or on that address, and to `::1` for a server on all IPv6 addresses or on that address. A server on another `127.x` address alone gets its connections there. Servers on other addresses alone aren't forwarded.
- **How many.** With every port, the forwarder takes ports from 1024 up, because the ports below are the host's system services. With listed ports, it takes those alone (`-only`), a listed port below 1024 included, because the user asked for it, and a bind the host refuses is logged. Either way the forwarder takes at most 256 ports at once. It reads the reserved ports (below) again with each report, and while it can't read them, it takes no new port and keeps those it has. A port it has that has since become reserved, such as one another VM's start has chosen, is given up at that report, though the VM still listens on it, and also within 10 s on the host's own clock (`Forwarder.Recheck`), whether or not the VM reports, so a VM that holds its session open and stays silent can't keep it. A reserved port the VM listens on waits and is tried again at each report until it's no longer reserved. Any other port the forwarder couldn't take, such as one a host program has, is tried again only once the VM's server on it goes and comes back.
- **How many.** With every port, the forwarder takes ports from 1024 up, because the ports below are the host's system services. With listed ports, it takes those alone (`-only`), a listed port below 1024 included, because the user asked for it, and a bind the host refuses is logged. Either way the forwarder takes at most 256 ports at once (`vmssh.MaxForwards`). It records why it couldn't take each port in `ports.forwarded`, by the bind's error: in use (`EADDRINUSE`), past its limit, or refused (`EACCES` or `EPERM`, such as below 1024 on Linux), and `devvm ports` warns each with its own message (`ports_taken`, `ports_limit`, `ports_refused`). Any other error, such as `EMFILE`, `ENOBUFS` or `EADDRNOTAVAIL`, says nothing about the port, so it's logged, not recorded, and the port is tried again at the next report, the log's limit capping the repeats. A port past the limit is tried again at the next report once the forwarder forwards fewer. A record from before the reasons, whose third line holds every port it couldn't take, is read as giving no reason, so it warns of none rather than call a refused port in use. It reads the reserved ports (below) again with each report, and while it can't read them, it takes no new port and keeps those it has. A port it has that has since become reserved, such as one another VM's start has chosen, is given up at that report, though the VM still listens on it, and also within 10 s on the host's own clock (`Forwarder.Recheck`), whether or not the VM reports, so a VM that holds its session open and stays silent can't keep it. A reserved port the VM listens on waits and is tried again at each report until it's no longer reserved. A port that a host program has, or that the host refused, is tried again only once the VM's server on it goes and comes back.
- **Listening.** The forwarder listens on `127.0.0.1` and `::1`, or on IPv4 alone on a host without IPv6. It binds without `SO_REUSEADDR` (`platform.ListenExclusive`). With that option, which Go and Lima set, macOS lets a socket take `127.0.0.1:PORT` while a program has `*:PORT`, and that program's loopback connections go with it. Without the option, the bind is refused when another program has the port on any address. This was checked on macOS for a program on `0.0.0.0`, on `::` (IPv4 and IPv6 at once, as Node's and Go's servers listen), on IPv6 alone and on `127.0.0.1`, each with and without `SO_REUSEADDR` of its own. A port held only by ended connections (`TIME_WAIT`, with nothing answering on it) is taken as usual, so a server that restarts gets its forward back. When a bind is refused, the forwarder dials the port and takes it only if the dial is refused. A full backlog times out, which counts as taken. A port the forwarder took on `127.0.0.1` but finds in use on `::1` is given up, so `localhost` never reaches two programs. On Linux, `SO_REUSEADDR` stays on. Linux refuses that bind with the option too while another socket listens on the port, and without it, the forwarder's own ended connections (`TIME_WAIT`) would keep anyone from listening on the port for a minute, its next forwarder included.
- **Each connection.** Each forwarded connection is a channel of the master's (`ssh -S <socket> -W HOST:PORT`), with one process per connection and at most 256 at once. The VM's sshd opens it to the VM's own loopback from inside the VM. The channel's ssh has the master's options. If the master is gone, ssh connects on its own, and it then reaches the VM's sshd the same way, never the host's.
- **Each connection.** Each forwarded connection is a channel of the master's (`ssh -S <socket> -W HOST:PORT`), with one process per connection and at most 256 at once. The VM's sshd opens it to the VM's own loopback from inside the VM. The channel's ssh has the master's options. If the master is gone, ssh connects on its own, and it then reaches the VM's sshd the same way, never the host's. Each relay's ssh runs with a context of its own, which closing its forward cancels, so the ssh is killed with the forward even when the VM never ends its channel.
- **Reserved ports.** The forwarder never takes the VM's own Lima ssh port, which Lima's `SSH` names, or its proxy port, which its state records, and the owner passes both as `-reserve`. It also never takes the ssh, proxy and desktop ports devvm chooses and records in any VM's state, the ports another VM's running forwarder forwards now, as its `ports.forwarded` record says, or the ports another VM lists while it has a claim on them, which is while its forwarder runs or while devvm holds its `ports.lock` to start one again, unless this VM lists them too (`ports.Reserved`). A stopped VM's listed ports aren't reserved from other VMs' forwarders, but the ports devvm chooses still avoid them (`ports.Used`). Every Lima VM's ssh port is one of those, whatever its tier: devvm chooses it when it makes the VM, sets it with `limactl clone --set .ssh.localPort`, and records it in the VM's `ports` section before the clone (`ports.Allocator.SSH`). One allocator, `ports.Allocator`, chooses every host port devvm chooses, the ssh, proxy and desktop ports, and records it while it holds the VM's lock and then the claims lock (`run/claims.lock`, `state.VM.Claim`) until the VM's state is written, so two devvm commands making or starting VMs at once never choose the same one. A build VM has no state, so devvm chooses its ssh port too, on every host, through the same allocator (`ports.Allocator.Build`), under the claims lock alone (`state.Claims`), and on macOS the build's Seatbelt profile names that port. It records the port by the build VM's name (`run/build-ports/<name>`), where `ports.Used` reads it, until `limactl start` returns, and by then Lima has bound the port or the start has failed. The devvm that starts the build holds a file lock on that record until then, and the kernel lets go of the lock when that devvm ends, even when it's killed. Each time devvm chooses a port, under the claims lock, it first deletes the records whose lock no process holds and that are over 15 minutes old. The age matters because a killed devvm leaves its `limactl start` running, which may still bind the port for up to Lima's 10 minutes of waiting for the VM's ssh. So a devvm killed while its build VM starts reserves that port for 15 minutes, and then only until the next port is chosen. A stopped VM gets a new one only when a program on the host has its port on any address, even one that accepts no connections, or when the VM lists it to forward, and its start then sets it with an edit. Lima binds the port only once the VM boots, a few seconds after its start, so a port Lima picked itself would be free for another VM's forwarder in that window, and Lima's own ssh, which checks no host key, would then reach the other VM (the threat check below).
- **The host key.** devvm keeps one record of a VM's host keys for each of its starts, `vms/<hash>/run/known_hosts` (`vmssh.PinHostKeys`). It removes the record before each start and reads the keys after it, through `limactl shell`, at most 64 KiB for at most 30 s, keeping only lines whose key decodes and names its own type (`vmssh.ParseHostKeys`). The record's first line names the start it was read for (`backend.Run.ID`), so a record of another start, such as one before a `limactl start` outside devvm, is read again, and keys read while the VM started again aren't recorded. The forwarder checks the VM against that record, with `HostKeyAlias` and `StrictHostKeyChecking yes`, as the ssh config, links' sessions and a `--clone` VM's git do. All of them reach the VM through one function, `vmssh.Checked`, which checks the backend's ssh and adds the record: the forwarder and the ssh config pin the keys when the record is another start's, and links' sessions and git take only a record of the current start. The pin keeps the forwarder from talking to a program on the host that takes the ssh port. It doesn't guard against the VM itself, which is already the other end of the connection.
- **Its lifeline.** The forwarder follows the hostagent's pid file (`ha.pid`, the lifeline Lima's `Running` gives), as the proxy does, and exits once the file is gone, holds anything else, or its process is gone. `devvm stop` stops it with the VM, and `devvm rm` and `devvm gc --orphans` stop it before they delete its files with the VM's folder. A VM that stops some other way, such as when its self-check fails or a restart stops it, ends its forwarder through the lifeline, and the next start stops any forwarder that's left before it starts its own.
@@ -75,10 +75,12 @@ These settings guard against the host's ssh asking for a forward that devvm's en
- **A port the VM chooses:** ruled out. `-only` comes from the VM's state, less the ports a host program has, both read on the host by the forwarder's owner, and the VM's reports can't add to it. A listed port is forwarded only while a server in the VM listens on it, as with every port.
- **Port 22 listed:** ruled out as a collision. Port 22 in the VM is its sshd, and Lima's ssh forward comes from another host port, so a listed 22 forwards the VM's sshd to the host's port 22 as it would forward any server. The VM's sshd still takes only keys. A host whose own sshd has port 22 keeps it, with a `ports_taken` warning.
- **A listed proxy port:** ruled out. The forwarder reserves the VM's own proxy port whether or not it's listed, and every other VM's as well.
- **A listed port below 1024:** taken because the user asked for it. A host service that has the port keeps it, and a bind the host refuses is logged. One that isn't running yet is under **Not covered**.
- **A listed port below 1024:** taken because the user asked for it. A host service that has the port keeps it, and a bind the host refuses is logged and recorded as refused, never as in use, so `devvm ports` warns `ports_refused` rather than `ports_taken`. One that isn't running yet is under **Not covered**.
- **A forwarder left behind:** ruled out. `devvm stop` stops it, `devvm rm` stops it and removes its files, any other stop ends it through its lifeline, and a start or change whose listed ports are all taken runs none. Two devvm runs that start a VM's forwarder at once take turns on the VM's lock, so the second stops the first one's forwarder, and neither leaves one that its pid file doesn't name, which nothing would stop.
- **A tier's confinement:** ruled out. Listed ports take fewer ports than every port, never more, and every connection still starts on the host.
- **Another VM takes a stopped or restarting VM's listed port:** mitigated. Only a running VM holds a port, so while VM V is stopped, another VM E may forward V's listed port, and a hostile E could then try to keep it, such as by forwarding every port and holding its ssh session open without reporting again. Three things stop that. First, the host decides when a port is given up: every forwarder closes each forward whose port is now reserved within 10 s on its own clock, whatever its VM reports, so E gives V's port up once V runs and lists it. Closing a forward also closes every connection it accepted that's still open, so a browser's keep-alive connection to `localhost:5173`, opened while E had the port, ends then too, and the browser's later requests, with V's cookies, never reach E over it. Second, V's start, a change of its ports and `devvm ports` warn with `ports_held` and name E in `held_by`, whether E lists the port or forwards every port, so V never waits silently. Third, V's listed ports stay reserved while devvm holds V's `ports.lock`, from stopping V's old forwarder until its new one runs, so no other VM takes them in that window. A stale `ports.forwarded` can't hold a port either: devvm removes it under that lock before each start, each forwarder writes an empty one when it starts, and a record counts only while its pid is the VM's running forwarder.
- **A relay the VM holds open:** confirmed, fixed. Closing a forward closed the connections it had accepted, but each connection's ssh (`-W`) waits for the VM's sshd to end its channel, so a hostile VM that ignored the EOF kept that ssh process, and one of the forwarder's 256 relays, until the forwarder ended. Up to 256 such ssh processes could pile up on the host for each VM, and the VM's forwards would then refuse every new connection. Each relay now runs with a context of its own, which closing its forward cancels, under the forwarder's lock as the close already runs, so the ssh is killed (`exec.CommandContext`), and a relay that ends by itself releases its context. Unit-tested with an ssh stand-in that never exits on its own: the relay ends, its process is gone and its slot is free once the forward closes (`TestForwarderEndsStuckRelay`), with no goroutine or file descriptor left under `-race`.
- **Channels the VM never closes in the master:** listed. A hostile VM that never sends CLOSE for a killed relay's channel can leave small channel entries, with no file descriptor, in the forwarder's ssh master. At most 256 relays run at once, which bounds them, and no code change is needed.
**Not covered:**
+14 -2
View File
@@ -24,7 +24,7 @@ When a start, or a change of a running VM's ports, finds that a program on this
### Ports other VMs forward
A host port that two VMs could forward belongs to the running VM that forwards it, never to a stopped one, so a stopped VM's listed ports are free to the others until it starts again. Each forwarder writes the ports it forwards to `ports.forwarded` in its VM's run folder, `~/.local/share/devvm/vms/<hash>/run/`, after each change, with its pid on the first line, the ports it forwards on the second, and the ports it tried and couldn't take on the third, and it writes an empty record when it starts. A record counts only while that pid is the VM's running forwarder, as `ports.pid` and the process's arguments say, so the record of a VM that stopped or crashed, whose forwarder ended with it, holds nothing. devvm also removes the record under the VM's `ports.lock` each time it starts the VM's forwarder, so a pid used again never makes an old record count.
A host port that two VMs could forward belongs to the running VM that forwards it, never to a stopped one, so a stopped VM's listed ports are free to the others until it starts again. Each forwarder writes the ports it forwards to `ports.forwarded` in its VM's run folder, `~/.local/share/devvm/vms/<hash>/run/`, after each change, with its pid on the first line and the ports it forwards on the second. The next three lines hold the ports it tried and couldn't take, by why: those a program on this machine has, those past its limit of 256 forwards, and those this machine refused for another reason, such as a port below 1024 on Linux. It writes an empty record when it starts. A record counts only while that pid is the VM's running forwarder, as `ports.pid` and the process's arguments say, so the record of a VM that stopped or crashed, whose forwarder ended with it, holds nothing. devvm also removes the record under the VM's `ports.lock` each time it starts the VM's forwarder, so a pid used again never makes an old record count.
At each report from its VM, every forwarder reads the other VMs' states and records again, and it never takes these ports:
@@ -33,7 +33,7 @@ At each report from its VM, every forwarder reads the other VMs' states and reco
A VM that lists a port comes before one that forwards every port. Besides its VM's reports, every forwarder checks the ports it forwards against those rules every 10 seconds on its own clock and closes a forward whose port is now another VM's, so a VM that keeps its session open without reporting can't keep a port. Closing a forward also closes the connections it accepted that are still open, such as a browser's keep-alive connections, so none of them reaches the old VM afterwards. A VM that forwards every port therefore gives up a port within about 10 seconds of a running VM listing it.
A port the forwarder never takes for those reasons, and that its VM listens on, waits: the forwarder tries it again at each report, which comes at least every 10 seconds, and forwards it once it's free, even when an earlier try found it taken. A port the other VM gives up can therefore take up to about 20 seconds to reach this VM: up to 10 for the other forwarder's check and up to 10 for this one's next report. When a start or a change of ports finds that another VM forwards one of the VM's listed ports now, whether that VM lists it or forwards every port, devvm keeps the port in the VM's list and warns you (`ports_held`), and `devvm ports` warns again, with the other VM in its JSON's `held_by`. A port that another VM forwards isn't a program's, so it never gets `ports_taken`. A listed port of a running VM that its forwarder tried and found a program's is only logged by the forwarder, and `devvm ports` warns about it with `ports_taken`. `devvm ports` reads that from the forwarder's record and binds nothing to find out, so it never takes a port the forwarder is opening at that moment. A record that the running forwarder didn't write, such as an older devvm's forwarder's after an upgrade, or none, gives no such warning.
A port the forwarder never takes for those reasons, and that its VM listens on, waits: the forwarder tries it again at each report, which comes at least every 10 seconds, and forwards it once it's free, even when an earlier try found it taken. A port the other VM gives up can therefore take up to about 20 seconds to reach this VM: up to 10 for the other forwarder's check and up to 10 for this one's next report. When a start or a change of ports finds that another VM forwards one of the VM's listed ports now, whether that VM lists it or forwards every port, devvm keeps the port in the VM's list and warns you (`ports_held`), and `devvm ports` warns again, with the other VM in its JSON's `held_by`. A port that another VM forwards isn't a program's, so it never gets `ports_taken`. A listed port of a running VM that its forwarder tried and couldn't take is only logged by the forwarder, and `devvm ports` warns about it, as [When it can't forward](#when-it-cant-forward) describes.
When two VMs that list the same port start at once, neither waits for the other, because neither forwards it yet. The first forwarder to bind the port on this machine's loopback has it, because the system lets one listener have it, and the other forwarder's try fails. That forwarder sees the winner's record at its next report and waits for the port from then on. No lock is needed for this, and no port is shared.
@@ -52,6 +52,8 @@ flowchart TD
The forwarder is devvm's own, the same on every backend. The backend only says how the forwarder reaches a running VM's sshd, which is a user, a key and a port on this machine's loopback, and which file the forwarder follows to know the VM still runs, as Lima's [Ports](lima.md#ports) section describes.
Each forwarded connection gets an ssh process of its own, which carries it over the forwarder's ssh connection to the VM, and the forwarder carries at most 256 connections at once, refusing the next one. When a forward closes, because the VM's server stopped or its port is now another VM's, the forwarder closes that forward's open connections and ends their ssh processes too. A VM that never closes its end of a connection therefore can't keep that connection's ssh process, or one of the 256, after its port's forward has gone.
## Its process and files
The forwarder runs as a hidden devvm command, `devvm _ports`, one process for each VM. devvm starts it after each start of the VM, once the backend says the VM runs, and again with the new ports when you change a running VM's ports. `devvm stop`, `devvm rm` and `devvm gc --orphans` stop it, and a VM that stops some other way ends it, because the forwarder exits once the backend's process for the VM is gone. Which ports a VM forwards is in the VM's state, which devvm reads each time it starts the forwarder, so `devvm ports` changes the state and never the backend's config, and the backend never hears of them. The forwarder's log is `ports.log` in the VM's logs folder, `~/.local/share/devvm/vms/<hash>/logs/`, and its `ports.pid`, `ports.status`, `ports.lock` and `ports.forwarded` are in the VM's run folder, `~/.local/share/devvm/vms/<hash>/run/`, beside the VM's host keys for its current start, `known_hosts`, which the forwarder checks the VM against, as devvm's ssh config does ([ssh into VMs](security.md#ssh-into-vms)). Its control socket is `~/.local/share/devvm/run/port-<hash>.ctl`, named by a hash of the VM's name, outside the VM's folder, because a unix socket's path has fewer than 104 characters.
@@ -62,6 +64,16 @@ devvm reads every list of ports the same way, whether it comes from `--ports`, `
When a forwarder doesn't start, devvm warns you and names its log (`ports_forward_failed`), and the VM runs on without forwarded ports.
When a running forwarder tries a listed port and can't take it, it logs the port with the system's error and records why in `ports.forwarded`. `devvm ports` warns about each such port by why:
- `ports_taken`, when a program on this machine has the port, which the system reports as the address being in use. The forwarder tries the port again only once the VM's server on it stops and starts again.
- `ports_limit`, when the VM already forwards 256 ports, the most a forwarder forwards at once, so the forwarder didn't try it. The forwarder tries the port again at the VM's next report once it forwards fewer.
- `ports_refused`, when this machine denied the forwarder the port, such as Linux keeping ports below 1024 for root. The forwarder tries the port again only once the VM's server on it stops and starts again.
Any other error, such as running out of open files for a moment, says nothing about the port, so the forwarder logs it alone, records nothing, and tries the port again at the VM's next report.
`devvm ports` reads these from the forwarder's record and binds nothing to find out, so it never takes a port that the forwarder is opening at that moment. A port that another VM forwards isn't one of these, so it gets `ports_held` instead. A record that the running forwarder didn't write, or none, gives none of these warnings, and neither does a record from an older devvm's forwarder after an upgrade, which lists every port it couldn't take on one line, without saying why, so devvm never says a port is in use when it may not be.
## Links between VMs
A [link between VMs](../using/links.md) carries a client VM's connections to a port that a target VM publishes. Like the forwarder, it goes over ssh, every connection starts on this machine, and it uses neither VM's network, so no backend's confinement changes and a confined VM still reaches nothing past its proxy over its own network. [The design note](design.md#links-between-vms) has the rules, the threat check and what the prototype showed.
+2 -1
View File
@@ -41,12 +41,13 @@ devvm ports -g none # what new VMs forward (default: all)
- `devvm ports -g` shows what new VMs forward, followed by where it came from after a `#`, and `devvm ports -g --json` adds it as `source`. When [`config.toml`](settings.md#configtoml) sets `ports`, `devvm ports -g` refuses to change it and names the file, so edit `config.toml` instead ([where a default comes from](settings.md#where-a-default-comes-from)).
- devvm forwards ports on every [network tier](../safety/network.md#network-tiers), and it forwards no ports from builds.
When a VM forwards every port, devvm forwards each TCP port from 1024 up that a server in the VM listens on, whether on the VM's loopback or on all its addresses. When a VM lists its ports, devvm forwards those ports alone, however many there are, ports below 1024 included. A port reaches this machine within a few seconds of the server starting, only on `localhost` (`127.0.0.1` and `::1`), and the forward goes away when the server stops. At most 256 ports are forwarded at once ([what it forwards](../internals/ports.md#what-it-forwards)). Your browser sends the cookies of every app you use on `localhost` to a forwarded port as well, so the server in the VM gets them ([your browser](../safety/attack-vectors.md#the-network)).
When a VM forwards every port, devvm forwards each TCP port from 1024 up that a server in the VM listens on, whether on the VM's loopback or on all its addresses. When a VM lists its ports, devvm forwards those ports alone, however many there are, ports below 1024 included. A port reaches this machine within a few seconds of the server starting, only on `localhost` (`127.0.0.1` and `::1`), and the forward goes away when the server stops. At most 256 ports are forwarded at once ([when it can't forward](../internals/ports.md#when-it-cant-forward)). Your browser sends the cookies of every app you use on `localhost` to a forwarded port as well, so the server in the VM gets them ([your browser](../safety/attack-vectors.md#the-network)).
A VM never takes a port that a program on this machine already has, a port that another running VM forwards or lists, or a port that devvm uses for its VMs' ssh and proxies ([what it never takes](../internals/ports.md#what-it-never-takes)):
- When a port you listed is taken by a program on this machine as the VM starts, or as you change its ports, devvm warns you and the VM runs on without that port. The next start or change that finds the port free forwards it.
- A program that starts on a port after the VM's forward does can still bind it on all addresses, as most servers do, and then that program's `localhost` connections reach the VM.
- When the VM's server listens on a listed port that the VM can't forward, because a program on this machine has it, the VM already forwards 256 ports, or this machine doesn't let devvm use the port, such as one below 1024 on Linux, `devvm ports` warns you and says which of these it is ([a listed port isn't forwarded](troubleshooting.md#a-listed-port-isnt-forwarded)).
- If the forwarder can't start at all, devvm warns you and names its log, and the VM runs on without forwarded ports.
**UDP isn't forwarded, on any backend.** Run the UDP client in the VM instead, or tunnel it over a forwarded TCP port with [socat](http://www.dest-unreach.org/socat/doc/socat.html), installed on both sides. For a UDP server on port 8125 in the VM, with TCP port 9125 forwarded:
@@ -218,6 +218,11 @@ A bundle that `SSL_CERT_FILE` names in devvm's environment works too, because th
When a program on this machine already has a port that the VM lists, devvm warns that the VM doesn't forward it, and the VM runs on without it. Stop that program, then run `devvm restart`, or change the VM's ports with `devvm ports`, and devvm forwards the port once it's free ([ports](ports-size.md#ports)).
devvm warns about two other reasons too, each in its own words, and `devvm ports` repeats the warning while the VM runs:
- **The VM already forwards 256 ports**, the most it forwards at once. Stop the servers you don't need in the VM, or list fewer ports with `devvm ports`, and devvm forwards the port within about 10 seconds of the VM forwarding fewer.
- **This machine doesn't let devvm use the port.** On Linux, only root can listen on a port below 1024, so a listed port such as 80 isn't forwarded. Have the server in the VM listen on a port from 1024 up and list that port instead.
## A VM won't boot
A Lima VM that doesn't answer over ssh within a minute of starting is stopped. Read its console log before you start it again, because every start overwrites the log. The log is `serialv.log`, or another `serial*.log`, in the VM's folder in devvm's Lima home, which is `~/.local/share/devvm/lima/<vm>/` unless you set `DEVVM_LIMA_HOME` ([Lima's limits](../backends/lima.md#limits)).
+2
View File
@@ -174,6 +174,8 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede
"ports_list_needed": "using/ports-size#ports",
"ports_rm_all": "using/ports-size#ports",
"ports_taken": "using/troubleshooting#a-listed-port-isnt-forwarded",
"ports_limit": "using/troubleshooting#a-listed-port-isnt-forwarded",
"ports_refused": "using/troubleshooting#a-listed-port-isnt-forwarded",
"ports_held": "using/ports-size#two-vms-and-one-port",
"ca_not_certificate": "using/settings#a-companys-ca",
"ca_not_ca": "using/settings#a-companys-ca",
+12
View File
@@ -3794,6 +3794,11 @@ func PortsHeld(count int, other string, ports string, vm string) M {
return M{id: "ports_held", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"other", other}, {"ports", ports}, {"vm", vm}}}
}
// PortsLimit is [ports_limit]: "{{.vm}} doesn't forward ports {{.ports}} for now because it already forwards {{.limit}} ports, the most it can at once."
func PortsLimit(count int, limit string, ports string, vm string) M {
return M{id: "ports_limit", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"limit", limit}, {"ports", ports}, {"vm", vm}}}
}
// PortsListNeeded is [ports_list_needed]: "{{.value}} isn't a list of ports. Give ports and ranges, such as 5173,8000-8010."
func PortsListNeeded(value string) M {
return M{id: "ports_list_needed", vals: []val{{"value", value}}}
@@ -3804,6 +3809,11 @@ func PortsNow(ports string, vm string) M {
return M{id: "ports_now", vals: []val{{"ports", ports}, {"vm", vm}}}
}
// PortsRefused is [ports_refused]: "{{.vm}} doesn't forward ports {{.ports}} because this machine doesn't let devvm use them, as with ports below 1024 on Linux."
func PortsRefused(count int, ports string, vm string) M {
return M{id: "ports_refused", plural: true, count: count, vals: []val{{"count", strconv.Itoa(count)}, {"ports", ports}, {"vm", vm}}}
}
// PortsRmAll is [ports_rm_all]: "Every port is forwarded, so none can be removed. Set the ones to keep instead, as in devvm ports 5173,8000-8010."
func PortsRmAll() M {
return M{id: "ports_rm_all"}
@@ -6034,8 +6044,10 @@ var specs = map[string]spec{
"ports_forward_failed": {fields: []string{"log", "vm"}},
"ports_forwarding": {fields: []string{"ports", "vm"}},
"ports_held": {plural: true, fields: []string{"count", "other", "ports", "vm"}},
"ports_limit": {plural: true, fields: []string{"count", "limit", "ports", "vm"}},
"ports_list_needed": {fields: []string{"value"}},
"ports_now": {fields: []string{"ports", "vm"}},
"ports_refused": {plural: true, fields: []string{"count", "ports", "vm"}},
"ports_rm_all": {},
"ports_taken": {plural: true, fields: []string{"count", "ports", "vm"}},
"program_broken": {fields: []string{"command", "name"}},
+13 -4
View File
@@ -150,8 +150,10 @@ func orAll(ports string) string {
// Ports returns which ports the folder's VM forwards: all, none or a
// list, and those of its listed ports another running VM forwards now,
// which it forwards once that VM gives them up, each warned (ports_held).
// A running VM's listed ports that a program on this machine has instead
// are warned too (ports_taken).
// A running VM's listed ports that its forwarder couldn't take are warned
// too, by why: a program on this machine has them (ports_taken), it
// forwards as many as it can already (ports_limit), or this machine
// refused them (ports_refused).
func (e Settings) Ports(ctx context.Context) (PortsShown, error) {
t, err := e.finder.target(ctx, need{has: hasMade, noVM: msg.NoVMPorts})
if err != nil {
@@ -160,8 +162,15 @@ func (e Settings) Ports(ctx context.Context) (PortsShown, error) {
fwd := sectionOf[ports.Ports](t.st, ports.Section).Forward
out := PortsShown{List: orAll(fwd)}
f := e.forwards()
if taken := f.Taken(t.f.Name, fwd); len(taken) > 0 {
e.Warn(msg.PortsTaken(backend.CountPorts(taken), backend.FormatPortRanges(taken), t.f.Name))
un := f.Unforwarded(t.f.Name, fwd)
if len(un.InUse) > 0 {
e.Warn(msg.PortsTaken(backend.CountPorts(un.InUse), backend.FormatPortRanges(un.InUse), t.f.Name))
}
if len(un.Limit) > 0 {
e.Warn(msg.PortsLimit(backend.CountPorts(un.Limit), strconv.Itoa(vmssh.MaxForwards), backend.FormatPortRanges(un.Limit), t.f.Name))
}
if len(un.Refused) > 0 {
e.Warn(msg.PortsRefused(backend.CountPorts(un.Refused), backend.FormatPortRanges(un.Refused), t.f.Name))
}
// Another VM's state unreadable for now: the list alone.
held, _ := f.Held(t.f.Name, fwd)
+105 -39
View File
@@ -65,11 +65,14 @@ import (
// Limits on what the VM's report makes the forwarder do.
const (
minForwardPort = 1024 // privileged ports aren't forwarded unless listed
maxForwards = 256 // ports forwarded at once
maxListeners = 4096 // lines in one report
maxRelays = 256 // connections carried at once
)
// MaxForwards is the most ports a VM's forwarder forwards at once
// (ports_limit names it).
const MaxForwards = 256
// Forwarder forwards a running VM's ports to the host's loopback, as the
// VM reports them (Watch).
type Forwarder struct {
@@ -93,14 +96,14 @@ type Forwarder struct {
// it's 0.
Recheck time.Duration
// Note, when set, records the host ports it forwards and those it
// tried and couldn't take, after each change (Forwards' record, which
// other VMs' forwarders and devvm ports read).
Note func(now, failed []int)
// tried and couldn't take, by why, after each change (Forwards' record,
// which other VMs' forwarders and devvm ports read).
Note func(now []int, failed failedPorts)
// Watch connects to the VM and runs ports.sh there, returning its
// output and how to wait for it; it ends with ctx or the connection.
Watch func(ctx context.Context) (io.ReadCloser, func() error, error)
// Relay carries conn to host:port in the VM until either side ends,
// then closes conn.
// or ctx does, which its forward's close ends, then closes conn.
Relay func(ctx context.Context, conn net.Conn, host string, port int)
// Listen listens on a host loopback address (HOST:PORT).
Listen func(ctx context.Context, addr string) (net.Listener, error)
@@ -114,18 +117,46 @@ type Forwarder struct {
mu sync.Mutex
ports map[int]*forward
skipped map[int]bool // not forwarded: tried again only once the VM's listener goes and comes back
skipped map[int]failure // not forwarded, and why: tried again only once the VM's listener goes and comes back
relays chan struct{}
}
// failure is why the forwarder couldn't take a port.
type failure int
const (
failedInUse failure = iota + 1 // a program on the host has it (EADDRINUSE)
failedLimit // MaxForwards are forwarded already
failedRefused // the host refused it (EACCES, EPERM), such as below 1024 on Linux
)
// failureOf is why a listen on a port failed, with ok when that's one
// the port keeps: in use, or refused. Any other error (EMFILE, ENOBUFS,
// EADDRNOTAVAIL...) says nothing of the port, so it's tried again at the
// next report.
func failureOf(err error) (failure, bool) {
switch {
case errors.Is(err, syscall.EADDRINUSE):
return failedInUse, true
case errors.Is(err, syscall.EACCES), errors.Is(err, syscall.EPERM):
return failedRefused, true
}
return 0, false
}
// failedPorts is the ports the forwarder tried and couldn't take, by
// why, each sorted.
type failedPorts struct{ inUse, limit, refused []int }
// forward is a port being forwarded: its host listeners, and the address
// in the VM its connections go to.
type forward struct {
lns []net.Listener
host string
// conns is the connections it accepted that are open, which close
// ends too, and closed whether it went: both under the forwarder's mu.
conns map[net.Conn]bool
// conns is the connections it accepted that are open, each with what
// ends its relay's context, which close ends too, and closed whether
// it went: both under the forwarder's mu.
conns map[net.Conn]context.CancelFunc
closed bool
}
@@ -159,9 +190,9 @@ func (f *Forwarder) Run(ctx context.Context) error {
f.logf("%s stopped", f.VM)
}
}()
f.ports, f.skipped, f.relays = map[int]*forward{}, map[int]bool{}, make(chan struct{}, maxRelays)
f.ports, f.skipped, f.relays = map[int]*forward{}, map[int]failure{}, make(chan struct{}, maxRelays)
if f.Note != nil {
f.Note(nil, nil) // an older record of the VM's names nothing now
f.Note(nil, failedPorts{}) // an older record of the VM's names nothing now
}
defer f.closeAll()
go func() {
@@ -337,8 +368,11 @@ func (f *Forwarder) apply(ctx context.Context, want map[int]string) {
f.logf("port %d: no longer forwarded", port)
}
}
for port := range f.skipped {
if _, ok := want[port]; !ok {
// A port past the limit is tried again once the forwarder is below
// it; any other failure stays until the VM's listener goes.
below := len(f.ports) < MaxForwards
for port, why := range f.skipped {
if _, ok := want[port]; !ok || why == failedLimit && below {
delete(f.skipped, port)
}
}
@@ -356,27 +390,40 @@ func (f *Forwarder) apply(ctx context.Context, want map[int]string) {
delete(f.skipped, port)
continue
}
if f.skipped[port] {
if _, ok := f.skipped[port]; ok {
continue
}
f.skipped[port] = true
if len(f.ports) >= maxForwards {
f.logf("port %d: not forwarded: %d forwarded already", port, maxForwards)
continue
if f.try(ctx, port, host) {
changed = true
}
fw, err := f.open(ctx, port)
if err != nil {
f.logf("port %d: not forwarded: %v", port, err)
continue
}
fw.host = host
f.ports[port] = fw
delete(f.skipped, port)
changed = true
f.logf("port %d: forwarded", port)
}
}
// try forwards a port the VM listens on, or records why it can't
// (skipped): its limit of forwards reached, or the host's listen failing
// with an error that's the port's (failureOf). Any other error is logged
// alone, and the port is tried again at the next report. Its caller holds
// mu.
func (f *Forwarder) try(ctx context.Context, port int, host string) bool {
if len(f.ports) >= MaxForwards {
f.skipped[port] = failedLimit
f.logf("port %d: not forwarded: %d forwarded already", port, MaxForwards)
return false
}
fw, err := f.open(ctx, port)
if err != nil {
if why, ok := failureOf(err); ok {
f.skipped[port] = why
}
f.logf("port %d: not forwarded: %v", port, err)
return false
}
fw.host = host
f.ports[port] = fw
f.logf("port %d: forwarded", port)
return true
}
// open listens on the port on the host's loopback, IPv4 and IPv6 (a host
// without IPv6 gets IPv4 alone), and serves it.
func (f *Forwarder) open(ctx context.Context, port int) (*forward, error) {
@@ -413,16 +460,20 @@ func (f *Forwarder) serve(ctx context.Context, l net.Listener, port int, fw *for
_ = conn.Close() // too many at once
continue
}
// Each relay's own context, which the forward's close ends, so its
// ssh is killed even when the VM never ends its channel.
rctx, cancel := context.WithCancel(ctx)
f.mu.Lock()
host, closed := fw.host, fw.closed
if !closed {
if fw.conns == nil {
fw.conns = map[net.Conn]bool{}
fw.conns = map[net.Conn]context.CancelFunc{}
}
fw.conns[conn] = true
fw.conns[conn] = cancel
}
f.mu.Unlock()
if closed {
cancel()
_ = conn.Close() // accepted as the forward went
<-f.relays
continue
@@ -432,24 +483,27 @@ func (f *Forwarder) serve(ctx context.Context, l net.Listener, port int, fw *for
f.mu.Lock()
delete(fw.conns, conn)
f.mu.Unlock()
cancel()
<-f.relays
}()
f.Relay(ctx, conn, host, port)
f.Relay(rctx, conn, host, port)
}()
}
}
// close ends the forward: its listeners, and the connections they
// accepted that are open, so a client's keep-alive connection, such as a
// browser's, never reaches the VM once its port is given up. Its caller
// holds the forwarder's mu.
// accepted that are open, with their relays' contexts, so a client's
// keep-alive connection, such as a browser's, never reaches the VM once
// its port is given up, and a relay whose channel the VM never ends
// stops with it. Its caller holds the forwarder's mu.
func (fw *forward) close() {
fw.closed = true
for _, l := range fw.lns {
_ = l.Close()
}
for c := range fw.conns {
for c, cancel := range fw.conns {
_ = c.Close()
cancel()
}
clear(fw.conns)
}
@@ -467,12 +521,24 @@ func (f *Forwarder) closeAll() {
clear(f.skipped)
}
// note records what it forwards and the ports it couldn't take (Note).
// Its caller holds mu.
// note records what it forwards and the ports it couldn't take, by why
// (Note). Its caller holds mu.
func (f *Forwarder) note() {
if f.Note != nil {
f.Note(slices.Sorted(maps.Keys(f.ports)), slices.Sorted(maps.Keys(f.skipped)))
if f.Note == nil {
return
}
var failed failedPorts
for _, port := range slices.Sorted(maps.Keys(f.skipped)) {
switch f.skipped[port] {
case failedInUse:
failed.inUse = append(failed.inUse, port)
case failedLimit:
failed.limit = append(failed.limit, port)
case failedRefused:
failed.refused = append(failed.refused, port)
}
}
f.Note(slices.Sorted(maps.Keys(f.ports)), failed)
}
// release closes the forwards whose ports devvm reserves now, noting what
+153 -9
View File
@@ -284,7 +284,7 @@ func TestForwarderOnly(t *testing.T) {
Alive: func(context.Context) bool { return true },
Reserved: func() (map[int]bool, error) { return map[int]bool{reserved: true}, nil },
Watch: vm.watch, Relay: echo, Listen: platform.ListenLoopback,
ports: map[int]*forward{}, skipped: map[int]bool{},
ports: map[int]*forward{}, skipped: map[int]failure{},
}
if !f.wanted(80) || f.wanted(other) || !f.wanted(listed) {
t.Error("wanted: not the listed ports alone")
@@ -370,7 +370,7 @@ func TestForwarderReservedUnknown(t *testing.T) {
p := freePorts(t, 1)[0]
var log bytes.Buffer
f := &Forwarder{
VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]bool{},
VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]failure{},
Reserved: func() (map[int]bool, error) { return nil, errors.New("unreadable") },
Listen: platform.ListenLoopback,
}
@@ -389,7 +389,7 @@ func TestForwarderReservedLater(t *testing.T) {
reserved := map[int]bool{}
var rerr error
f := &Forwarder{
VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]bool{},
VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]failure{},
Reserved: func() (map[int]bool, error) { return reserved, rerr },
Listen: platform.ListenLoopback,
}
@@ -436,7 +436,7 @@ func TestForwarderGivesUpSilently(t *testing.T) {
defer mu.Unlock()
return maps.Clone(reserved), nil
},
Note: func(ports, _ []int) {
Note: func(ports []int, _ failedPorts) {
mu.Lock()
defer mu.Unlock()
notes = append(notes, ports)
@@ -470,7 +470,7 @@ func TestForwarderClosesConnections(t *testing.T) {
var reserved map[int]bool
accepted := make(chan struct{}, 1)
f := &Forwarder{
VM: "devvm-f", Log: io.Discard, ports: map[int]*forward{}, skipped: map[int]bool{}, relays: make(chan struct{}, maxRelays),
VM: "devvm-f", Log: io.Discard, ports: map[int]*forward{}, skipped: map[int]failure{}, relays: make(chan struct{}, maxRelays),
Reserved: func() (map[int]bool, error) { return reserved, nil },
Relay: func(_ context.Context, conn net.Conn, _ string, _ int) {
accepted <- struct{}{}
@@ -496,6 +496,150 @@ func TestForwarderClosesConnections(t *testing.T) {
}
}
// The forwarder records why it couldn't take each port: a program's
// (EADDRINUSE), past its limit of forwards, or refused by the host
// (EACCES, EPERM), such as below 1024 on Linux. A port in use or refused
// is tried again only once the VM's listener goes and comes back; one
// past the limit at the next report once the forwarder is below it. Any
// other error (EMFILE: out of descriptors for now) is logged alone, not
// recorded, and tried again at the next report.
func TestForwarderFailures(t *testing.T) {
const refused, denied, inUse, busy = 80, 81, 5000, 7000
limited := freePorts(t, 1)[0]
var notes []failedPorts
listens := map[int]int{}
f := &Forwarder{
VM: "devvm-f", Log: io.Discard, ports: map[int]*forward{}, skipped: map[int]failure{},
Only: []backend.PortRange{{From: 1, To: 65535}}, // 80 listed
Reserved: func() (map[int]bool, error) { return nil, nil },
Note: func(_ []int, failed failedPorts) { notes = append(notes, failed) },
Listen: func(ctx context.Context, addr string) (net.Listener, error) {
_, ps, _ := net.SplitHostPort(addr)
p, _ := strconv.Atoi(ps)
listens[p]++
bind := func(errno syscall.Errno) error {
return &net.OpError{Op: "listen", Net: "tcp", Err: os.NewSyscallError("bind", errno)}
}
switch p {
case refused:
return nil, bind(syscall.EACCES)
case denied:
return nil, bind(syscall.EPERM)
case inUse:
return nil, bind(syscall.EADDRINUSE)
case busy:
return nil, bind(syscall.EMFILE)
case limited:
return platform.ListenLoopback(ctx, addr)
}
return nil, fmt.Errorf("port %d: not the test's", p)
},
}
defer f.closeAll()
want := map[int]string{refused: "127.0.0.1", denied: "127.0.0.1", inUse: "127.0.0.1", busy: "127.0.0.1"}
f.apply(t.Context(), want)
failed := failedPorts{inUse: []int{inUse}, refused: []int{refused, denied}}
if got, w := notes, []failedPorts{failed}; !slices.EqualFunc(got, w, failedEqual) {
t.Fatalf("noted %+v, want %+v", got, w)
}
f.apply(t.Context(), want)
if listens[busy] != 2 || listens[refused] != 1 || listens[denied] != 1 || listens[inUse] != 1 {
t.Errorf("EMFILE not tried again at the next report, or another one was: listened %v", listens)
}
// At its limit: a new port isn't tried, and is recorded as past it.
delete(want, busy)
for i := range MaxForwards {
f.ports[30000+i] = &forward{}
want[30000+i] = "127.0.0.1"
}
want[limited] = "127.0.0.1"
f.apply(t.Context(), want)
failed.limit = []int{limited}
if got := notes[len(notes)-1]; !failedEqual(got, failed) {
t.Errorf("noted %+v, want %+v", got, failed)
}
f.apply(t.Context(), want)
if listens[limited] != 0 {
t.Errorf("a port past the limit tried: listened %v", listens)
}
// Below it again (a forward went): forwarded at the next report.
delete(want, 30000)
f.apply(t.Context(), want)
failed.limit = nil
if got := notes[len(notes)-1]; f.ports[limited] == nil || !failedEqual(got, failed) {
t.Errorf("past the limit, then below it: forwarded %v, noted %+v", f.ports[limited] != nil, got)
}
}
func failedEqual(a, b failedPorts) bool {
return slices.Equal(a.inUse, b.inUse) && slices.Equal(a.limit, b.limit) && slices.Equal(a.refused, b.refused)
}
// A relay whose far end never ends its channel (a VM whose sshd ignores
// EOF) still ends when its forward goes: its ssh is killed, and its slot
// is free again, so a VM can't keep the forwarder's relays by holding
// them open. The ssh here is a stand-in, on PATH, that never exits on its
// own.
func TestForwarderEndsStuckRelay(t *testing.T) {
p := freePorts(t, 1)[0]
bin := t.TempDir()
pidFile := filepath.Join(bin, "pid")
stub := "#!/bin/sh\necho $$ > " + pidFile + ".tmp && mv " + pidFile + ".tmp " + pidFile + "\nexec sleep 600\n"
if err := os.WriteFile(filepath.Join(bin, "ssh"), []byte(stub), 0o700); err != nil { //nolint:gosec // gosec G306: the test's own script, which it runs
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
var reserved map[int]bool
ended := make(chan struct{})
f := &Forwarder{
VM: "devvm-f", Log: io.Discard, ports: map[int]*forward{}, skipped: map[int]failure{}, relays: make(chan struct{}, maxRelays),
Reserved: func() (map[int]bool, error) { return reserved, nil },
Relay: func(ctx context.Context, conn net.Conn, _ string, _ int) {
defer close(ended)
pipeSSH(ctx, conn, nil)
},
Listen: platform.ListenLoopback,
}
defer f.closeAll()
f.apply(t.Context(), map[int]string{p: "127.0.0.1"})
d := net.Dialer{Timeout: time.Second}
c, err := d.DialContext(t.Context(), "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(p)))
if err != nil {
t.Fatal(err)
}
defer func() { _ = c.Close() }()
var pid int
for range 200 {
if b, err := os.ReadFile(pidFile); err == nil { //nolint:gosec // gosec G304: the test's own temp file
pid, _ = strconv.Atoi(strings.TrimSpace(string(b)))
break
}
time.Sleep(10 * time.Millisecond)
}
if pid <= 0 {
t.Fatal("the ssh stand-in never started")
}
reserved = map[int]bool{p: true}
f.release()
select {
case <-ended:
case <-time.After(5 * time.Second):
_ = daemon.Signal(pid, syscall.SIGKILL)
t.Fatal("the relay outlived its forward")
}
if daemon.Alive(pid) {
_ = daemon.Signal(pid, syscall.SIGKILL)
t.Error("its ssh still runs")
}
for range 100 {
if len(f.relays) == 0 {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Errorf("%d relay slots still taken", len(f.relays))
}
// A reserved port the VM listens on waits: another VM forwards it, and
// once that VM gives it up (it stops) it's forwarded at the next report,
// even after a try that found it taken. What it forwards is noted at each
@@ -506,10 +650,10 @@ func TestForwarderWaits(t *testing.T) {
var reserved map[int]bool
var notes []string // what it forwards, then what it couldn't take
f := &Forwarder{
VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]bool{},
VM: "devvm-f", Log: &log, ports: map[int]*forward{}, skipped: map[int]failure{},
Only: []backend.PortRange{{From: p, To: p}},
Reserved: func() (map[int]bool, error) { return reserved, nil },
Note: func(now, failed []int) { notes = append(notes, fmt.Sprint(now, failed)) },
Note: func(now []int, failed failedPorts) { notes = append(notes, fmt.Sprint(now, failed.inUse)) },
Listen: platform.ListenLoopback,
}
ps := fmt.Sprint([]int{p})
@@ -521,7 +665,7 @@ func TestForwarderWaits(t *testing.T) {
t.Fatal(err)
}
f.apply(t.Context(), want)
if f.ports[p] != nil || !f.skipped[p] || !slices.Equal(notes, []string{"[] " + ps}) {
if f.ports[p] != nil || f.skipped[p] != failedInUse || !slices.Equal(notes, []string{"[] " + ps}) {
t.Fatalf("a taken port: forwarded %v, skipped %v, noted %q", f.ports, f.skipped, notes)
}
// It's the other VM's: waited for, with no try, and no longer one it
@@ -529,7 +673,7 @@ func TestForwarderWaits(t *testing.T) {
reserved = map[int]bool{p: true}
f.apply(t.Context(), want)
f.apply(t.Context(), want)
if f.ports[p] != nil || f.skipped[p] || !slices.Equal(notes, []string{"[] " + ps, "[] []"}) {
if _, skipped := f.skipped[p]; f.ports[p] != nil || skipped || !slices.Equal(notes, []string{"[] " + ps, "[] []"}) {
t.Fatalf("a reserved port: forwarded %v, skipped %v, noted %q", f.ports, f.skipped, notes)
}
notes = nil
+50 -27
View File
@@ -210,32 +210,43 @@ func (f Forwards) Held(vm, forward string) (map[string][]backend.PortRange, erro
return heldBy(holders, want.Ranges), nil
}
// Taken returns the listed ports of the running VM, as its state lists
// them (forward), that its forwarder tried and couldn't take, as its
// record says, and no other VM forwards: a program's, which the forwarder
// leaves until the VM's server listens again, as devvm ports shows them.
// It reads the forwarder's own view and binds nothing, so it never takes
// a port the forwarder is opening. A VM whose forwarder doesn't run, or
// whose record its forwarder didn't write (an older devvm's forwarder, or
// a write that failed), has none known.
func (f Forwards) Taken(vm, forward string) []backend.PortRange {
// Unforwarded is a running VM's listed ports that its forwarder tried
// and couldn't take, by why, as devvm ports shows them.
type Unforwarded struct {
InUse []backend.PortRange // a program's on this machine (ports_taken)
Limit []backend.PortRange // past the limit of forwards (ports_limit)
Refused []backend.PortRange // refused by this machine otherwise, such as below 1024 on Linux (ports_refused)
}
// Unforwarded returns the listed ports of the running VM, as its state
// lists them (forward), that its forwarder tried and couldn't take, as its
// record says, by why, and no other VM forwards: each left until the VM's
// server listens again. It reads the forwarder's own view and binds
// nothing, so it never takes a port the forwarder is opening. A VM whose
// forwarder doesn't run, or whose record its forwarder didn't write (an
// older devvm's forwarder, or a write that failed), or whose record
// doesn't say why (an older devvm's), has none known.
func (f Forwards) Unforwarded(vm, forward string) Unforwarded {
want, err := ports.Forwarding(forward)
if err != nil || want.All {
return nil
return Unforwarded{}
}
rec, ok := f.recorded(vm)
if !ok {
return nil
return Unforwarded{}
}
holders, err := ports.Holders(f.Dirs, vm, f.live)
if err != nil {
return nil
return Unforwarded{}
}
_, taken := splitPorts(want.Ranges, func(p int) bool {
_, held := holders[p]
return !held && slices.Contains(rec.failed, p)
})
return taken
of := func(failed []int) []backend.PortRange {
_, out := splitPorts(want.Ranges, func(p int) bool {
_, held := holders[p]
return !held && slices.Contains(failed, p)
})
return out
}
return Unforwarded{InUse: of(rec.failed.inUse), Limit: of(rec.failed.limit), Refused: of(rec.failed.refused)}
}
// Reserved returns the host ports the VM's forwarder never takes
@@ -261,8 +272,18 @@ func (f Forwards) live(vm string) ([]int, bool) {
}
// forwarderRecord is what a VM's running forwarder records (record): the
// ports it forwards now, and those it tried and couldn't take.
type forwarderRecord struct{ now, failed []int }
// ports it forwards now, and those it tried and couldn't take, by why.
type forwarderRecord struct {
now []int
failed failedPorts
}
// recordLines is how many lines a record has: its pid, the ports
// forwarded, and those it couldn't take because they're in use, past its
// limit, and refused. An older devvm's has three, its last any port it
// couldn't take, whatever the reason: read as none, so no port is
// wrongly said to be in use.
const recordLines = 5
// recorded returns the VM's forwarder's record, with ok when its forwarder
// runs and that process wrote it.
@@ -280,8 +301,8 @@ func (f Forwards) recorded(vm string) (forwarderRecord, bool) {
return forwarderRecord{}, false
}
rec := forwarderRecord{now: parsePorts(lines[1])}
if len(lines) > 2 {
rec.failed = parsePorts(lines[2])
if len(lines) >= recordLines {
rec.failed = failedPorts{inUse: parsePorts(lines[2]), limit: parsePorts(lines[3]), refused: parsePorts(lines[4])}
}
return rec, true
}
@@ -300,17 +321,19 @@ func parsePorts(s string) []int {
// record records the host ports the VM's forwarder, process pid,
// forwards now, which other VMs' forwarders read (live), and those it
// tried and couldn't take (Taken): its pid, then each list of ports,
// comma-separated, on a line of its own, written whole.
func (f Forwards) record(vm string, pid int, now, failed []int) error {
join := func(ps []int) string {
// tried and couldn't take, by why (Unforwarded): its pid, then each list
// of ports, comma-separated, on a line of its own (recordLines), written
// whole. An older devvm reads its third line, those in use, alone.
func (f Forwards) record(vm string, pid int, now []int, failed failedPorts) error {
lines := []string{strconv.Itoa(pid)}
for _, ps := range [][]int{now, failed.inUse, failed.limit, failed.refused} {
es := make([]string, len(ps))
for i, n := range ps {
es[i] = strconv.Itoa(n)
}
return strings.Join(es, ",")
lines = append(lines, strings.Join(es, ","))
}
return state.WriteFile(f.Dirs.VM(vm).Forwarder(".forwarded"), []byte(strconv.Itoa(pid)+"\n"+join(now)+"\n"+join(failed)+"\n"))
return state.WriteFile(f.Dirs.VM(vm).Forwarder(".forwarded"), []byte(strings.Join(lines, "\n")+"\n"))
}
// splitPorts splits ranges into the ports inUse says are free and those it
+56 -29
View File
@@ -95,7 +95,7 @@ func TestForwardsStart(t *testing.T) {
forward("")
// Its old forwarder's record goes with it: a pid used again never
// makes it the new one's.
if err := f.record(vm, 1, []int{5173}, nil); err != nil {
if err := f.record(vm, 1, []int{5173}, failedPorts{}); err != nil {
t.Fatal(err)
}
f.Start(ctx, b, st)
@@ -221,7 +221,7 @@ func TestForwardsHeld(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if err := f.record(vm, pid, now, nil); err != nil {
if err := f.record(vm, pid, now, failedPorts{}); err != nil {
t.Fatal(err)
}
}
@@ -229,7 +229,7 @@ func TestForwardsHeld(t *testing.T) {
run(every, 3000)
// A record its process didn't write names none; a VM that's stopped,
// or crashed, its forwarder gone, holds none.
if err := f.record(gone, 1, []int{5173}, nil); err != nil {
if err := f.record(gone, 1, []int{5173}, failedPorts{}); err != nil {
t.Fatal(err)
}
if now, ok := f.live(gone); ok || now != nil {
@@ -239,13 +239,13 @@ func TestForwardsHeld(t *testing.T) {
t.Errorf("a running VM: %v, %v", now, ok)
}
pid, _ := f.proc(every).PID()
if err := f.record(every, pid+1, []int{3000}, nil); err != nil {
if err := f.record(every, pid+1, []int{3000}, failedPorts{}); err != nil {
t.Fatal(err)
}
if now, ok := f.live(every); !ok || now != nil {
t.Errorf("another process's record: %v, %v", now, ok)
}
if err := f.record(every, pid, []int{3000}, nil); err != nil {
if err := f.record(every, pid, []int{3000}, failedPorts{}); err != nil {
t.Fatal(err)
}
@@ -257,7 +257,7 @@ func TestForwardsHeld(t *testing.T) {
if now, ok := f.live(every); !ok || now != nil {
t.Errorf("no record: %v, %v", now, ok)
}
if err := f.record(every, pid, []int{3000}, nil); err != nil {
if err := f.record(every, pid, []int{3000}, failedPorts{}); err != nil {
t.Fatal(err)
}
@@ -311,37 +311,64 @@ func TestForwardsHeld(t *testing.T) {
}
// a's own forwarder runs: its listed ports that it tried and couldn't
// take, as its record says (its third line), and no VM holds, are a
// program's (devvm ports says so). Nothing is bound to find out, so a
// port it may be opening right then (8001, in use as it opens it)
// isn't one.
// take, as its record says, by why, and no VM holds, are a program's
// (in use), past its limit, or refused by this machine (devvm ports
// says which). Nothing is bound to find out, so a port it may be
// opening right then (8001, in use as it opens it) is what the record
// says.
const list = "80,5173,8000-8001,3000,9000"
run(a, 8000)
pidA, _ := f.proc(a).PID()
if err := f.record(a, pidA, []int{8000}, failedPorts{inUse: []int{5173, 9000}, limit: []int{8001}, refused: []int{80}}); err != nil {
t.Fatal(err)
}
rec := f.Dirs.VM(a).Forwarder(".forwarded")
if err := state.WriteFile(rec, []byte(strconv.Itoa(pidA)+"\n8000\n9000,5173\n")); err != nil {
if got, want := readFile(t, rec), strconv.Itoa(pidA)+"\n8000\n5173,9000\n8001\n80\n"; got != want {
t.Errorf("record %q, want %q", got, want)
}
f.InUse = func(_ context.Context, p int) bool { return p == 8001 || p == 9000 || p == 80 }
un := f.Unforwarded(a, list)
if !slices.Equal(un.InUse, []backend.PortRange{r(9000, 9000)}) || !slices.Equal(un.Limit, []backend.PortRange{r(8001, 8001)}) ||
!slices.Equal(un.Refused, []backend.PortRange{r(80, 80)}) {
t.Errorf("Unforwarded = %+v", un)
}
unforwardedUnknown(t, *f, a, list, pidA)
if un := f.Unforwarded(gone, "7000"); un.InUse != nil {
t.Errorf("Unforwarded of a stopped VM = %+v", un)
}
}
// unforwardedUnknown checks that the running VM's forwarder, process pid,
// has no port it couldn't take known without its record, with one
// another process wrote (an older devvm's forwarder, or a write that
// failed), or with an older devvm's record, whose third line is every
// port it couldn't take, whatever the reason: none is wrongly said to be
// in use. An older devvm's record still says what it forwards.
func unforwardedUnknown(t *testing.T, f Forwards, vm, list string, pid int) {
t.Helper()
rec := f.Dirs.VM(vm).Forwarder(".forwarded")
for name, data := range map[string]string{
"another process's": strconv.Itoa(pid+1) + "\n8000\n9000\n\n80\n",
"an older devvm's": strconv.Itoa(pid) + "\n8000\n9000,80\n",
} {
if err := state.WriteFile(rec, []byte(data)); err != nil {
t.Fatal(err)
}
if un := f.Unforwarded(vm, list); un.InUse != nil || un.Limit != nil || un.Refused != nil {
t.Errorf("Unforwarded with %s record = %+v", name, un)
}
}
if err := state.WriteFile(rec, []byte(strconv.Itoa(pid)+"\n8000\n9000,80\n")); err != nil {
t.Fatal(err)
}
f.InUse = func(_ context.Context, p int) bool { return p == 8001 || p == 9000 }
if taken := f.Taken(a, "5173,8000-8001,3000,9000"); !slices.Equal(taken, []backend.PortRange{r(9000, 9000)}) {
t.Errorf("Taken = %v", taken)
}
// Without its record, or with one another process wrote (an older
// devvm's forwarder, or a write that failed), what it couldn't take
// is unknown: none.
if err := state.WriteFile(rec, []byte(strconv.Itoa(pidA+1)+"\n8000\n9000\n")); err != nil {
t.Fatal(err)
}
if taken := f.Taken(a, "5173,8000-8001,3000,9000"); taken != nil {
t.Errorf("Taken with another process's record = %v", taken)
if now, ok := f.live(vm); !ok || !slices.Equal(now, []int{8000}) {
t.Errorf("an older devvm's record forwards %v, %v", now, ok)
}
if err := os.Remove(rec); err != nil {
t.Fatal(err)
}
if taken := f.Taken(a, "5173,8000-8001,3000,9000"); taken != nil {
t.Errorf("Taken without a record = %v", taken)
}
if taken := f.Taken(gone, "7000"); taken != nil {
t.Errorf("Taken of a stopped VM = %v", taken)
if un := f.Unforwarded(vm, list); un.InUse != nil || un.Limit != nil || un.Refused != nil {
t.Errorf("Unforwarded without a record = %+v", un)
}
}
@@ -355,7 +382,7 @@ func TestForwardsRecordFails(t *testing.T) {
if err := os.WriteFile(f.Dirs.VM(vm).Run(), nil, 0o600); err != nil {
t.Fatal(err)
}
if err := f.record(vm, 1, []int{5173}, nil); err == nil {
if err := f.record(vm, 1, []int{5173}, failedPorts{}); err == nil {
t.Error("a record where its folder is a file")
}
}
+1 -1
View File
@@ -40,7 +40,7 @@ func Main(ctx context.Context, args []string, script []byte, d paths.Dirs, log i
if err != nil {
return err
}
f.Note = func(now, failed []int) {
f.Note = func(now []int, failed failedPorts) {
if err := fw.record(fl.VM, os.Getpid(), now, failed); err != nil {
f.logf("its ports not recorded: %v", err)
}
+10
View File
@@ -1365,6 +1365,16 @@ description = "ports is a list of ports and ranges, like 5173,8000-8010; count i
one = "{{.vm}} doesn't forward port {{.ports}} for now because it's in use on this machine."
other = "{{.vm}} doesn't forward ports {{.ports}} for now because they're in use on this machine."
[ports_limit]
description = "ports is a list of ports and ranges, like 5173,8000-8010; count is how many ports; limit is the most ports a VM forwards at once"
one = "{{.vm}} doesn't forward port {{.ports}} for now because it already forwards {{.limit}} ports, the most it can at once."
other = "{{.vm}} doesn't forward ports {{.ports}} for now because it already forwards {{.limit}} ports, the most it can at once."
[ports_refused]
description = "ports is a list of ports and ranges, like 5173,8000-8010; count is how many ports"
one = "{{.vm}} doesn't forward port {{.ports}} because this machine doesn't let devvm use it, as with a port below 1024 on Linux."
other = "{{.vm}} doesn't forward ports {{.ports}} because this machine doesn't let devvm use them, as with ports below 1024 on Linux."
[ports_held]
description = "ports is a list of ports and ranges, like 5173,8000-8010; count is how many ports; other is the VM that forwards them now"
one = "{{.vm}} forwards port {{.ports}} once {{.other}} stops forwarding it."
+1 -1
View File
@@ -48,5 +48,5 @@ internal/upgrade 93.2
internal/upgrade/upgradetest 97.4
internal/vm 88.4
internal/vmname 100.0
internal/vmssh 90.8
internal/vmssh 91.2
packaging 71.4
+12
View File
@@ -144,6 +144,18 @@ stdout '^==> ports_forwarding ports='$P','$TAKEN','$Q' vm=devvm-web-[0-9a-f]{14}
stderr '^devvm: ports_taken count=1 ports='$TAKEN' vm=devvm-web-[0-9a-f]{14}$'
exec sh -c 'ps -axww -o command= | grep -- "[_]ports -vm $WEB "'
stdout ' -only '$P','$Q'$'
# devvm ports says why the forwarder couldn't take each listed port, as
# its record says: in use, past its limit of forwards, or refused by this
# machine, such as a port below 1024 on Linux. An older devvm's record,
# which doesn't say why, warns of none.
exec sh -c 'printf "%s\n\n%s\n%s\n%s\n" "$(head -n1 "$WEB_dir/run/ports.pid")" '$TAKEN' '$Q' '$P' > "$WEB_dir/run/ports.forwarded"'
exec devvm ports
stderr '^devvm: ports_taken count=1 ports='$TAKEN' vm=devvm-web-[0-9a-f]{14}$'
stderr '^devvm: ports_limit count=1 limit=256 ports='$Q' vm=devvm-web-[0-9a-f]{14}$'
stderr '^devvm: ports_refused count=1 ports='$P' vm=devvm-web-[0-9a-f]{14}$'
exec sh -c 'printf "%s\n\n%s\n" "$(head -n1 "$WEB_dir/run/ports.pid")" '$P','$Q' > "$WEB_dir/run/ports.forwarded"'
exec devvm ports
! stderr 'ports_(taken|limit|refused)'
# Stopped, its forwarder stops too.
exec devvm stop
exec sh -c 'for i in 1 2 3 4 5 6 7 8 9 10; do ps -axww -o command= | grep -q -- "[_]ports -vm $WEB " || exit 0; sleep 0.5; done; exit 1'