Compare commits
86 commits
main
...
rework/sta
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1bdff32a84 | ||
|
|
55b24dabc6 | ||
|
|
066d3494c2 | ||
|
|
11d9fb2141 | ||
|
|
b5bad66e36 | ||
|
|
280f3880ef | ||
|
|
95406c3d2d | ||
|
|
ebe3b56348 | ||
|
|
8c4b70370e | ||
|
|
0aace09917 | ||
|
|
40b8722d58 | ||
|
|
ec3eeef436 | ||
|
|
98aaa09a2b | ||
|
|
0059d26b3b | ||
|
|
166116e57a | ||
|
|
bb7f98016b | ||
|
|
6c13b19ad1 | ||
|
|
a124b7164c | ||
|
|
5d36b76bbe | ||
|
|
9f29935356 | ||
|
|
030dccb37b | ||
|
|
2e3c5959b6 | ||
|
|
526ba9270f | ||
|
|
2cfd41160f | ||
|
|
b8cf3aefaa | ||
|
|
7f14fcbe33 | ||
|
|
edf196a149 | ||
|
|
2b1b9b0e95 | ||
|
|
3e219f8fcb | ||
|
|
aa6be396c7 | ||
|
|
af453aa705 | ||
|
|
f08467d63b | ||
|
|
9c898e862b | ||
|
|
b3f9452a1d | ||
|
|
058616de38 | ||
|
|
4bb60d074f | ||
|
|
481a4af693 | ||
|
|
88c67435ed | ||
|
|
2dd42d0e03 | ||
|
|
0ace9c454a | ||
|
|
86c110f0b1 | ||
|
|
130b7943b4 | ||
|
|
38e05c695f | ||
|
|
ef735fb37c | ||
|
|
c3606d5873 | ||
|
|
846ee4d2bc | ||
|
|
76ae6c3a87 | ||
|
|
2cbc0c3d70 | ||
|
|
e5c6b279f6 | ||
|
|
538418d553 | ||
|
|
250f6a0250 | ||
|
|
c328fff867 | ||
|
|
4232020b4a | ||
|
|
0f9314c12a | ||
|
|
d426752b6e | ||
|
|
4ed81ef635 | ||
|
|
351970078f | ||
|
|
28fd86b8d5 | ||
|
|
ecd99fcffc | ||
|
|
4bd84dc8d2 | ||
|
|
94002e286f | ||
|
|
1c57f92c42 | ||
|
|
2653df7a03 | ||
|
|
39e8264528 | ||
|
|
8584a638f1 | ||
|
|
9d5b6bf0c4 | ||
|
|
5132daa292 | ||
|
|
c3de5a06ef | ||
|
|
2db51e9385 | ||
|
|
945ae80c73 | ||
|
|
0a98a75212 | ||
|
|
dc3d1b77fe | ||
|
|
fbaffb4354 | ||
|
|
2ba00b0ad0 | ||
|
|
6696fea67a | ||
|
|
f57565989c | ||
|
|
8d6fe48536 | ||
|
|
2f3491c1db | ||
|
|
511375492a | ||
|
|
829b1237b2 | ||
|
|
1f6f400276 | ||
|
|
ffcc8f5806 | ||
|
|
05da3c0d30 | ||
|
|
407d758fa3 | ||
|
|
baa5f44ed8 | ||
|
|
e601f14db5 |
286 changed files with 58514 additions and 541 deletions
21
.github/workflows/ci.yml
vendored
21
.github/workflows/ci.yml
vendored
|
|
@ -4,7 +4,9 @@ on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
- "rework/**"
|
||||||
pull_request:
|
pull_request:
|
||||||
|
workflow_call:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
|
|
@ -19,14 +21,17 @@ jobs:
|
||||||
go-version-file: go.mod
|
go-version-file: go.mod
|
||||||
cache: true
|
cache: true
|
||||||
|
|
||||||
- name: Vendor Go modules
|
- name: gofmt
|
||||||
run: go mod vendor
|
run: make fmt-check
|
||||||
|
|
||||||
|
- name: go vet
|
||||||
|
run: make vet
|
||||||
|
|
||||||
|
- name: vendor is up to date
|
||||||
|
run: make vendor-check
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: GOFLAGS=-mod=vendor go build ./...
|
run: make build
|
||||||
|
|
||||||
- name: Vet
|
- name: Test (race)
|
||||||
run: GOFLAGS=-mod=vendor go vet ./...
|
run: make race
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: GOFLAGS=-mod=vendor go test ./...
|
|
||||||
|
|
|
||||||
14
.github/workflows/release.yml
vendored
14
.github/workflows/release.yml
vendored
|
|
@ -13,19 +13,7 @@ env:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
uses: ./.github/workflows/ci.yml
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version-file: go.mod
|
|
||||||
cache: true
|
|
||||||
|
|
||||||
- name: Run tests
|
|
||||||
run: GOFLAGS=-mod=vendor go test ./...
|
|
||||||
|
|
||||||
release:
|
release:
|
||||||
needs: test
|
needs: test
|
||||||
|
|
|
||||||
11
.gitignore
vendored
11
.gitignore
vendored
|
|
@ -1,2 +1,11 @@
|
||||||
target/
|
target/
|
||||||
vcom
|
/vcom
|
||||||
|
|
||||||
|
# release artifacts
|
||||||
|
*.tar.gz
|
||||||
|
*.pkg.tar.zst
|
||||||
|
*.deb
|
||||||
|
*.rpm
|
||||||
|
|
||||||
|
# local agent worktrees
|
||||||
|
.claude/worktrees/
|
||||||
|
|
|
||||||
80
CHANGELOG.md
Normal file
80
CHANGELOG.md
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
## v0.2.8 — stability hotfixes
|
||||||
|
|
||||||
|
Data-loss and crash fixes for v0.2.7 while the larger rework is in progress.
|
||||||
|
|
||||||
|
### Data loss
|
||||||
|
- **Archiving no longer destroys the source.** Archiving `data.tar` as tar (or `report.zip` as zip) into the same
|
||||||
|
directory used to truncate the source; archiving a directory into a pane inside it made the archive include
|
||||||
|
itself. Both are now refused. Archives are written to a temporary file and renamed into place only on success,
|
||||||
|
so a failed or cancelled run leaves no partial file and keeps an existing archive intact; replacing an existing
|
||||||
|
archive asks first. A replaced archive keeps its permissions (a private `0600` archive no longer becomes
|
||||||
|
world-readable), and archive names close to the file-name length limit work again.
|
||||||
|
- **Deleting a remote symlink to a directory no longer wipes the target directory.** The link itself is removed.
|
||||||
|
- **SSH panes no longer act on local files.** Rename, Enter (edit / run / open / enter archive), archive and unpack
|
||||||
|
in an SSH pane used to operate on the *local* file with the same path (e.g. running a local
|
||||||
|
`/usr/local/bin/deploy.sh`). They are now refused with a message until remote support lands.
|
||||||
|
- **No more writes into an archive pane or the SSH host list.** Copy/move/unpack/archive into a pane showing an
|
||||||
|
archive used to put files into a temporary directory that is deleted when the archive is closed; with the
|
||||||
|
`ssh://` host list as target, files went to `./ssh:/…` in the process directory. Both are now refused.
|
||||||
|
- **Delete moves to the trash by default.** Permanent deletion is chosen explicitly with `D`/`d` in the dialog.
|
||||||
|
`behavior.confirm_delete = false` now works and skips the question only for the trash. If an item cannot be moved
|
||||||
|
to the trash (e.g. it is on another filesystem than the home trash, or the trash is broken), the other items are
|
||||||
|
still trashed and vcom asks whether to delete only the refused ones permanently; nothing is deleted without that
|
||||||
|
confirmation.
|
||||||
|
- **Mirror (`p`) is refused inside an archive.** It used to give the other pane the archive's temporary directory as
|
||||||
|
a normal writable directory; changes there were lost when the archive was closed. Mirroring *into* a pane that is
|
||||||
|
inside an archive now leaves the archive properly (it used to keep treating the real directory as a read-only
|
||||||
|
archive).
|
||||||
|
|
||||||
|
### SSH
|
||||||
|
- **One unsupported line in `~/.ssh/known_hosts` no longer breaks every connection.** Lines with key types vcom
|
||||||
|
cannot parse (e.g. OpenSSH 10 `ssh-mldsa44-ed25519`) are skipped with a warning in the log. A host recorded only
|
||||||
|
with such a key is refused rather than silently trusted with a different key.
|
||||||
|
- Host key types already recorded for a host are preferred in the handshake (like OpenSSH), so a server known only
|
||||||
|
by its ed25519 key is no longer reported as "REMOTE HOST IDENTIFICATION HAS CHANGED".
|
||||||
|
|
||||||
|
### Crashes and races
|
||||||
|
- Caret mode (`i` in the info pane) no longer panics without colors (`NO_COLOR`, dumb terminals).
|
||||||
|
- Closing an SSH connection while it is in use (background transfer, mirrored pane, preview) no longer races or
|
||||||
|
panics. Mirrored panes and background jobs share a reference-counted connection: leaving a host in one pane no
|
||||||
|
longer disconnects the other pane or a running transfer.
|
||||||
|
|
||||||
|
### Usability
|
||||||
|
- Status and error messages are shown in a line above the footer (they were never displayed before).
|
||||||
|
- Cyrillic (and other non-Latin) text can be typed in mkdir, rename, the filter and the SSH form; Russian-layout
|
||||||
|
keys still work as commands in the browser.
|
||||||
|
- `PgDn` works.
|
||||||
|
- `q` closes the info pane, the filter or the selection first, and quits only from the plain browser; `q` no longer
|
||||||
|
closes the SSH add-host form while typing.
|
||||||
|
- `n` cancels yes/no dialogs, as their hints say.
|
||||||
|
- Creating a directory that already exists reports an error instead of silent success, in local and SSH panes.
|
||||||
|
- `j`, `k` and other letters can be typed in the filter (they used to move the cursor); arrows still navigate.
|
||||||
|
- `?` can be typed in the SSH add-host form (e.g. in passwords); `F1` opens the form's help.
|
||||||
|
|
||||||
|
### Trash
|
||||||
|
- Follows the freedesktop trash spec: items on another filesystem go to that filesystem's `$topdir/.Trash-$uid`
|
||||||
|
instead of failing; `.trashinfo` `Path=` is percent-encoded (names with spaces/Cyrillic restore correctly in other
|
||||||
|
tools); `XDG_DATA_HOME` is honoured; name collisions (including broken symlinks already in the trash) never
|
||||||
|
overwrite an existing trashed item.
|
||||||
|
|
||||||
|
### Config, session and logs
|
||||||
|
- Choosing a theme changes only the `theme = ...` line; comments and other keys in `vcom.toml` are preserved. This
|
||||||
|
also works when the section is written as `ui.theme = ...` or `ui = { theme = ... }`. A read-only (`chmod a-w`)
|
||||||
|
config is not changed (as in v0.2.7). With `-config` / `$VCOM_CONFIG` naming a file that does not exist yet, the
|
||||||
|
theme is saved to that file. If saving the theme fails, the error stays visible in the status line.
|
||||||
|
- A broken config no longer prevents startup: vcom starts with defaults and shows the error (in red) in the status
|
||||||
|
line.
|
||||||
|
- `./vcom.toml` in the current directory is no longer picked up implicitly.
|
||||||
|
- Config and session are written atomically. The session moved to `$XDG_STATE_HOME/vcom/session.toml` (migrated
|
||||||
|
once from the old location; if the state directory is not writable, the old session is still restored and the
|
||||||
|
error is shown) and is also saved on SIGTERM/SIGHUP.
|
||||||
|
- A single rotating log at `$XDG_STATE_HOME/vcom/vcom.log` replaces a new file in `/tmp/vcom-logs` per run;
|
||||||
|
secrets are never logged.
|
||||||
|
|
||||||
|
### Development
|
||||||
|
- In-process SSH/SFTP test server with a fault-injecting proxy (`internal/testutil/sshtest`), tree helpers
|
||||||
|
(`fstree`), a Bubble Tea test driver (`teadriver`) and behavioural smoke tests for the UI.
|
||||||
|
- CI: `make ci` runs gofmt, vet, a vendor consistency check, build and race-enabled tests; releases run the same
|
||||||
|
workflow.
|
||||||
47
Makefile
Normal file
47
Makefile
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
# Developer and CI entry points. CI (.github/workflows/*.yml) calls these
|
||||||
|
# targets so local runs and CI stay identical.
|
||||||
|
|
||||||
|
GO ?= go
|
||||||
|
GOFLAGS ?= -mod=vendor
|
||||||
|
export GOFLAGS
|
||||||
|
|
||||||
|
# Go sources we own (vendor/ is third-party and not reformatted).
|
||||||
|
GOFILES = $(shell git ls-files '*.go' | grep -v '^vendor/')
|
||||||
|
|
||||||
|
# Targets mutate vendor/ (vendor-check) and then build from it: never run them
|
||||||
|
# concurrently, even under `make -j`.
|
||||||
|
.NOTPARALLEL:
|
||||||
|
|
||||||
|
.PHONY: all build test race lint fmt-check vet vendor-check ci fmt
|
||||||
|
|
||||||
|
all: build
|
||||||
|
|
||||||
|
build:
|
||||||
|
$(GO) build ./...
|
||||||
|
|
||||||
|
test:
|
||||||
|
$(GO) test -count=1 ./...
|
||||||
|
|
||||||
|
race:
|
||||||
|
$(GO) test -race -count=1 ./...
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
gofmt -w $(GOFILES)
|
||||||
|
|
||||||
|
fmt-check:
|
||||||
|
@out="$$(gofmt -l $(GOFILES) $$(git ls-files --others --exclude-standard '*.go' | grep -v '^vendor/'))"; \
|
||||||
|
if [ -n "$$out" ]; then echo "gofmt needed for:"; echo "$$out"; exit 1; fi
|
||||||
|
|
||||||
|
vet:
|
||||||
|
$(GO) vet ./...
|
||||||
|
|
||||||
|
# go mod vendor must be a no-op: go.mod, go.sum and vendor/ are committed.
|
||||||
|
vendor-check:
|
||||||
|
GOFLAGS= $(GO) mod vendor
|
||||||
|
git diff --exit-code -- vendor go.mod go.sum
|
||||||
|
@untracked="$$(git ls-files --others --exclude-standard vendor)"; \
|
||||||
|
if [ -n "$$untracked" ]; then echo "untracked files in vendor/:"; echo "$$untracked"; exit 1; fi
|
||||||
|
|
||||||
|
lint: fmt-check vet vendor-check
|
||||||
|
|
||||||
|
ci: lint build race
|
||||||
2
PKGBUILD
2
PKGBUILD
|
|
@ -1,5 +1,5 @@
|
||||||
pkgname=vcom
|
pkgname=vcom
|
||||||
pkgver=0.2.7
|
pkgver=0.2.8
|
||||||
pkgrel=1
|
pkgrel=1
|
||||||
pkgdesc="Terminal file manager inspired by Midnight Commander"
|
pkgdesc="Terminal file manager inspired by Midnight Commander"
|
||||||
arch=("x86_64" "aarch64")
|
arch=("x86_64" "aarch64")
|
||||||
|
|
|
||||||
36
README.md
36
README.md
|
|
@ -44,13 +44,13 @@ go build -o vcom ./cmd/vcom
|
||||||
Run directly from the flake:
|
Run directly from the flake:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
nix run github:vrubelroman/vcom?ref=v0.2.7
|
nix run github:vrubelroman/vcom?ref=v0.2.8
|
||||||
```
|
```
|
||||||
|
|
||||||
Install into user profile:
|
Install into user profile:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
nix profile add github:vrubelroman/vcom?ref=v0.2.7
|
nix profile add github:vrubelroman/vcom?ref=v0.2.8
|
||||||
```
|
```
|
||||||
|
|
||||||
The Nix package wraps `vcom` with `ueberzugpp` in `PATH`, so image preview works in non-`kitty` terminals out of the box.
|
The Nix package wraps `vcom` with `ueberzugpp` in `PATH`, so image preview works in non-`kitty` terminals out of the box.
|
||||||
|
|
@ -60,8 +60,8 @@ The Nix package wraps `vcom` with `ueberzugpp` in `PATH`, so image preview works
|
||||||
Download and install the latest release:
|
Download and install the latest release:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.7/vcom_0.2.7_amd64.deb -o /tmp/vcom_0.2.7_amd64.deb
|
curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.8/vcom_0.2.8_amd64.deb -o /tmp/vcom_0.2.8_amd64.deb
|
||||||
sudo apt install /tmp/vcom_0.2.7_amd64.deb
|
sudo apt install /tmp/vcom_0.2.8_amd64.deb
|
||||||
```
|
```
|
||||||
|
|
||||||
The Debian package recommends `ueberzugpp` for image preview outside `kitty` (optional). To install it:
|
The Debian package recommends `ueberzugpp` for image preview outside `kitty` (optional). To install it:
|
||||||
|
|
@ -85,7 +85,7 @@ The Arch package depends on `ueberzugpp`, so non-`kitty` image preview is instal
|
||||||
Download and install the latest RPM:
|
Download and install the latest RPM:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.7/vcom-0.2.7-1.x86_64.rpm -o /tmp/vcom.rpm
|
curl -sL https://github.com/vrubelroman/vcom/releases/download/v0.2.8/vcom-0.2.8-1.x86_64.rpm -o /tmp/vcom.rpm
|
||||||
sudo dnf install /tmp/vcom.rpm
|
sudo dnf install /tmp/vcom.rpm
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
@ -176,12 +176,18 @@ Preview mode (`F9` / `i`) temporarily replaces the inactive pane and shows:
|
||||||
Optional config lookup order:
|
Optional config lookup order:
|
||||||
|
|
||||||
1. `-config /path/to/vcom.toml`
|
1. `-config /path/to/vcom.toml`
|
||||||
2. `./vcom.toml`
|
2. `$VCOM_CONFIG`
|
||||||
3. `./config/vcom.toml`
|
3. `$XDG_CONFIG_HOME/vcom/vcom.toml`
|
||||||
4. `$XDG_CONFIG_HOME/vcom/vcom.toml`
|
4. `~/.config/vcom/vcom.toml`
|
||||||
5. `~/.config/vcom/vcom.toml`
|
|
||||||
|
|
||||||
Reference config: [vcom.toml](/home/vrubel/projects/vcom/vcom.toml)
|
A `vcom.toml` in the current directory is no longer loaded. A broken config does not stop vcom: it starts with
|
||||||
|
defaults and shows the error. Unknown keys are reported as warnings. Choosing a theme edits only the `theme = ...`
|
||||||
|
line of the config; comments and other keys are kept.
|
||||||
|
|
||||||
|
Reference config: [vcom.toml](vcom.toml)
|
||||||
|
|
||||||
|
The session is kept in `$XDG_STATE_HOME/vcom/session.toml` (default `~/.local/state/vcom/`), next to the log
|
||||||
|
`vcom.log`. The log level is `warn` by default; use `--log-level=debug|info|warn|error`, `--debug` or `VCOM_LOG`.
|
||||||
|
|
||||||
Icon mode example:
|
Icon mode example:
|
||||||
|
|
||||||
|
|
@ -216,7 +222,7 @@ Built-in themes (press `t` to open theme selector or set `ui.theme` in config):
|
||||||
|
|
||||||
## Releases
|
## Releases
|
||||||
|
|
||||||
Pushing a tag like `v0.2.7` triggers GitHub Actions release workflow (`.github/workflows/release.yml`) which:
|
Pushing a tag like `v0.2.8` triggers GitHub Actions release workflow (`.github/workflows/release.yml`) which:
|
||||||
|
|
||||||
- runs tests
|
- runs tests
|
||||||
- vendors Go modules
|
- vendors Go modules
|
||||||
|
|
@ -227,10 +233,10 @@ Pushing a tag like `v0.2.7` triggers GitHub Actions release workflow (`.github/w
|
||||||
|
|
||||||
Release artifacts:
|
Release artifacts:
|
||||||
|
|
||||||
- `vcom-v0.2.7-x86_64-unknown-linux-gnu.tar.gz`
|
- `vcom-v0.2.8-x86_64-unknown-linux-gnu.tar.gz`
|
||||||
- `vcom_0.2.7_amd64.deb`
|
- `vcom_0.2.8_amd64.deb`
|
||||||
- `vcom-0.2.7-1.x86_64.rpm`
|
- `vcom-0.2.8-1.x86_64.rpm`
|
||||||
- `vcom-v0.2.7-checksums.txt`
|
- `vcom-v0.2.8-checksums.txt`
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
|
|
|
||||||
248
cmd/vcom/main.go
248
cmd/vcom/main.go
|
|
@ -1,57 +1,249 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
|
||||||
"vcom/internal/config"
|
"vcom/internal/config"
|
||||||
|
"vcom/internal/imgview"
|
||||||
|
"vcom/internal/jobs"
|
||||||
|
"vcom/internal/logx"
|
||||||
|
"vcom/internal/paths"
|
||||||
|
"vcom/internal/ssh/conn"
|
||||||
|
"vcom/internal/ssh/sshconfig"
|
||||||
|
"vcom/internal/tui"
|
||||||
"vcom/internal/ui"
|
"vcom/internal/ui"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() { os.Exit(run()) }
|
||||||
|
|
||||||
|
// run follows design §9.4: flags → log → config (not fatal) → run dir → UI;
|
||||||
|
// teardown (session, jobs, connections, temp files, run dir, log) happens
|
||||||
|
// after Program.Run in every case: normal quit, signal, or a panic Bubble
|
||||||
|
// Tea recovered from.
|
||||||
|
func run() int {
|
||||||
configPath := flag.String("config", "", "path to vcom TOML config")
|
configPath := flag.String("config", "", "path to vcom TOML config")
|
||||||
|
logLevel := flag.String("log-level", "", "log level: debug, info, warn, error (default warn, or $VCOM_LOG)")
|
||||||
|
debug := flag.Bool("debug", false, "shorthand for --log-level=debug")
|
||||||
|
uiFlag := flag.String("ui", "old", "user interface: old (default) or next (the new UI, work in progress)")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
cfg, resolvedPath, err := config.Load(*configPath)
|
logger, logErr := openLog(*debug, *logLevel)
|
||||||
if err != nil {
|
defer logger.Close()
|
||||||
fmt.Fprintf(os.Stderr, "config error: %v\n", err)
|
slog.SetDefault(logger.Logger)
|
||||||
os.Exit(1)
|
logx.RedirectStdLog(logger.Logger)
|
||||||
|
if logErr != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "vcom: log disabled: %v\n", logErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set up debug logging to a file in /tmp
|
// A broken config is not fatal: defaults + a message in the status line.
|
||||||
logDir := filepath.Join(os.TempDir(), "vcom-logs")
|
cfg, info, cfgErr := config.Load(*configPath)
|
||||||
if err := os.MkdirAll(logDir, 0755); err != nil {
|
// The theme is saved to resolvedPath: the file that was read, or — for
|
||||||
fmt.Fprintf(os.Stderr, "warning: cannot create log dir %s: %v\n", logDir, err)
|
// an explicit -config/$VCOM_CONFIG that does not exist yet — that path,
|
||||||
|
// so the next start finds it (QA-15). "" means the default XDG file.
|
||||||
|
resolvedPath := ""
|
||||||
|
explicit := *configPath != "" || os.Getenv("VCOM_CONFIG") != ""
|
||||||
|
if cfgErr == nil && (info.Found || explicit) {
|
||||||
|
resolvedPath = info.Path
|
||||||
}
|
}
|
||||||
logPath := filepath.Join(logDir, fmt.Sprintf("vcom-%s.log", time.Now().Format("2006-01-02_15-04-05")))
|
notice := ""
|
||||||
f, err := tea.LogToFile(logPath, "")
|
switch {
|
||||||
|
case cfgErr != nil:
|
||||||
|
notice = "Config error: " + cfgErr.Error() // "error" → shown in red (QA-19)
|
||||||
|
slog.Warn("config", "err", cfgErr)
|
||||||
|
case len(info.Warnings) == 1:
|
||||||
|
notice = "config: " + info.Warnings[0]
|
||||||
|
case len(info.Warnings) > 1:
|
||||||
|
notice = fmt.Sprintf("config: %s (+%d more warnings in the log)", info.Warnings[0], len(info.Warnings)-1)
|
||||||
|
}
|
||||||
|
for _, w := range info.Warnings {
|
||||||
|
slog.Warn("config", "warning", w)
|
||||||
|
}
|
||||||
|
slog.Info("starting", "config", resolvedPath, "log", logger.Path, "ui", *uiFlag)
|
||||||
|
|
||||||
|
runDir, err := paths.CreateRunDir()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Fprintf(os.Stderr, "warning: cannot set up log file %s: %v\n", logPath, err)
|
slog.Warn("run dir", "err", err)
|
||||||
} else {
|
} else {
|
||||||
defer f.Close()
|
defer func() {
|
||||||
log.Printf("[INIT] Logging to %s", logPath)
|
if err := paths.RemoveRunDir(runDir); err != nil {
|
||||||
log.Printf("[INIT] vcom starting — config: %s, resolved: %s", *configPath, resolvedPath)
|
slog.Warn("remove run dir", "err", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
model, err := ui.NewModel(cfg, resolvedPath)
|
var (
|
||||||
if err != nil {
|
program *tea.Program
|
||||||
log.Printf("[FATAL] startup error: %v", err)
|
teardown func()
|
||||||
fmt.Fprintf(os.Stderr, "startup error: %v\n", err)
|
onSignal = tea.Quit // SIGHUP: the new UI saves its session first
|
||||||
os.Exit(1)
|
)
|
||||||
|
switch *uiFlag {
|
||||||
|
case "next":
|
||||||
|
program, teardown = startNext(cfg, resolvedPath, notice, runDir)
|
||||||
|
onSignal = func() tea.Msg { return tui.Signal() }
|
||||||
|
case "old", "":
|
||||||
|
model, err := ui.NewModel(cfg, resolvedPath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("startup", "err", err)
|
||||||
|
fmt.Fprintf(os.Stderr, "startup error: %v\n", err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
model = model.WithStatus(notice)
|
||||||
|
program = tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
|
||||||
|
teardown = func() {}
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "vcom: unknown --ui=%s (old or next)\n", *uiFlag)
|
||||||
|
return 2
|
||||||
}
|
}
|
||||||
|
|
||||||
program := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
|
// SIGTERM/SIGINT are handled by Bubble Tea itself; SIGHUP (terminal
|
||||||
log.Printf("[INIT] Bubble Tea program started")
|
// closed) is not. Do NOT subscribe to SIGTERM here: when our tea.Quit
|
||||||
if _, err := program.Run(); err != nil {
|
// wins the race, Bubble Tea's own signal goroutine blocks forever on an
|
||||||
log.Printf("[FATAL] runtime error: %v", err)
|
// unbuffered send and Program.shutdown waits for it (QA-12).
|
||||||
fmt.Fprintf(os.Stderr, "runtime error: %v\n", err)
|
sigs := make(chan os.Signal, 1)
|
||||||
os.Exit(1)
|
signal.Notify(sigs, syscall.SIGHUP)
|
||||||
|
defer signal.Stop(sigs)
|
||||||
|
go func() {
|
||||||
|
for s := range sigs {
|
||||||
|
slog.Info("signal", "sig", s.String())
|
||||||
|
program.Send(onSignal())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
final, runErr := program.Run()
|
||||||
|
shutdown(final)
|
||||||
|
teardown()
|
||||||
|
switch {
|
||||||
|
case runErr == nil:
|
||||||
|
slog.Info("exited cleanly")
|
||||||
|
return 0
|
||||||
|
case errors.Is(runErr, tea.ErrInterrupted):
|
||||||
|
return 130
|
||||||
|
default:
|
||||||
|
slog.Error("runtime", "err", runErr)
|
||||||
|
fmt.Fprintf(os.Stderr, "runtime error: %v\n", runErr)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func openLog(debug bool, flagLevel string) (*logx.Logger, error) {
|
||||||
|
level, lerr := logx.ResolveLevel(debug, flagLevel, os.Getenv("VCOM_LOG"))
|
||||||
|
dir, err := paths.StateDir()
|
||||||
|
if err != nil {
|
||||||
|
return logx.Discard(), err
|
||||||
|
}
|
||||||
|
l, err := logx.Open(logx.Options{Dir: dir, Level: level})
|
||||||
|
if err != nil {
|
||||||
|
return logx.Discard(), err
|
||||||
|
}
|
||||||
|
if lerr != nil {
|
||||||
|
l.Warn("log level", "err", lerr)
|
||||||
|
}
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// shutdown saves the session of the final model (idempotent if the quit key
|
||||||
|
// already did it). The new UI saves its session in stage 6.6.
|
||||||
|
func shutdown(final tea.Model) {
|
||||||
|
switch m := final.(type) {
|
||||||
|
case ui.Model:
|
||||||
|
m.Shutdown()
|
||||||
|
case *tui.App:
|
||||||
|
if err := m.Shutdown(); err != nil {
|
||||||
|
slog.Warn("session", "err", err)
|
||||||
|
}
|
||||||
|
case *ui.Model:
|
||||||
|
m.Shutdown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// startNext wires the new UI (design §9.4): the jobs manager, the SSH
|
||||||
|
// connection pool and the host resolver go into tui.Deps. The returned
|
||||||
|
// teardown cancels jobs (giving them 3 s to remove temp files) and closes
|
||||||
|
// every connection; it runs after Program.Run returns.
|
||||||
|
func startNext(cfg config.Config, cfgPath, notice, runDir string) (*tea.Program, func()) {
|
||||||
|
var prog atomic.Pointer[tea.Program]
|
||||||
|
var pendingMu sync.Mutex
|
||||||
|
var pending []tea.Msg
|
||||||
|
send := func(m tea.Msg) {
|
||||||
|
if p := prog.Load(); p != nil {
|
||||||
|
p.Send(m)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pendingMu.Lock()
|
||||||
|
pending = append(pending, m)
|
||||||
|
pendingMu.Unlock()
|
||||||
|
}
|
||||||
|
readHome, _ := paths.ReadHome()
|
||||||
|
deps := tui.DefaultDeps(cfg, cfgPath)
|
||||||
|
deps.Notice = notice
|
||||||
|
if runDir != "" {
|
||||||
|
deps.RunDir = runDir
|
||||||
|
}
|
||||||
|
deps.Jobs = jobs.New(func(e jobs.Event) { send(tui.JobEvent(e)) }, cfg.Transfer.MaxParallelJobs)
|
||||||
|
pool := conn.NewPool(conn.PoolOptions{
|
||||||
|
DialOptions: conn.DialOptions{
|
||||||
|
HandshakeTimeout: cfg.SSH.ConnectTimeout.Duration,
|
||||||
|
Home: readHome,
|
||||||
|
Warn: func(m string) { slog.Warn("ssh", "msg", m) },
|
||||||
|
},
|
||||||
|
KeepaliveInterval: cfg.SSH.KeepaliveInterval.Duration,
|
||||||
|
})
|
||||||
|
deps.Pool = pool
|
||||||
|
var store *sshconfig.Store
|
||||||
|
if f, err := paths.DefaultConfigFile(); err == nil {
|
||||||
|
if s, err := sshconfig.OpenStore(filepath.Dir(f)); err == nil {
|
||||||
|
store = s
|
||||||
|
} else {
|
||||||
|
slog.Warn("hosts store", "err", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res, err := sshconfig.NewResolver(sshconfig.Options{Home: readHome, Store: store})
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("ssh config", "err", err)
|
||||||
|
}
|
||||||
|
deps.Resolver = res
|
||||||
|
|
||||||
|
tty := imgview.NewSyncTTY(os.Stdout)
|
||||||
|
images := imgview.Start(imgview.Options{
|
||||||
|
Backend: imgview.Detect(cfg.Preview.ImageBackend, os.Getenv),
|
||||||
|
TTY: tty,
|
||||||
|
TmpDir: runDir,
|
||||||
|
Tmux: os.Getenv("TMUX") != "",
|
||||||
|
OnEvent: func(e imgview.Event) { send(tui.ImageEvent(e)) },
|
||||||
|
})
|
||||||
|
deps.Image = images
|
||||||
|
p := tea.NewProgram(tui.New(deps), tea.WithAltScreen(), tea.WithMouseCellMotion(), tea.WithOutput(tty))
|
||||||
|
prog.Store(p)
|
||||||
|
pendingMu.Lock()
|
||||||
|
queued := append([]tea.Msg(nil), pending...)
|
||||||
|
pending = nil
|
||||||
|
pendingMu.Unlock()
|
||||||
|
go func() {
|
||||||
|
for _, m := range queued {
|
||||||
|
p.Send(m)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return p, func() {
|
||||||
|
prog.Store(nil)
|
||||||
|
images.Stop()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := deps.Jobs.Shutdown(ctx); err != nil {
|
||||||
|
slog.Warn("jobs shutdown", "err", err)
|
||||||
|
}
|
||||||
|
pool.Close()
|
||||||
}
|
}
|
||||||
log.Printf("[INIT] vcom exited cleanly")
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
97
cmd/vcom/qa_signal_test.go
Normal file
97
cmd/vcom/qa_signal_test.go
Normal file
|
|
@ -0,0 +1,97 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
// QA (v0.2.8 RC2): SIGTERM must end vcom and save the session. main
|
||||||
|
// registers its own SIGTERM handler next to Bubble Tea's; when main's
|
||||||
|
// tea.Quit wins, Bubble Tea's handler blocks forever on an unbuffered send
|
||||||
|
// and Program.shutdown waits for it: the process hangs in the alt screen
|
||||||
|
// and the session is never saved. The test runs the real run() in a child
|
||||||
|
// process (this test binary) on a pty (util-linux `script`) and sends
|
||||||
|
// SIGTERM repeatedly.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestQASigtermHelperProcess(t *testing.T) {
|
||||||
|
if os.Getenv("VCOM_QA_CHILD") != "1" {
|
||||||
|
t.Skip("helper process")
|
||||||
|
}
|
||||||
|
home := os.Getenv("HOME")
|
||||||
|
_ = os.WriteFile(filepath.Join(home, "pid"), []byte(strconv.Itoa(os.Getpid())), 0o600)
|
||||||
|
os.Args = []string{"vcom"}
|
||||||
|
os.Exit(run())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQASigtermExitsAndSavesSession(t *testing.T) {
|
||||||
|
script, err := exec.LookPath("script")
|
||||||
|
if err != nil {
|
||||||
|
t.Skip("util-linux script not available")
|
||||||
|
}
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// The hang was intermittent (~1 in 3); 12 runs take ~80s, so CI does a
|
||||||
|
// quick 2-run smoke and VCOM_SLOW_TESTS=1 enables the full loop.
|
||||||
|
runs := 2
|
||||||
|
if os.Getenv("VCOM_SLOW_TESTS") != "" {
|
||||||
|
runs = 12
|
||||||
|
}
|
||||||
|
hung, saved := 0, 0
|
||||||
|
for i := 0; i < runs; i++ {
|
||||||
|
home := t.TempDir()
|
||||||
|
child := exe + " -test.run=^TestQASigtermHelperProcess$"
|
||||||
|
cmd := exec.Command(script, "-qfec", "stty rows 40 cols 120; "+child, "/dev/null")
|
||||||
|
cmd.Env = append(os.Environ(),
|
||||||
|
"VCOM_QA_CHILD=1", "HOME="+home, "TERM=xterm-256color",
|
||||||
|
"XDG_CONFIG_HOME="+filepath.Join(home, ".config"),
|
||||||
|
"XDG_STATE_HOME="+filepath.Join(home, ".local", "state"),
|
||||||
|
"XDG_CACHE_HOME="+filepath.Join(home, ".cache"),
|
||||||
|
"XDG_DATA_HOME="+filepath.Join(home, ".local", "share"),
|
||||||
|
"VCOM_CONFIG=", "SSH_AUTH_SOCK=",
|
||||||
|
)
|
||||||
|
cmd.Dir = home
|
||||||
|
var out strings.Builder
|
||||||
|
cmd.Stdout, cmd.Stderr = &out, &out
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { cmd.Wait(); close(done) }()
|
||||||
|
var pid int
|
||||||
|
for w := 0; w < 500 && pid == 0; w++ {
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
if b, err := os.ReadFile(filepath.Join(home, "pid")); err == nil {
|
||||||
|
pid, _ = strconv.Atoi(strings.TrimSpace(string(b)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pid == 0 {
|
||||||
|
cmd.Process.Kill()
|
||||||
|
<-done
|
||||||
|
t.Fatalf("child did not start: %.400q", out.String())
|
||||||
|
}
|
||||||
|
time.Sleep(1500 * time.Millisecond) // UI up and idle
|
||||||
|
_ = syscall.Kill(pid, syscall.SIGTERM)
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(4 * time.Second):
|
||||||
|
hung++
|
||||||
|
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); err == nil {
|
||||||
|
saved++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Logf("runs=%d hung=%d saved=%d", runs, hung, saved)
|
||||||
|
if hung > 0 || saved != runs {
|
||||||
|
t.Fatalf("SIGTERM: vcom hung in %d of %d runs; session saved in %d", hung, runs, saved)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -13,7 +13,7 @@
|
||||||
lib = pkgs.lib;
|
lib = pkgs.lib;
|
||||||
packageBase = pkgs.buildGoModule {
|
packageBase = pkgs.buildGoModule {
|
||||||
pname = "vcom";
|
pname = "vcom";
|
||||||
version = "0.2.6";
|
version = "0.2.8";
|
||||||
src = ./.;
|
src = ./.;
|
||||||
vendorHash = null;
|
vendorHash = null;
|
||||||
|
|
||||||
|
|
|
||||||
2
go.mod
2
go.mod
|
|
@ -12,6 +12,7 @@ require (
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4
|
github.com/pelletier/go-toml/v2 v2.2.4
|
||||||
github.com/pkg/sftp v1.13.10
|
github.com/pkg/sftp v1.13.10
|
||||||
golang.org/x/crypto v0.50.0
|
golang.org/x/crypto v0.50.0
|
||||||
|
golang.org/x/image v0.39.0
|
||||||
golang.org/x/sys v0.43.0
|
golang.org/x/sys v0.43.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -22,6 +23,7 @@ require (
|
||||||
github.com/charmbracelet/x/term v0.2.1 // indirect
|
github.com/charmbracelet/x/term v0.2.1 // indirect
|
||||||
github.com/dlclark/regexp2 v1.11.5 // indirect
|
github.com/dlclark/regexp2 v1.11.5 // indirect
|
||||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||||
|
github.com/kevinburke/ssh_config v1.6.0 // indirect
|
||||||
github.com/kr/fs v0.1.0 // indirect
|
github.com/kr/fs v0.1.0 // indirect
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
|
|
||||||
4
go.sum
4
go.sum
|
|
@ -30,6 +30,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6
|
||||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||||
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
|
||||||
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=
|
||||||
|
github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY=
|
||||||
|
github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
|
||||||
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||||
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
|
||||||
|
|
@ -63,6 +65,8 @@ golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||||
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
|
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
|
||||||
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
|
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
|
||||||
|
golang.org/x/image v0.39.0 h1:skVYidAEVKgn8lZ602XO75asgXBgLj9G/FE3RbuPFww=
|
||||||
|
golang.org/x/image v0.39.0/go.mod h1:sIbmppfU+xFLPIG0FoVUTvyBMmgng1/XAMhQ2ft0hpA=
|
||||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||||
|
|
|
||||||
386
internal/archive/create.go
Normal file
386
internal/archive/create.go
Normal file
|
|
@ -0,0 +1,386 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"archive/zip"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/transfer"
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Create errors.
|
||||||
|
var (
|
||||||
|
ErrSameFile = errors.New("the archive would overwrite one of its sources")
|
||||||
|
ErrIntoSource = errors.New("the archive would be written inside a source directory")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Create writes the given sources (any FS) into archivePath on dst (any FS)
|
||||||
|
// in format f (design §5.1). The archive is written through
|
||||||
|
// transfer.WriteAtomic: a failed or cancelled run leaves neither a partial
|
||||||
|
// archive nor a damaged previous one, and a source is never truncated.
|
||||||
|
// Refused up front: an archivePath that is one of the sources or lies inside
|
||||||
|
// a source directory (also through symlinks; U-P0-1). An existing archive is
|
||||||
|
// a conflict for h.Resolve (Overwrite / KeepBoth = "name (1).zip" / Skip /
|
||||||
|
// Abort); without Resolve it is refused. Symlinks are stored as links.
|
||||||
|
// Errors of the zip/tar/gzip writers' Close fail the operation (N-P2-13).
|
||||||
|
func Create(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string, f Format,
|
||||||
|
h transfer.Hooks) transfer.Report {
|
||||||
|
var rep transfer.Report
|
||||||
|
fail := func(err error) transfer.Report {
|
||||||
|
rep.Err = err
|
||||||
|
rep.Cancelled = ctx.Err() != nil
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
if dst.Caps().ReadOnly {
|
||||||
|
return fail(fmt.Errorf("%w: %s", transfer.ErrReadOnly, dst.Label()))
|
||||||
|
}
|
||||||
|
archivePath = dst.Paths().Clean(archivePath)
|
||||||
|
if err := checkSources(ctx, src, paths, dst, archivePath); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
target, replace, skip, err := resolveTarget(ctx, dst, archivePath, h)
|
||||||
|
if err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
if skip {
|
||||||
|
rep.Skipped = 1
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
var items []transfer.Item
|
||||||
|
var total int64
|
||||||
|
seen := map[string]bool{}
|
||||||
|
err = transfer.FSSource(src, paths, transfer.CopyLinks).Walk(ctx, func(it transfer.Item) error {
|
||||||
|
if !strings.Contains(it.Rel, "/") {
|
||||||
|
if seen[it.Rel] {
|
||||||
|
return fmt.Errorf("%w: %s", transfer.ErrDuplicateName, it.Rel)
|
||||||
|
}
|
||||||
|
seen[it.Rel] = true
|
||||||
|
}
|
||||||
|
items = append(items, it)
|
||||||
|
if it.Kind == transfer.File {
|
||||||
|
total += it.Size
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
w := &writer{ctx: ctx, src: src, f: f, h: h, rep: &rep, items: items, total: total}
|
||||||
|
err = transfer.WriteAtomic(ctx, dst, target, transfer.WriteOptions{Perm: 0o644, Replace: replace, Fsync: true}, w.fill)
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
rep.Cancelled = true
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if !rep.Cancelled && rep.Err == nil {
|
||||||
|
rep.Err = err
|
||||||
|
}
|
||||||
|
rep.Done, rep.Bytes = 0, 0
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
rep.Affected = []vfs.Location{{FS: dst, Path: dst.Paths().Dir(target)}}
|
||||||
|
w.progress(true)
|
||||||
|
return rep
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkSources(ctx context.Context, src vfs.FS, paths []string, dst vfs.FS, archivePath string) error {
|
||||||
|
for _, p := range paths {
|
||||||
|
same, err := vfs.SameFile(ctx, src, p, dst, archivePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if same {
|
||||||
|
return fmt.Errorf("%w: %s", ErrSameFile, p)
|
||||||
|
}
|
||||||
|
if src.Volume() != dst.Volume() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fi, err := src.Lstat(ctx, p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !fi.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
in, err := vfs.Within(ctx, dst, archivePath, p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if in {
|
||||||
|
return fmt.Errorf("%w: %s", ErrIntoSource, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveTarget handles an existing archive file.
|
||||||
|
func resolveTarget(ctx context.Context, dst vfs.FS, p string, h transfer.Hooks) (target string, replace, skip bool, err error) {
|
||||||
|
fi, err := dst.Lstat(ctx, p)
|
||||||
|
if errors.Is(err, vfs.ErrNotExist) {
|
||||||
|
return p, false, false, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", false, false, err
|
||||||
|
}
|
||||||
|
if fi.IsDir() {
|
||||||
|
return "", false, false, fmt.Errorf("%s is a directory", p)
|
||||||
|
}
|
||||||
|
if h.Resolve == nil {
|
||||||
|
return "", false, false, fmt.Errorf("%s: %w", p, vfs.ErrExist)
|
||||||
|
}
|
||||||
|
res, err := h.Resolve(ctx, transfer.Conflict{
|
||||||
|
Item: transfer.Item{Rel: dst.Paths().Base(p), Kind: transfer.File, Existing: &fi},
|
||||||
|
Kind: transfer.FileFile,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return "", false, false, err
|
||||||
|
}
|
||||||
|
switch res.Action {
|
||||||
|
case transfer.ResolveOverwrite:
|
||||||
|
return p, true, false, nil
|
||||||
|
case transfer.ResolveSkip:
|
||||||
|
return "", false, true, nil
|
||||||
|
case transfer.ResolveKeepBoth:
|
||||||
|
free, err := FreeName(ctx, dst, p)
|
||||||
|
return free, false, false, err
|
||||||
|
}
|
||||||
|
return "", false, false, transfer.ErrAborted
|
||||||
|
}
|
||||||
|
|
||||||
|
// FreeName returns p or the first free "name (n).ext" next to it (the
|
||||||
|
// archive extension, e.g. .tar.gz, stays together).
|
||||||
|
func FreeName(ctx context.Context, fsys vfs.FS, p string) (string, error) {
|
||||||
|
ops := fsys.Paths()
|
||||||
|
dir, base := ops.Dir(p), ops.Base(p)
|
||||||
|
stem := stripArchiveExt(base)
|
||||||
|
ext := base[len(stem):]
|
||||||
|
for n := 0; n <= 10000; n++ {
|
||||||
|
cand := p
|
||||||
|
if n > 0 {
|
||||||
|
cand = ops.Join(dir, fmt.Sprintf("%s (%d)%s", stem, n, ext))
|
||||||
|
}
|
||||||
|
_, err := fsys.Lstat(ctx, cand)
|
||||||
|
if errors.Is(err, vfs.ErrNotExist) {
|
||||||
|
return cand, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("no free name for %s", p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// writer streams the items into the archive format.
|
||||||
|
type writer struct {
|
||||||
|
ctx context.Context
|
||||||
|
src vfs.FS
|
||||||
|
f Format
|
||||||
|
h transfer.Hooks
|
||||||
|
rep *transfer.Report
|
||||||
|
items []transfer.Item
|
||||||
|
total int64
|
||||||
|
done int64
|
||||||
|
files int
|
||||||
|
last time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writer) progress(force bool) {
|
||||||
|
if w.h.Progress == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
every := w.h.ProgressInterval
|
||||||
|
if every <= 0 {
|
||||||
|
every = 50 * time.Millisecond
|
||||||
|
}
|
||||||
|
if !force && time.Since(w.last) < every {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.last = time.Now()
|
||||||
|
w.h.Progress(transfer.Progress{Phase: transfer.Copying, FilesDone: w.files, BytesDone: w.done, BytesTotal: w.total})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writer) fill(out io.Writer) error {
|
||||||
|
switch w.f {
|
||||||
|
case Zip:
|
||||||
|
zw := zip.NewWriter(out)
|
||||||
|
if err := w.each(zipAdder{zw}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return zw.Close()
|
||||||
|
case Tar, TarGz:
|
||||||
|
var gz *gzip.Writer
|
||||||
|
if w.f == TarGz {
|
||||||
|
gz = gzip.NewWriter(out)
|
||||||
|
out = gz
|
||||||
|
}
|
||||||
|
tw := tar.NewWriter(out)
|
||||||
|
if err := w.each(tarAdder{tw}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tw.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if gz != nil {
|
||||||
|
return gz.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("archive: unknown format %d", w.f)
|
||||||
|
}
|
||||||
|
|
||||||
|
// adder writes one entry; body is nil except for regular files.
|
||||||
|
type adder interface {
|
||||||
|
add(it transfer.Item, body io.Reader) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writer) each(a adder) error {
|
||||||
|
for _, it := range w.items {
|
||||||
|
if err := w.ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch it.Kind {
|
||||||
|
case transfer.Special:
|
||||||
|
w.rep.Skipped++
|
||||||
|
w.rep.Warnings = append(w.rep.Warnings, it.Rel+": special file skipped")
|
||||||
|
continue
|
||||||
|
case transfer.Dir, transfer.Symlink:
|
||||||
|
if err := a.add(it, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if it.Kind == transfer.Symlink {
|
||||||
|
w.rep.Done++
|
||||||
|
w.files++
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := w.addFile(a, it); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// addFile opens the source first, so an unreadable file can be skipped
|
||||||
|
// (OnError) before its header is written. An error in the middle of a file
|
||||||
|
// aborts the archive (a tar header already promised its size).
|
||||||
|
func (w *writer) addFile(a adder, it transfer.Item) error {
|
||||||
|
for {
|
||||||
|
r, err := w.src.Open(w.ctx, it.Src)
|
||||||
|
if err == nil {
|
||||||
|
start := w.done
|
||||||
|
pr := &countReader{ctx: w.ctx, r: r, onRead: func(n int64) { w.done = start + n; w.progress(false) }}
|
||||||
|
err = a.add(it, pr)
|
||||||
|
r.Close()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s: %w", it.Rel, err)
|
||||||
|
}
|
||||||
|
if pr.n != it.Size {
|
||||||
|
return fmt.Errorf("%s: changed while archiving (%d of %d bytes)", it.Rel, pr.n, it.Size)
|
||||||
|
}
|
||||||
|
w.files++
|
||||||
|
w.rep.Done++
|
||||||
|
w.rep.Bytes += it.Size
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ie := transfer.ItemError{Item: it, Op: "read", Err: err}
|
||||||
|
act := transfer.ErrorSkip
|
||||||
|
switch {
|
||||||
|
case w.h.OnError != nil:
|
||||||
|
var herr error
|
||||||
|
if act, herr = w.h.OnError(w.ctx, ie); herr != nil {
|
||||||
|
return herr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch act {
|
||||||
|
case transfer.ErrorRetry:
|
||||||
|
continue
|
||||||
|
case transfer.ErrorStop:
|
||||||
|
w.rep.Errors = append(w.rep.Errors, ie)
|
||||||
|
w.rep.Failed++
|
||||||
|
return fmt.Errorf("%w: %v", transfer.ErrAborted, ie)
|
||||||
|
}
|
||||||
|
w.rep.Errors = append(w.rep.Errors, ie)
|
||||||
|
w.rep.Failed++
|
||||||
|
w.done += it.Size
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type countReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
r io.Reader
|
||||||
|
n int64
|
||||||
|
onRead func(int64)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *countReader) Read(p []byte) (int, error) {
|
||||||
|
if err := c.ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
n, err := c.r.Read(p)
|
||||||
|
c.n += int64(n)
|
||||||
|
if n > 0 {
|
||||||
|
c.onRead(c.n)
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
type zipAdder struct{ zw *zip.Writer }
|
||||||
|
|
||||||
|
func (z zipAdder) add(it transfer.Item, body io.Reader) error {
|
||||||
|
h := &zip.FileHeader{Name: it.Rel, Modified: it.ModTime, Method: zip.Deflate}
|
||||||
|
switch it.Kind {
|
||||||
|
case transfer.Dir:
|
||||||
|
h.Name += "/"
|
||||||
|
h.Method = zip.Store
|
||||||
|
h.SetMode(fs.ModeDir | it.Mode.Perm())
|
||||||
|
case transfer.Symlink:
|
||||||
|
h.Method = zip.Store
|
||||||
|
h.SetMode(fs.ModeSymlink | 0o777)
|
||||||
|
body = strings.NewReader(it.LinkTarget)
|
||||||
|
default:
|
||||||
|
h.SetMode(it.Mode.Perm())
|
||||||
|
h.UncompressedSize64 = uint64(it.Size)
|
||||||
|
}
|
||||||
|
w, err := z.zw.CreateHeader(h)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if body != nil {
|
||||||
|
_, err = io.Copy(w, body)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
type tarAdder struct{ tw *tar.Writer }
|
||||||
|
|
||||||
|
func (t tarAdder) add(it transfer.Item, body io.Reader) error {
|
||||||
|
h := &tar.Header{Name: it.Rel, ModTime: it.ModTime, Mode: int64(it.Mode.Perm())}
|
||||||
|
switch it.Kind {
|
||||||
|
case transfer.Dir:
|
||||||
|
h.Typeflag, h.Name = tar.TypeDir, it.Rel+"/"
|
||||||
|
case transfer.Symlink:
|
||||||
|
h.Typeflag, h.Linkname, h.Mode = tar.TypeSymlink, it.LinkTarget, 0o777
|
||||||
|
default:
|
||||||
|
h.Typeflag, h.Size = tar.TypeReg, it.Size
|
||||||
|
}
|
||||||
|
if err := t.tw.WriteHeader(h); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if body != nil {
|
||||||
|
if _, err := io.Copy(t.tw, body); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
214
internal/archive/create_test.go
Normal file
214
internal/archive/create_test.go
Normal file
|
|
@ -0,0 +1,214 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/fstree"
|
||||||
|
"vcom/internal/transfer"
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
"vcom/internal/vfs/localfs"
|
||||||
|
"vcom/internal/vfs/vfstest"
|
||||||
|
)
|
||||||
|
|
||||||
|
var local = localfs.New()
|
||||||
|
|
||||||
|
func noTemps(t *testing.T, dir string) {
|
||||||
|
t.Helper()
|
||||||
|
ents, _ := os.ReadDir(dir)
|
||||||
|
for _, e := range ents {
|
||||||
|
if strings.HasPrefix(e.Name(), ".vcom-") {
|
||||||
|
t.Errorf("temp left: %s", e.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUP01_ArchiveDoesNotDestroySource(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
fstree.Build(t, dir, fstree.Spec{fstree.File("data.tar", "").WithSize(64 << 10)})
|
||||||
|
before, _ := os.ReadFile(filepath.Join(dir, "data.tar"))
|
||||||
|
name := Name([]string{"data.tar"}, Tar)
|
||||||
|
if name != "data.tar" {
|
||||||
|
t.Fatalf("name %s", name)
|
||||||
|
}
|
||||||
|
rep := Create(bg, local, []string{filepath.Join(dir, "data.tar")}, local, filepath.Join(dir, name), Tar,
|
||||||
|
transfer.Hooks{Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) {
|
||||||
|
return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil
|
||||||
|
}})
|
||||||
|
if !errors.Is(rep.Err, ErrSameFile) {
|
||||||
|
t.Fatalf("err = %v, want ErrSameFile (U-P0-1)", rep.Err)
|
||||||
|
}
|
||||||
|
if after, _ := os.ReadFile(filepath.Join(dir, "data.tar")); string(after) != string(before) {
|
||||||
|
t.Fatal("source damaged")
|
||||||
|
}
|
||||||
|
// With another name (what the UI offers) it works.
|
||||||
|
free, err := FreeName(bg, local, filepath.Join(dir, name))
|
||||||
|
if err != nil || filepath.Base(free) != "data (1).tar" {
|
||||||
|
t.Fatalf("free name %q %v", free, err)
|
||||||
|
}
|
||||||
|
rep = Create(bg, local, []string{filepath.Join(dir, "data.tar")}, local, free, Tar, transfer.Hooks{})
|
||||||
|
if rep.Err != nil || rep.Done != 1 {
|
||||||
|
t.Fatalf("%+v", rep)
|
||||||
|
}
|
||||||
|
idx, err := IndexFile(bg, local, free, nil)
|
||||||
|
if err != nil || len(idx.Entries) != 1 || idx.Entries[0].Size != 64<<10 {
|
||||||
|
t.Fatalf("index %+v %v", idx, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArchiveIntoSourceDirRejected(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
fstree.Build(t, dir, fstree.Spec{fstree.File("proj/a", "a"), fstree.Dir("proj/sub"), fstree.Symlink("alias", "proj")})
|
||||||
|
for _, target := range []string{
|
||||||
|
filepath.Join(dir, "proj", "proj.zip"),
|
||||||
|
filepath.Join(dir, "proj", "sub", "x.zip"),
|
||||||
|
filepath.Join(dir, "alias", "x.zip"), // through a symlink
|
||||||
|
} {
|
||||||
|
rep := Create(bg, local, []string{filepath.Join(dir, "proj")}, local, target, Zip, transfer.Hooks{})
|
||||||
|
if !errors.Is(rep.Err, ErrIntoSource) {
|
||||||
|
t.Errorf("%s: %v", target, rep.Err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(target); !os.IsNotExist(err) {
|
||||||
|
t.Errorf("%s written", target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rep := Create(bg, local, []string{filepath.Join(dir, "proj")}, local, filepath.Join(dir, "proj.zip"), Zip, transfer.Hooks{}); rep.Err != nil {
|
||||||
|
t.Fatal(rep.Err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArchiveCancelRemovesPartial(t *testing.T) {
|
||||||
|
src := t.TempDir()
|
||||||
|
fstree.Build(t, src, fstree.Spec{fstree.File("d/big", "").WithSize(4 << 20), fstree.File("d/b", "b")})
|
||||||
|
out := t.TempDir()
|
||||||
|
old := filepath.Join(out, "d.tar.gz")
|
||||||
|
if err := os.WriteFile(old, []byte("previous archive"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dst := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
|
||||||
|
if op == vfstest.OpWrite {
|
||||||
|
time.Sleep(2 * time.Millisecond)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}}
|
||||||
|
ctx, cancel := context.WithCancel(bg)
|
||||||
|
time.AfterFunc(50*time.Millisecond, cancel)
|
||||||
|
rep := Create(ctx, local, []string{filepath.Join(src, "d")}, dst, old, TarGz, transfer.Hooks{
|
||||||
|
Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) {
|
||||||
|
return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil
|
||||||
|
}})
|
||||||
|
if !rep.Cancelled || rep.Done != 0 {
|
||||||
|
t.Fatalf("%+v", rep)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(old); string(b) != "previous archive" {
|
||||||
|
t.Fatal("previous archive damaged by a cancelled overwrite")
|
||||||
|
}
|
||||||
|
noTemps(t, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArchiveCloseErrorReported(t *testing.T) {
|
||||||
|
src := t.TempDir()
|
||||||
|
fstree.Build(t, src, fstree.Spec{fstree.File("a", "data")})
|
||||||
|
for _, f := range []Format{Zip, Tar, TarGz} {
|
||||||
|
out := t.TempDir()
|
||||||
|
dst := &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpClose, 1, syscall.EIO)}
|
||||||
|
target := filepath.Join(out, "a"+f.Ext())
|
||||||
|
rep := Create(bg, local, []string{filepath.Join(src, "a")}, dst, target, f, transfer.Hooks{})
|
||||||
|
if !errors.Is(rep.Err, syscall.EIO) || rep.Done != 0 {
|
||||||
|
t.Fatalf("%v: close error not reported (N-P2-13): %+v", f, rep)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(target); !os.IsNotExist(err) {
|
||||||
|
t.Fatalf("%v: archive committed", f)
|
||||||
|
}
|
||||||
|
noTemps(t, out)
|
||||||
|
// A write error while the writers flush on Close is reported too.
|
||||||
|
dst = &vfstest.FaultFS{FS: local, Hook: vfstest.FailNth(vfstest.OpWrite, 1, syscall.ENOSPC)}
|
||||||
|
rep = Create(bg, local, []string{filepath.Join(src, "a")}, dst, target, f, transfer.Hooks{})
|
||||||
|
if !errors.Is(rep.Err, syscall.ENOSPC) {
|
||||||
|
t.Fatalf("%v: flush error: %+v", f, rep)
|
||||||
|
}
|
||||||
|
noTemps(t, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArchiveNameTarGzToZip(t *testing.T) {
|
||||||
|
if got := Name([]string{"/srv/foo.tar.gz"}, Zip); got != "foo.zip" {
|
||||||
|
t.Fatalf("got %s (U-P2: was foo.tar.zip)", got)
|
||||||
|
}
|
||||||
|
out := t.TempDir()
|
||||||
|
fstree.Build(t, out, fstree.Spec{fstree.File("a (1).tar.gz", ""), fstree.File("a.tar.gz", "")})
|
||||||
|
if p, _ := FreeName(bg, local, filepath.Join(out, "a.tar.gz")); filepath.Base(p) != "a (2).tar.gz" {
|
||||||
|
t.Fatalf("free %s", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArchiveSymlinksPreserved(t *testing.T) {
|
||||||
|
src := t.TempDir()
|
||||||
|
mt := time.Date(2019, 3, 4, 5, 6, 7, 0, time.UTC)
|
||||||
|
spec := fstree.Spec{
|
||||||
|
fstree.File("d/run.sh", "#!/bin/sh").WithMode(0o755).WithMTime(mt),
|
||||||
|
fstree.Symlink("d/ln", "run.sh"),
|
||||||
|
fstree.Symlink("d/broken", "../nowhere"),
|
||||||
|
fstree.Dir("d/empty"),
|
||||||
|
}
|
||||||
|
fstree.Build(t, src, spec)
|
||||||
|
for _, f := range []Format{Zip, Tar, TarGz} {
|
||||||
|
out := t.TempDir()
|
||||||
|
arch := filepath.Join(out, "d"+f.Ext())
|
||||||
|
rep := Create(bg, local, []string{filepath.Join(src, "d")}, local, arch, f, transfer.Hooks{})
|
||||||
|
if rep.Err != nil || rep.Done != 3 {
|
||||||
|
t.Fatalf("%v: %+v", f, rep)
|
||||||
|
}
|
||||||
|
idx, err := IndexFile(bg, local, arch, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for p, want := range map[string]string{"d/ln": "run.sh", "d/broken": "../nowhere"} {
|
||||||
|
if e, ok := idx.Lookup(p); !ok || !e.IsSymlink() || e.Link != want {
|
||||||
|
t.Fatalf("%v: %s = %+v", f, p, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Round trip through Unpack gives the same tree (modes, mtimes, links).
|
||||||
|
back := t.TempDir()
|
||||||
|
if rep := Unpack(bg, local, arch, idx, nil, local, back, transfer.DefaultOptions(), transfer.Hooks{}); rep.Err != nil || rep.Failed != 0 {
|
||||||
|
t.Fatalf("%v: unpack %+v", f, rep)
|
||||||
|
}
|
||||||
|
fstree.Equal(t, fstree.Snapshot(t, filepath.Join(src, "d")), fstree.Snapshot(t, filepath.Join(back, "d")),
|
||||||
|
fstree.Opts{Mode: true, Links: true})
|
||||||
|
if fi, _ := os.Stat(filepath.Join(back, "d", "run.sh")); !fi.ModTime().Equal(mt) {
|
||||||
|
t.Fatalf("%v: mtime %v", f, fi.ModTime())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestArchiveExistingTargetIsConflict(t *testing.T) {
|
||||||
|
src, out := t.TempDir(), t.TempDir()
|
||||||
|
fstree.Build(t, src, fstree.Spec{fstree.File("a", "new")})
|
||||||
|
target := filepath.Join(out, "a.zip")
|
||||||
|
_ = os.WriteFile(target, []byte("old"), 0o644)
|
||||||
|
if rep := Create(bg, local, []string{filepath.Join(src, "a")}, local, target, Zip, transfer.Hooks{}); !errors.Is(rep.Err, vfs.ErrExist) {
|
||||||
|
t.Fatalf("no Resolve: %v", rep.Err)
|
||||||
|
}
|
||||||
|
rep := Create(bg, local, []string{filepath.Join(src, "a")}, local, target, Zip, transfer.Hooks{
|
||||||
|
Resolve: func(_ context.Context, c transfer.Conflict) (transfer.Resolution, error) {
|
||||||
|
if c.Item.Existing == nil {
|
||||||
|
t.Error("no Existing")
|
||||||
|
}
|
||||||
|
return transfer.Resolution{Action: transfer.ResolveKeepBoth}, nil
|
||||||
|
}})
|
||||||
|
if rep.Err != nil || len(rep.Affected) != 1 {
|
||||||
|
t.Fatalf("%+v", rep)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(target); string(b) != "old" {
|
||||||
|
t.Fatal("KeepBoth overwrote")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(out, "a (1).zip")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
89
internal/archive/format.go
Normal file
89
internal/archive/format.go
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
// Package archive reads and writes zip, tar and tar.gz archives on top of
|
||||||
|
// vfs (design §5.1–5.3): an Index is built without unpacking anything to a
|
||||||
|
// temp directory, NewSource feeds members to the transfer engine in one pass
|
||||||
|
// over the archive (Unpack), and Create writes an archive through
|
||||||
|
// transfer.WriteAtomic.
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Format of an archive.
|
||||||
|
type Format uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Zip Format = iota
|
||||||
|
Tar
|
||||||
|
TarGz
|
||||||
|
)
|
||||||
|
|
||||||
|
func (f Format) String() string {
|
||||||
|
switch f {
|
||||||
|
case Zip:
|
||||||
|
return "zip"
|
||||||
|
case Tar:
|
||||||
|
return "tar"
|
||||||
|
case TarGz:
|
||||||
|
return "tar.gz"
|
||||||
|
}
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ext is the file extension, with the dot.
|
||||||
|
func (f Format) Ext() string { return "." + f.String() }
|
||||||
|
|
||||||
|
// knownExts in match order (longest first).
|
||||||
|
var knownExts = []struct {
|
||||||
|
ext string
|
||||||
|
f Format
|
||||||
|
}{
|
||||||
|
{".tar.gz", TarGz}, {".tgz", TarGz}, {".tar", Tar}, {".zip", Zip},
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetectFormat guesses the format from the file name.
|
||||||
|
func DetectFormat(name string) (Format, bool) {
|
||||||
|
lower := strings.ToLower(name)
|
||||||
|
for _, k := range knownExts {
|
||||||
|
if strings.HasSuffix(lower, k.ext) && len(lower) > len(k.ext) {
|
||||||
|
return k.f, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// stripArchiveExt removes a known archive extension, or else the last
|
||||||
|
// extension (report.pdf → report).
|
||||||
|
func stripArchiveExt(name string) string {
|
||||||
|
lower := strings.ToLower(name)
|
||||||
|
for _, k := range knownExts {
|
||||||
|
if strings.HasSuffix(lower, k.ext) && len(name) > len(k.ext) {
|
||||||
|
return name[:len(name)-len(k.ext)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ext := path.Ext(name); ext != "" && ext != name {
|
||||||
|
return name[:len(name)-len(ext)]
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name proposes an archive file name for the given sources (paths or base
|
||||||
|
// names, slash-separated): one source → its name without extension
|
||||||
|
// (foo.tar.gz → foo.zip, not foo.tar.zip; U-P2); several → the name of
|
||||||
|
// their parent directory, or "archive".
|
||||||
|
func Name(srcNames []string, f Format) string {
|
||||||
|
if len(srcNames) == 1 {
|
||||||
|
base := path.Base(strings.TrimRight(srcNames[0], "/"))
|
||||||
|
if b := stripArchiveExt(base); b != "" && b != "." && b != "/" {
|
||||||
|
return b + f.Ext()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(srcNames) > 1 {
|
||||||
|
parent := path.Base(path.Dir(srcNames[0]))
|
||||||
|
if parent != "." && parent != "/" && parent != "" {
|
||||||
|
return parent + f.Ext()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "archive" + f.Ext()
|
||||||
|
}
|
||||||
135
internal/archive/helpers_test.go
Normal file
135
internal/archive/helpers_test.go
Normal file
|
|
@ -0,0 +1,135 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var bg = context.Background()
|
||||||
|
|
||||||
|
// member describes an entry for test archives.
|
||||||
|
type member struct {
|
||||||
|
name string
|
||||||
|
body string
|
||||||
|
mode fs.FileMode // type bits + perm; 0 → regular 0644
|
||||||
|
link string
|
||||||
|
}
|
||||||
|
|
||||||
|
var mtime = time.Date(2020, 5, 6, 7, 8, 9, 0, time.UTC)
|
||||||
|
|
||||||
|
func dir(name string) member { return member{name: name, mode: fs.ModeDir | 0o755} }
|
||||||
|
func file(name, body string) member { return member{name: name, body: body} }
|
||||||
|
func symlink(name, target string) member {
|
||||||
|
return member{name: name, mode: fs.ModeSymlink | 0o777, link: target}
|
||||||
|
}
|
||||||
|
|
||||||
|
// makeArchive writes members in the given format to a byte slice.
|
||||||
|
func makeArchive(t *testing.T, f Format, ms ...member) []byte {
|
||||||
|
t.Helper()
|
||||||
|
var buf bytes.Buffer
|
||||||
|
switch f {
|
||||||
|
case Zip:
|
||||||
|
zw := zip.NewWriter(&buf)
|
||||||
|
for _, m := range ms {
|
||||||
|
mode := m.mode
|
||||||
|
if mode == 0 {
|
||||||
|
mode = 0o644
|
||||||
|
}
|
||||||
|
h := &zip.FileHeader{Name: m.name, Method: zip.Deflate, Modified: mtime}
|
||||||
|
h.SetMode(mode)
|
||||||
|
w, err := zw.CreateHeader(h)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body := m.body
|
||||||
|
if mode&fs.ModeSymlink != 0 {
|
||||||
|
body = m.link
|
||||||
|
}
|
||||||
|
if _, err := w.Write([]byte(body)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := zw.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
var gz *gzip.Writer
|
||||||
|
var tw *tar.Writer
|
||||||
|
if f == TarGz {
|
||||||
|
gz = gzip.NewWriter(&buf)
|
||||||
|
tw = tar.NewWriter(gz)
|
||||||
|
} else {
|
||||||
|
tw = tar.NewWriter(&buf)
|
||||||
|
}
|
||||||
|
for _, m := range ms {
|
||||||
|
h := &tar.Header{Name: m.name, Mode: 0o644, ModTime: mtime, Typeflag: tar.TypeReg, Size: int64(len(m.body))}
|
||||||
|
switch {
|
||||||
|
case m.mode.IsDir():
|
||||||
|
h.Typeflag, h.Mode, h.Size = tar.TypeDir, 0o755, 0
|
||||||
|
case m.mode&fs.ModeSymlink != 0:
|
||||||
|
h.Typeflag, h.Mode, h.Size, h.Linkname = tar.TypeSymlink, 0o777, 0, m.link
|
||||||
|
case m.mode&fs.ModeNamedPipe != 0:
|
||||||
|
h.Typeflag, h.Size = tar.TypeFifo, 0
|
||||||
|
case m.mode != 0:
|
||||||
|
h.Mode = int64(m.mode.Perm())
|
||||||
|
}
|
||||||
|
if err := tw.WriteHeader(h); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if h.Size > 0 {
|
||||||
|
if _, err := tw.Write([]byte(m.body)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tw.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if gz != nil {
|
||||||
|
if err := gz.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return buf.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeArchive stores an archive as <tmp>/<name> and returns its path.
|
||||||
|
func writeArchive(t *testing.T, name string, ms ...member) string {
|
||||||
|
t.Helper()
|
||||||
|
f, ok := DetectFormat(name)
|
||||||
|
if !ok {
|
||||||
|
t.Fatalf("bad name %s", name)
|
||||||
|
}
|
||||||
|
p := filepath.Join(t.TempDir(), name)
|
||||||
|
if err := os.WriteFile(p, makeArchive(t, f, ms...), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func index(t *testing.T, f Format, ms ...member) *Index {
|
||||||
|
t.Helper()
|
||||||
|
b := makeArchive(t, f, ms...)
|
||||||
|
idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), f, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return idx
|
||||||
|
}
|
||||||
|
|
||||||
|
func paths(idx *Index) []string {
|
||||||
|
var out []string
|
||||||
|
for _, e := range idx.Entries {
|
||||||
|
out = append(out, e.Path)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
308
internal/archive/index.go
Normal file
308
internal/archive/index.go
Normal file
|
|
@ -0,0 +1,308 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"archive/zip"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"path"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Entry is one member of an archive.
|
||||||
|
type Entry struct {
|
||||||
|
Path string // clean, slash-separated, relative ("dir/file"); never "..", never absolute
|
||||||
|
Mode fs.FileMode
|
||||||
|
Size int64
|
||||||
|
ModTime time.Time
|
||||||
|
Link string // symlink target, as stored
|
||||||
|
// Implicit: a parent directory that has no entry of its own.
|
||||||
|
Implicit bool
|
||||||
|
ord int // position in the archive (header number); -1 for implicit dirs
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsDir, IsSymlink and IsRegular classify the entry.
|
||||||
|
func (e Entry) IsDir() bool { return e.Mode.IsDir() }
|
||||||
|
func (e Entry) IsSymlink() bool { return e.Mode&fs.ModeSymlink != 0 }
|
||||||
|
func (e Entry) IsRegular() bool { return e.Mode.IsRegular() }
|
||||||
|
|
||||||
|
// Index lists an archive's members, sorted by path (parents first).
|
||||||
|
type Index struct {
|
||||||
|
Format Format
|
||||||
|
Entries []Entry
|
||||||
|
TotalBytes int64 // sum of regular file sizes (shown before unpacking)
|
||||||
|
Rejected []string // unsafe names dropped (zip-slip, absolute, under a symlink)
|
||||||
|
byPath map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the entry at p ("" or "/" is not an entry).
|
||||||
|
func (x *Index) Lookup(p string) (Entry, bool) {
|
||||||
|
i, ok := x.byPath[strings.Trim(path.Clean("/"+p), "/")]
|
||||||
|
if !ok {
|
||||||
|
return Entry{}, false
|
||||||
|
}
|
||||||
|
return x.Entries[i], true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limits protect against archive bombs.
|
||||||
|
type Limits struct {
|
||||||
|
MaxMembers int // default 1 000 000
|
||||||
|
MaxBytes int64 // sum of declared sizes; 0 = unlimited
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultLimits are used by BuildIndex.
|
||||||
|
var DefaultLimits = Limits{MaxMembers: 1_000_000}
|
||||||
|
|
||||||
|
// ErrTooManyMembers and ErrTooLarge are returned when Limits are exceeded.
|
||||||
|
var (
|
||||||
|
ErrTooManyMembers = errors.New("archive has too many members")
|
||||||
|
ErrTooLarge = errors.New("archive is too large")
|
||||||
|
)
|
||||||
|
|
||||||
|
// BuildIndex reads the archive's directory (zip) or walks it once (tar,
|
||||||
|
// tar.gz: one decompression pass). progress gets the member count so far;
|
||||||
|
// ctx cancels the pass.
|
||||||
|
func BuildIndex(ctx context.Context, r io.ReaderAt, size int64, f Format, progress func(n int)) (*Index, error) {
|
||||||
|
return BuildIndexLimits(ctx, r, size, f, DefaultLimits, progress)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildIndexLimits is BuildIndex with explicit limits.
|
||||||
|
func BuildIndexLimits(ctx context.Context, r io.ReaderAt, size int64, f Format, lim Limits, progress func(n int)) (*Index, error) {
|
||||||
|
b := &indexBuilder{idx: &Index{Format: f}, lim: lim, kinds: map[string]fs.FileMode{}, progress: progress}
|
||||||
|
var err error
|
||||||
|
switch f {
|
||||||
|
case Zip:
|
||||||
|
err = b.zip(ctx, r, size)
|
||||||
|
case Tar, TarGz:
|
||||||
|
err = b.tar(ctx, io.NewSectionReader(r, 0, size), f == TarGz)
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf("archive: unknown format %d", f)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b.finish()
|
||||||
|
return b.idx, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type indexBuilder struct {
|
||||||
|
idx *Index
|
||||||
|
lim Limits
|
||||||
|
n int
|
||||||
|
kinds map[string]fs.FileMode // path → type bits of entries seen
|
||||||
|
entries map[string]Entry
|
||||||
|
progress func(int)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *indexBuilder) zip(ctx context.Context, r io.ReaderAt, size int64) error {
|
||||||
|
zr, err := zip.NewReader(r, size)
|
||||||
|
if err != nil && !errors.Is(err, zip.ErrInsecurePath) { // insecure names are rejected below
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i, zf := range zr.File {
|
||||||
|
if i%256 == 0 {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mode := zf.Mode()
|
||||||
|
e := Entry{Path: zf.Name, Mode: mode, Size: int64(zf.UncompressedSize64), ModTime: zf.Modified, ord: i}
|
||||||
|
if mode&fs.ModeSymlink != 0 {
|
||||||
|
e.Size = 0
|
||||||
|
link, err := readZipLink(zf)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("%s: %w", zf.Name, err)
|
||||||
|
}
|
||||||
|
e.Link = link
|
||||||
|
}
|
||||||
|
if err := b.add(e); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// readZipLink reads a symlink's target, stored as the member's body.
|
||||||
|
func readZipLink(zf *zip.File) (string, error) {
|
||||||
|
rc, err := zf.Open()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer rc.Close()
|
||||||
|
b, err := io.ReadAll(io.LimitReader(rc, 4096))
|
||||||
|
return string(b), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *indexBuilder) tar(ctx context.Context, r io.Reader, gz bool) error {
|
||||||
|
if gz {
|
||||||
|
zr, err := gzip.NewReader(r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer zr.Close()
|
||||||
|
r = zr
|
||||||
|
}
|
||||||
|
tr := tar.NewReader(&ctxReader{ctx: ctx, r: r})
|
||||||
|
for i := 0; ; i++ {
|
||||||
|
h, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, tar.ErrInsecurePath) {
|
||||||
|
err = nil // (GODEBUG=tarinsecurepath=0) rejected by cleanName instead
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
e, ok := tarEntry(h, i)
|
||||||
|
if !ok {
|
||||||
|
continue // PAX globals, GNU long-name records handled by archive/tar
|
||||||
|
}
|
||||||
|
if err := b.add(e); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func tarEntry(h *tar.Header, ord int) (Entry, bool) {
|
||||||
|
fi := h.FileInfo()
|
||||||
|
e := Entry{Path: h.Name, Mode: fi.Mode(), Size: h.Size, ModTime: h.ModTime, ord: ord}
|
||||||
|
switch h.Typeflag {
|
||||||
|
case tar.TypeReg, tar.TypeRegA, tar.TypeGNUSparse:
|
||||||
|
case tar.TypeDir:
|
||||||
|
e.Size = 0
|
||||||
|
case tar.TypeSymlink:
|
||||||
|
e.Size, e.Link = 0, h.Linkname
|
||||||
|
case tar.TypeLink:
|
||||||
|
// Hard links are indexed as specials (skipped on unpack): following
|
||||||
|
// them would need a second pass.
|
||||||
|
e.Mode, e.Size = fs.ModeIrregular|fi.Mode().Perm(), 0
|
||||||
|
case tar.TypeChar, tar.TypeBlock, tar.TypeFifo:
|
||||||
|
e.Size = 0
|
||||||
|
default:
|
||||||
|
return Entry{}, false
|
||||||
|
}
|
||||||
|
return e, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanName returns the safe relative path of a member, or false for
|
||||||
|
// zip-slip ("..", absolute paths, drive letters).
|
||||||
|
func cleanName(name string) (string, bool) {
|
||||||
|
name = strings.ReplaceAll(name, "\\", "/")
|
||||||
|
if strings.HasPrefix(name, "/") || (len(name) > 1 && name[1] == ':') {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
for _, part := range strings.Split(name, "/") {
|
||||||
|
if part == ".." {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c := path.Clean(name)
|
||||||
|
if c == "." || c == "" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return c, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *indexBuilder) add(e Entry) error {
|
||||||
|
b.n++
|
||||||
|
if b.lim.MaxMembers > 0 && b.n > b.lim.MaxMembers {
|
||||||
|
return fmt.Errorf("%w (more than %d)", ErrTooManyMembers, b.lim.MaxMembers)
|
||||||
|
}
|
||||||
|
if b.progress != nil && b.n%256 == 0 {
|
||||||
|
b.progress(b.n)
|
||||||
|
}
|
||||||
|
p, ok := cleanName(e.Path)
|
||||||
|
if !ok {
|
||||||
|
b.idx.Rejected = append(b.idx.Rejected, e.Path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// A member below a symlink (or file) of the same archive would be
|
||||||
|
// written through that link on unpack: reject it.
|
||||||
|
for d := path.Dir(p); d != "."; d = path.Dir(d) {
|
||||||
|
if m, seen := b.kinds[d]; seen && !m.IsDir() {
|
||||||
|
b.idx.Rejected = append(b.idx.Rejected, e.Path)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.Path = p
|
||||||
|
if e.Mode.IsRegular() {
|
||||||
|
b.idx.TotalBytes += e.Size
|
||||||
|
if b.lim.MaxBytes > 0 && b.idx.TotalBytes > b.lim.MaxBytes {
|
||||||
|
return fmt.Errorf("%w (more than %d bytes)", ErrTooLarge, b.lim.MaxBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if b.entries == nil {
|
||||||
|
b.entries = map[string]Entry{}
|
||||||
|
}
|
||||||
|
if old, dup := b.entries[p]; dup && old.Mode.IsRegular() {
|
||||||
|
b.idx.TotalBytes -= old.Size // a later member with the same name wins (tar semantics)
|
||||||
|
}
|
||||||
|
b.entries[p] = e
|
||||||
|
b.kinds[p] = e.Mode.Type()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// finish drops members below a non-directory (in any archive order), adds
|
||||||
|
// implicit parent directories and sorts.
|
||||||
|
func (b *indexBuilder) finish() {
|
||||||
|
for p := range b.entries {
|
||||||
|
for d := path.Dir(p); d != "."; d = path.Dir(d) {
|
||||||
|
if e, ok := b.entries[d]; ok && !e.IsDir() {
|
||||||
|
b.idx.Rejected = append(b.idx.Rejected, p)
|
||||||
|
if old := b.entries[p]; old.Mode.IsRegular() {
|
||||||
|
b.idx.TotalBytes -= old.Size
|
||||||
|
}
|
||||||
|
delete(b.entries, p)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(b.idx.Rejected)
|
||||||
|
for p := range b.entries {
|
||||||
|
for d := path.Dir(p); d != "."; d = path.Dir(d) {
|
||||||
|
if _, ok := b.entries[d]; ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
b.entries[d] = Entry{Path: d, Mode: fs.ModeDir | 0o755, Implicit: true, ord: -1}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
x := b.idx
|
||||||
|
x.Entries = make([]Entry, 0, len(b.entries))
|
||||||
|
for _, e := range b.entries {
|
||||||
|
x.Entries = append(x.Entries, e)
|
||||||
|
}
|
||||||
|
// Sort by components: "a/b" right after "a" (plain order puts "a-b" between).
|
||||||
|
sort.Slice(x.Entries, func(i, j int) bool {
|
||||||
|
return strings.ReplaceAll(x.Entries[i].Path, "/", "\x00") < strings.ReplaceAll(x.Entries[j].Path, "/", "\x00")
|
||||||
|
})
|
||||||
|
x.byPath = make(map[string]int, len(x.Entries))
|
||||||
|
for i, e := range x.Entries {
|
||||||
|
x.byPath[e.Path] = i
|
||||||
|
}
|
||||||
|
if b.progress != nil {
|
||||||
|
b.progress(b.n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ctxReader stops a long decompression on cancel.
|
||||||
|
type ctxReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
r io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ctxReader) Read(p []byte) (int, error) {
|
||||||
|
if err := c.ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return c.r.Read(p)
|
||||||
|
}
|
||||||
211
internal/archive/index_test.go
Normal file
211
internal/archive/index_test.go
Normal file
|
|
@ -0,0 +1,211 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"vcom/internal/transfer"
|
||||||
|
"vcom/internal/vfs/localfs"
|
||||||
|
"vcom/internal/vfs/vfstest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIndexZip(t *testing.T) {
|
||||||
|
idx := index(t, Zip,
|
||||||
|
dir("docs/"),
|
||||||
|
file("docs/a.txt", "hello"),
|
||||||
|
file("deep/x/y.bin", "12345678"), // parents implicit
|
||||||
|
symlink("docs/ln", "a.txt"),
|
||||||
|
)
|
||||||
|
if got := fmt.Sprint(paths(idx)); got != "[deep deep/x deep/x/y.bin docs docs/a.txt docs/ln]" {
|
||||||
|
t.Fatalf("paths %s", got)
|
||||||
|
}
|
||||||
|
if idx.TotalBytes != 13 || idx.Format != Zip {
|
||||||
|
t.Fatalf("total %d", idx.TotalBytes)
|
||||||
|
}
|
||||||
|
e, _ := idx.Lookup("/docs/ln")
|
||||||
|
if !e.IsSymlink() || e.Link != "a.txt" {
|
||||||
|
t.Fatalf("link %+v", e)
|
||||||
|
}
|
||||||
|
d, _ := idx.Lookup("deep")
|
||||||
|
if !d.IsDir() || !d.Implicit {
|
||||||
|
t.Fatalf("implicit dir %+v", d)
|
||||||
|
}
|
||||||
|
f, _ := idx.Lookup("docs/a.txt")
|
||||||
|
if f.Size != 5 || !f.ModTime.Equal(mtime) || f.Mode.Perm() != 0o644 {
|
||||||
|
t.Fatalf("file %+v", f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIndexTarGz(t *testing.T) {
|
||||||
|
var ms []member
|
||||||
|
for i := range 1000 {
|
||||||
|
ms = append(ms, file(fmt.Sprintf("d/f%04d", i), "x"))
|
||||||
|
}
|
||||||
|
ms = append(ms, symlink("d/ln", "f0000"), member{name: "d/fifo", mode: os.ModeNamedPipe | 0o644})
|
||||||
|
b := makeArchive(t, TarGz, ms...)
|
||||||
|
var progress []int
|
||||||
|
idx, err := BuildIndex(bg, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) { progress = append(progress, n) })
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(idx.Entries) != 1003 || idx.TotalBytes != 1000 {
|
||||||
|
t.Fatalf("%d entries, %d bytes", len(idx.Entries), idx.TotalBytes)
|
||||||
|
}
|
||||||
|
if len(progress) < 3 || progress[len(progress)-1] != 1002 {
|
||||||
|
t.Fatalf("progress %v", progress)
|
||||||
|
}
|
||||||
|
if e, _ := idx.Lookup("d/fifo"); e.Mode&os.ModeNamedPipe == 0 {
|
||||||
|
t.Fatalf("fifo %+v", e)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(bg)
|
||||||
|
_, err = BuildIndex(ctx, bytes.NewReader(b), int64(len(b)), TarGz, func(n int) {
|
||||||
|
if n >= 256 {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatalf("cancel: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestZipSlipRejected(t *testing.T) {
|
||||||
|
for _, f := range []Format{Zip, Tar} {
|
||||||
|
idx := index(t, f,
|
||||||
|
file("../evil", "x"),
|
||||||
|
file("/abs/path", "x"),
|
||||||
|
file("a/../../up", "x"),
|
||||||
|
file(`..\win`, "x"),
|
||||||
|
file("C:/drive", "x"),
|
||||||
|
file("ok/./file", "fine"),
|
||||||
|
symlink("esc", "/etc"),
|
||||||
|
file("esc/passwd", "through the link"),
|
||||||
|
file("plainfile", "f"),
|
||||||
|
file("plainfile/child", "under a file"),
|
||||||
|
)
|
||||||
|
if got := fmt.Sprint(paths(idx)); got != "[esc ok ok/file plainfile]" {
|
||||||
|
t.Errorf("%v: kept %s", f, got)
|
||||||
|
}
|
||||||
|
if len(idx.Rejected) != 7 {
|
||||||
|
t.Errorf("%v: rejected %v", f, idx.Rejected)
|
||||||
|
}
|
||||||
|
if idx.TotalBytes != 5 {
|
||||||
|
t.Errorf("%v: total %d", f, idx.TotalBytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A member under a link is rejected whatever the order in the archive.
|
||||||
|
idx := index(t, Tar, file("esc/passwd", "x"), symlink("esc", "/etc"))
|
||||||
|
if fmt.Sprint(paths(idx)) != "[esc]" {
|
||||||
|
t.Fatalf("order-dependent: %v", paths(idx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMemberLimit(t *testing.T) {
|
||||||
|
var ms []member
|
||||||
|
for i := range 11 {
|
||||||
|
ms = append(ms, file(fmt.Sprintf("f%d", i), "abc"))
|
||||||
|
}
|
||||||
|
for _, f := range []Format{Zip, TarGz} {
|
||||||
|
b := makeArchive(t, f, ms...)
|
||||||
|
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 10}, nil); !errors.Is(err, ErrTooManyMembers) {
|
||||||
|
t.Errorf("%v members: %v", f, err)
|
||||||
|
}
|
||||||
|
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxBytes: 30}, nil); !errors.Is(err, ErrTooLarge) {
|
||||||
|
t.Errorf("%v bytes: %v", f, err)
|
||||||
|
}
|
||||||
|
if _, err := BuildIndexLimits(bg, bytes.NewReader(b), int64(len(b)), f, Limits{MaxMembers: 11, MaxBytes: 33}, nil); err != nil {
|
||||||
|
t.Errorf("%v at the limit: %v", f, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// opens counts FS opens of one path.
|
||||||
|
type opens struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
n map[string]int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o *opens) hook(op vfstest.Op, p string) error {
|
||||||
|
if op == vfstest.OpOpen {
|
||||||
|
o.mu.Lock()
|
||||||
|
if o.n == nil {
|
||||||
|
o.n = map[string]int{}
|
||||||
|
}
|
||||||
|
o.n[p]++
|
||||||
|
o.mu.Unlock()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSourceSinglePass(t *testing.T) {
|
||||||
|
for _, name := range []string{"a.tar.gz", "a.zip", "a.tar"} {
|
||||||
|
var ms []member
|
||||||
|
for i := range 50 {
|
||||||
|
ms = append(ms, file(fmt.Sprintf("top/f%02d", i), strings.Repeat("y", i)))
|
||||||
|
}
|
||||||
|
ms = append(ms, symlink("top/ln", "f01"), dir("top/empty/"))
|
||||||
|
arch := writeArchive(t, name, ms...)
|
||||||
|
o := &opens{}
|
||||||
|
fsys := &vfstest.FaultFS{FS: localfs.New(), Hook: o.hook}
|
||||||
|
idx, err := IndexFile(bg, fsys, arch, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dst := t.TempDir()
|
||||||
|
rep := Unpack(bg, fsys, arch, idx, nil, localfs.New(), dst, transfer.DefaultOptions(), transfer.Hooks{})
|
||||||
|
if rep.Err != nil || rep.Done != 51 || rep.Failed != 0 {
|
||||||
|
t.Fatalf("%s: %+v", name, rep)
|
||||||
|
}
|
||||||
|
if o.n[arch] != 2 { // one for the index, one for the unpack
|
||||||
|
t.Fatalf("%s: archive opened %d times, want 2 (one pass per phase)", name, o.n[arch])
|
||||||
|
}
|
||||||
|
b, _ := os.ReadFile(filepath.Join(dst, "top", "f49"))
|
||||||
|
if len(b) != 49 {
|
||||||
|
t.Fatalf("%s: f49 has %d bytes", name, len(b))
|
||||||
|
}
|
||||||
|
if l, _ := os.Readlink(filepath.Join(dst, "top", "ln")); l != "f01" {
|
||||||
|
t.Fatalf("%s: link %q", name, l)
|
||||||
|
}
|
||||||
|
if fi, err := os.Stat(filepath.Join(dst, "top", "empty")); err != nil || !fi.IsDir() {
|
||||||
|
t.Fatalf("%s: empty dir missing", name)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(filepath.Join(dst, "top", "f10")); !fi.ModTime().Equal(mtime) {
|
||||||
|
t.Fatalf("%s: mtime %v", name, fi.ModTime())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNameAndDetect(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
src []string
|
||||||
|
f Format
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{[]string{"foo.tar.gz"}, Zip, "foo.zip"},
|
||||||
|
{[]string{"/x/foo.zip"}, TarGz, "foo.tar.gz"},
|
||||||
|
{[]string{"report.pdf"}, Tar, "report.tar"},
|
||||||
|
{[]string{"photos/"}, Zip, "photos.zip"},
|
||||||
|
{[]string{"/home/u/proj/a", "/home/u/proj/b"}, Zip, "proj.zip"},
|
||||||
|
{[]string{"a", "b"}, Tar, "archive.tar"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
if got := Name(c.src, c.f); got != c.want {
|
||||||
|
t.Errorf("Name(%v, %v) = %q, want %q", c.src, c.f, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, want := range map[string]Format{"a.ZIP": Zip, "a.tgz": TarGz, "a.tar.gz": TarGz, "a.tar": Tar} {
|
||||||
|
if f, ok := DetectFormat(name); !ok || f != want {
|
||||||
|
t.Errorf("DetectFormat(%s) = %v %v", name, f, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := DetectFormat(".zip"); ok {
|
||||||
|
t.Error("bare extension detected")
|
||||||
|
}
|
||||||
|
}
|
||||||
94
internal/archive/member.go
Normal file
94
internal/archive/member.go
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"archive/zip"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// OpenMember opens one regular member for reading. zip members are read
|
||||||
|
// directly; tar and tar.gz are scanned sequentially up to the member
|
||||||
|
// (expensive — meant for preview and single files, bulk extraction uses
|
||||||
|
// NewSource). The returned reader owns the archive file.
|
||||||
|
func OpenMember(ctx context.Context, fsys vfs.FS, archivePath string, idx *Index, p string) (io.ReadCloser, error) {
|
||||||
|
e, ok := idx.Lookup(p)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("%s: %w", p, vfs.ErrNotExist)
|
||||||
|
}
|
||||||
|
if !e.IsRegular() {
|
||||||
|
return nil, fmt.Errorf("%s: not a regular file", p)
|
||||||
|
}
|
||||||
|
file, err := fsys.Open(ctx, archivePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
rc, err := openMember(ctx, file, idx.Format, e.ord)
|
||||||
|
if err != nil {
|
||||||
|
file.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return rc, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func openMember(ctx context.Context, file vfs.File, f Format, ord int) (io.ReadCloser, error) {
|
||||||
|
if f == Zip {
|
||||||
|
fi, err := file.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
zr, err := zip.NewReader(file, fi.Size)
|
||||||
|
if err != nil && !errors.Is(err, zip.ErrInsecurePath) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ord >= len(zr.File) {
|
||||||
|
return nil, fmt.Errorf("archive changed since indexing: %w", vfs.ErrNotExist)
|
||||||
|
}
|
||||||
|
rc, err := zr.File[ord].Open()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return multiCloser{rc, []io.Closer{rc, file}}, nil
|
||||||
|
}
|
||||||
|
var r io.Reader = &ctxReader{ctx: ctx, r: file}
|
||||||
|
closers := []io.Closer{file}
|
||||||
|
if f == TarGz {
|
||||||
|
zr, err := gzip.NewReader(r)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
r = zr
|
||||||
|
closers = append([]io.Closer{zr}, closers...)
|
||||||
|
}
|
||||||
|
tr := tar.NewReader(r)
|
||||||
|
for i := 0; ; i++ {
|
||||||
|
_, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
return nil, fmt.Errorf("archive changed since indexing: %w", vfs.ErrNotExist)
|
||||||
|
}
|
||||||
|
if err != nil && !errors.Is(err, tar.ErrInsecurePath) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if i == ord {
|
||||||
|
return multiCloser{tr, closers}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type multiCloser struct {
|
||||||
|
io.Reader
|
||||||
|
cs []io.Closer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m multiCloser) Close() error {
|
||||||
|
var errs []error
|
||||||
|
for _, c := range m.cs {
|
||||||
|
errs = append(errs, c.Close())
|
||||||
|
}
|
||||||
|
return errors.Join(errs...)
|
||||||
|
}
|
||||||
84
internal/archive/remote_test.go
Normal file
84
internal/archive/remote_test.go
Normal file
|
|
@ -0,0 +1,84 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh/knownhosts"
|
||||||
|
|
||||||
|
"vcom/internal/ssh/conn"
|
||||||
|
"vcom/internal/testutil/fstree"
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
"vcom/internal/transfer"
|
||||||
|
"vcom/internal/vfs/sftpfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// remoteFS starts an in-process SSH/SFTP server and returns an FS on it.
|
||||||
|
// The server shares this machine's file system, so results are checked on
|
||||||
|
// disk.
|
||||||
|
func remoteFS(t *testing.T) *sftpfs.FS {
|
||||||
|
t.Helper()
|
||||||
|
home := sshtest.IsolatedHome(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
kh := filepath.Join(home, ".ssh", "known_hosts")
|
||||||
|
f, err := os.OpenFile(kh, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, k := range srv.HostKeys {
|
||||||
|
_, _ = f.WriteString(knownhosts.Line([]string{knownhosts.Normalize(srv.Addr)}, k.PublicKey()) + "\n")
|
||||||
|
}
|
||||||
|
f.Close()
|
||||||
|
pool := conn.NewPool(conn.PoolOptions{DialOptions: conn.DialOptions{
|
||||||
|
Home: home, AgentSocket: "-", KnownHostsFiles: []string{kh},
|
||||||
|
}})
|
||||||
|
t.Cleanup(func() { pool.Close() })
|
||||||
|
host, port, _ := net.SplitHostPort(srv.Addr)
|
||||||
|
p, _ := strconv.Atoi(port)
|
||||||
|
l, err := pool.Acquire(context.Background(), conn.Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: srv.Password})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
fsys := sftpfs.New(l)
|
||||||
|
t.Cleanup(fsys.Release)
|
||||||
|
return fsys
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P1-15: archiving onto (and from) a remote panel works through vfs.
|
||||||
|
func TestArchiveToRemote(t *testing.T) {
|
||||||
|
remote := remoteFS(t)
|
||||||
|
src := t.TempDir()
|
||||||
|
fstree.Build(t, src, fstree.Spec{
|
||||||
|
fstree.File("proj/a.txt", "alpha"),
|
||||||
|
fstree.File("proj/sub/b.bin", "").WithSize(300 << 10),
|
||||||
|
fstree.Symlink("proj/ln", "a.txt"),
|
||||||
|
})
|
||||||
|
out := t.TempDir()
|
||||||
|
target := filepath.Join(out, "proj.tar.gz")
|
||||||
|
rep := Create(bg, local, []string{filepath.Join(src, "proj")}, remote, target, TarGz, transfer.Hooks{})
|
||||||
|
if rep.Err != nil || rep.Done != 3 {
|
||||||
|
t.Fatalf("local → remote: %+v", rep)
|
||||||
|
}
|
||||||
|
idx, err := IndexFile(bg, remote, target, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if e, ok := idx.Lookup("proj/sub/b.bin"); !ok || e.Size != 300<<10 {
|
||||||
|
t.Fatalf("index %+v", e)
|
||||||
|
}
|
||||||
|
if e, _ := idx.Lookup("proj/ln"); e.Link != "a.txt" {
|
||||||
|
t.Fatalf("link %+v", e)
|
||||||
|
}
|
||||||
|
noTemps(t, out)
|
||||||
|
|
||||||
|
// Remote source → local archive.
|
||||||
|
back := filepath.Join(t.TempDir(), "again.zip")
|
||||||
|
rep = Create(bg, remote, []string{filepath.Join(src, "proj")}, local, back, Zip, transfer.Hooks{})
|
||||||
|
if rep.Err != nil || rep.Done != 3 {
|
||||||
|
t.Fatalf("remote → local: %+v", rep)
|
||||||
|
}
|
||||||
|
}
|
||||||
242
internal/archive/source.go
Normal file
242
internal/archive/source.go
Normal file
|
|
@ -0,0 +1,242 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"archive/zip"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"vcom/internal/transfer"
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IndexFile opens p on fsys, detects the format from the name and builds the
|
||||||
|
// index. It reads the archive once and creates no temp files.
|
||||||
|
func IndexFile(ctx context.Context, fsys vfs.FS, p string, progress func(n int)) (*Index, error) {
|
||||||
|
f, ok := DetectFormat(p)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("archive: %s: unknown archive format", p)
|
||||||
|
}
|
||||||
|
file, err := fsys.Open(ctx, p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
fi, err := file.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return BuildIndex(ctx, file, fi.Size, f, progress)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSource returns a transfer.Source with the given members (archive paths;
|
||||||
|
// nil or empty = the whole archive). A member's Rel starts at its own name,
|
||||||
|
// so extracting "docs/a" yields "a" in the target. Stream reads the archive
|
||||||
|
// in one pass: directories and links come first (from the index), then file
|
||||||
|
// contents in archive order.
|
||||||
|
func NewSource(fsys vfs.FS, archivePath string, idx *Index, members []string) transfer.Source {
|
||||||
|
return &source{fs: fsys, path: archivePath, idx: idx, members: members}
|
||||||
|
}
|
||||||
|
|
||||||
|
type source struct {
|
||||||
|
fs vfs.FS
|
||||||
|
path string
|
||||||
|
idx *Index
|
||||||
|
members []string
|
||||||
|
ordRel map[string]int // Rel of a file item → its ordinal in the archive
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *source) Label() string { return s.fs.Paths().Base(s.path) }
|
||||||
|
|
||||||
|
func (s *source) Walk(ctx context.Context, fn func(transfer.Item) error) error {
|
||||||
|
s.ordRel = map[string]int{}
|
||||||
|
emit := func(e Entry, rel string, root int) error {
|
||||||
|
it := transfer.Item{Rel: rel, Size: e.Size, Mode: e.Mode, ModTime: e.ModTime, LinkTarget: e.Link, Root: root}
|
||||||
|
switch {
|
||||||
|
case e.IsDir():
|
||||||
|
it.Kind = transfer.Dir
|
||||||
|
case e.IsSymlink():
|
||||||
|
it.Kind = transfer.Symlink
|
||||||
|
case e.IsRegular():
|
||||||
|
it.Kind = transfer.File
|
||||||
|
s.ordRel[rel] = e.ord
|
||||||
|
default:
|
||||||
|
it.Kind = transfer.Special
|
||||||
|
}
|
||||||
|
return fn(it)
|
||||||
|
}
|
||||||
|
if len(s.members) == 0 {
|
||||||
|
roots := map[string]int{}
|
||||||
|
for i, e := range s.idx.Entries {
|
||||||
|
if i%256 == 0 {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
top, _, _ := strings.Cut(e.Path, "/")
|
||||||
|
r, ok := roots[top]
|
||||||
|
if !ok {
|
||||||
|
r = len(roots)
|
||||||
|
roots[top] = r
|
||||||
|
}
|
||||||
|
if err := emit(e, e.Path, r); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for r, m := range s.members {
|
||||||
|
m = strings.Trim(path.Clean("/"+m), "/")
|
||||||
|
if _, ok := s.idx.Lookup(m); !ok {
|
||||||
|
return fmt.Errorf("%s: %w", m, vfs.ErrNotExist)
|
||||||
|
}
|
||||||
|
parent := path.Dir(m)
|
||||||
|
cut := 0
|
||||||
|
if parent != "." {
|
||||||
|
cut = len(parent) + 1
|
||||||
|
}
|
||||||
|
for _, e := range s.idx.Entries {
|
||||||
|
if e.Path != m && !strings.HasPrefix(e.Path, m+"/") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := emit(e, e.Path[cut:], r); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *source) Stream(ctx context.Context, items []transfer.Item, fn func(transfer.Item, io.Reader) error) error {
|
||||||
|
wanted := map[int]transfer.Item{}
|
||||||
|
for _, it := range items {
|
||||||
|
if it.Kind == transfer.File {
|
||||||
|
ord, ok := s.ordRel[it.Rel]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("archive: %s is not in the plan of this source", it.Rel)
|
||||||
|
}
|
||||||
|
wanted[ord] = it
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := fn(it, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(wanted) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
file, err := s.fs.Open(ctx, s.path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
switch s.idx.Format {
|
||||||
|
case Zip:
|
||||||
|
err = s.streamZip(ctx, file, wanted, fn)
|
||||||
|
default:
|
||||||
|
err = s.streamTar(ctx, file, wanted, fn)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, it := range wanted { // members that vanished from the archive since indexing
|
||||||
|
if err := fn(it, errReader{fmt.Errorf("%s: %w in the archive", it.Rel, vfs.ErrNotExist)}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *source) streamZip(ctx context.Context, file vfs.File, wanted map[int]transfer.Item, fn func(transfer.Item, io.Reader) error) error {
|
||||||
|
fi, err := file.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
zr, err := zip.NewReader(file, fi.Size)
|
||||||
|
if err != nil && !errors.Is(err, zip.ErrInsecurePath) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for i, zf := range zr.File {
|
||||||
|
it, ok := wanted[i]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
delete(wanted, i)
|
||||||
|
rc, err := zf.Open()
|
||||||
|
if err != nil {
|
||||||
|
if err := fn(it, errReader{err}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
err = fn(it, rc)
|
||||||
|
rc.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *source) streamTar(ctx context.Context, file vfs.File, wanted map[int]transfer.Item, fn func(transfer.Item, io.Reader) error) error {
|
||||||
|
var r io.Reader = &ctxReader{ctx: ctx, r: file}
|
||||||
|
if s.idx.Format == TarGz {
|
||||||
|
zr, err := gzip.NewReader(r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer zr.Close()
|
||||||
|
r = zr
|
||||||
|
}
|
||||||
|
tr := tar.NewReader(r)
|
||||||
|
for i := 0; len(wanted) > 0; i++ {
|
||||||
|
_, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, tar.ErrInsecurePath) {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
it, ok := wanted[i] // i counts headers exactly as BuildIndex does
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
delete(wanted, i)
|
||||||
|
if err := fn(it, tr); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type errReader struct{ err error }
|
||||||
|
|
||||||
|
func (r errReader) Read([]byte) (int, error) { return 0, r.err }
|
||||||
|
|
||||||
|
// Unpack extracts members (nil = all) of the indexed archive into toDir on
|
||||||
|
// any FS through the transfer engine: conflicts are resolved by opts/hooks
|
||||||
|
// instead of silent overwrites, files are written via temp + rename, and an
|
||||||
|
// existing symlink in the target is never written through (U-P1-11).
|
||||||
|
func Unpack(ctx context.Context, fsys vfs.FS, archivePath string, idx *Index, members []string,
|
||||||
|
to vfs.FS, toDir string, opts transfer.Options, h transfer.Hooks) transfer.Report {
|
||||||
|
req := transfer.Request{Op: transfer.Copy, From: NewSource(fsys, archivePath, idx, members), To: to, ToDir: toDir, Opts: opts}
|
||||||
|
plan, err := transfer.Prepare(ctx, req, h.Progress)
|
||||||
|
if err != nil {
|
||||||
|
return transfer.Report{Err: err, Cancelled: ctx.Err() != nil}
|
||||||
|
}
|
||||||
|
return transfer.Execute(ctx, plan, h)
|
||||||
|
}
|
||||||
123
internal/archive/unpack_test.go
Normal file
123
internal/archive/unpack_test.go
Normal file
|
|
@ -0,0 +1,123 @@
|
||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/fstree"
|
||||||
|
"vcom/internal/transfer"
|
||||||
|
)
|
||||||
|
|
||||||
|
// U-P1-11: an existing file is a conflict, not a silent overwrite.
|
||||||
|
func TestUnpackConflictAsks(t *testing.T) {
|
||||||
|
for _, name := range []string{"a.zip", "a.tar.gz"} {
|
||||||
|
arch := writeArchive(t, name, file("top/keep.txt", "from archive"), file("top/new.txt", "n"))
|
||||||
|
idx, err := IndexFile(bg, local, arch, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dst := t.TempDir()
|
||||||
|
fstree.Build(t, dst, fstree.Spec{fstree.File("top/keep.txt", "user data")})
|
||||||
|
var asked []string
|
||||||
|
rep := Unpack(bg, local, arch, idx, nil, local, dst, transfer.DefaultOptions(), transfer.Hooks{
|
||||||
|
Resolve: func(_ context.Context, c transfer.Conflict) (transfer.Resolution, error) {
|
||||||
|
asked = append(asked, c.Item.Rel)
|
||||||
|
return transfer.Resolution{Action: transfer.ResolveSkip}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if len(asked) != 1 || asked[0] != "top/keep.txt" {
|
||||||
|
t.Fatalf("%s: asked %v", name, asked)
|
||||||
|
}
|
||||||
|
if rep.Done != 1 || rep.Skipped != 1 {
|
||||||
|
t.Fatalf("%s: %+v", name, rep)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(filepath.Join(dst, "top", "keep.txt")); string(b) != "user data" {
|
||||||
|
t.Fatalf("%s: existing file overwritten", name)
|
||||||
|
}
|
||||||
|
// Overwrite replaces atomically.
|
||||||
|
rep = Unpack(bg, local, arch, idx, []string{"top/keep.txt"}, local, filepath.Join(dst, "top"),
|
||||||
|
transfer.Options{Conflict: transfer.Overwrite}, transfer.Hooks{})
|
||||||
|
if b, _ := os.ReadFile(filepath.Join(dst, "top", "keep.txt")); rep.Done != 1 || string(b) != "from archive" {
|
||||||
|
t.Fatalf("%s: overwrite %+v %q", name, rep, b)
|
||||||
|
}
|
||||||
|
noTemps(t, filepath.Join(dst, "top"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnpackDoesNotWriteThroughSymlink(t *testing.T) {
|
||||||
|
elsewhere := t.TempDir()
|
||||||
|
arch := writeArchive(t, "a.tar", file("foo/x", "payload"), file("bar", "b"))
|
||||||
|
idx, err := IndexFile(bg, local, arch, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dst := t.TempDir()
|
||||||
|
if err := os.Symlink(elsewhere, filepath.Join(dst, "foo")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, pol := range []transfer.ConflictPolicy{transfer.Overwrite, transfer.Ask, transfer.Skip} {
|
||||||
|
rep := Unpack(bg, local, arch, idx, nil, local, dst, transfer.Options{Conflict: pol}, transfer.Hooks{
|
||||||
|
Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) {
|
||||||
|
return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if rep.Err != nil {
|
||||||
|
t.Fatal(rep.Err)
|
||||||
|
}
|
||||||
|
if ents, _ := os.ReadDir(elsewhere); len(ents) != 0 {
|
||||||
|
t.Fatalf("policy %d: wrote through the symlink: %v", pol, ents)
|
||||||
|
}
|
||||||
|
if fi, err := os.Lstat(filepath.Join(dst, "foo")); err != nil || fi.Mode()&os.ModeSymlink == 0 {
|
||||||
|
t.Fatal("the link itself was replaced")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// KeepBoth puts the directory beside the link.
|
||||||
|
rep := Unpack(bg, local, arch, idx, nil, local, dst, transfer.Options{Conflict: transfer.KeepBoth}, transfer.Hooks{})
|
||||||
|
if b, _ := os.ReadFile(filepath.Join(dst, "foo (1)", "x")); rep.Err != nil || string(b) != "payload" {
|
||||||
|
t.Fatalf("keep both: %+v", rep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P1-15: unpacking into a remote panel goes through the same engine.
|
||||||
|
func TestUnpackToRemote(t *testing.T) {
|
||||||
|
remote := remoteFS(t)
|
||||||
|
arch := writeArchive(t, "a.zip", file("top/a.txt", "alpha"), symlink("top/ln", "a.txt"), dir("top/empty/"))
|
||||||
|
idx, err := IndexFile(bg, local, arch, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dst := t.TempDir()
|
||||||
|
fstree.Build(t, dst, fstree.Spec{fstree.File("top/a.txt", "remote data")})
|
||||||
|
asked := 0
|
||||||
|
rep := Unpack(bg, local, arch, idx, nil, remote, dst, transfer.DefaultOptions(), transfer.Hooks{
|
||||||
|
Resolve: func(context.Context, transfer.Conflict) (transfer.Resolution, error) {
|
||||||
|
asked++
|
||||||
|
return transfer.Resolution{Action: transfer.ResolveOverwrite}, nil
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if rep.Err != nil || rep.Done != 2 || asked != 1 {
|
||||||
|
t.Fatalf("%+v asked=%d", rep, asked)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(filepath.Join(dst, "top", "a.txt")); string(b) != "alpha" {
|
||||||
|
t.Fatalf("content %q", b)
|
||||||
|
}
|
||||||
|
if l, _ := os.Readlink(filepath.Join(dst, "top", "ln")); l != "a.txt" {
|
||||||
|
t.Fatalf("link %q", l)
|
||||||
|
}
|
||||||
|
noTemps(t, filepath.Join(dst, "top"))
|
||||||
|
|
||||||
|
// And from a remote archive into a local directory.
|
||||||
|
arch2 := filepath.Join(dst, "copy.zip")
|
||||||
|
b, _ := os.ReadFile(arch)
|
||||||
|
_ = os.WriteFile(arch2, b, 0o644)
|
||||||
|
idx2, err := IndexFile(bg, remote, arch2, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dst2 := t.TempDir()
|
||||||
|
if rep := Unpack(bg, remote, arch2, idx2, nil, local, dst2, transfer.DefaultOptions(), transfer.Hooks{}); rep.Err != nil || rep.Done != 2 {
|
||||||
|
t.Fatalf("remote archive: %+v", rep)
|
||||||
|
}
|
||||||
|
}
|
||||||
142
internal/atomicfile/atomicfile.go
Normal file
142
internal/atomicfile/atomicfile.go
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
// Package atomicfile replaces local files atomically: temp file in the same
|
||||||
|
// directory → write → fsync → rename → fsync of the directory (design §9.2).
|
||||||
|
// A crash or error at any point leaves either the old file or the new one,
|
||||||
|
// never a truncated mix. Used for the config, the session, hosts.dat and
|
||||||
|
// known_hosts.
|
||||||
|
package atomicfile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WriteFile atomically replaces path with data. See Write.
|
||||||
|
func WriteFile(path string, data []byte, perm fs.FileMode) error {
|
||||||
|
return Write(path, perm, func(w io.Writer) error {
|
||||||
|
_, err := w.Write(data)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write atomically replaces path with what fill writes. If fill (or any later
|
||||||
|
// step) fails, the temp file is removed and path is untouched.
|
||||||
|
//
|
||||||
|
// - If path is a symlink (dotfiles!), the file it points to is replaced and
|
||||||
|
// the link is kept.
|
||||||
|
// - If path exists but is not writable by us (chmod a-w), Write fails with
|
||||||
|
// EACCES like a plain write would, instead of replacing it.
|
||||||
|
// - If path exists, its permission bits are kept (perm is used only for a
|
||||||
|
// new file) and, when running as root, its owner too — so sudo does not
|
||||||
|
// leave a root-owned file in a user's home.
|
||||||
|
func Write(path string, perm fs.FileMode, fill func(w io.Writer) error) (err error) {
|
||||||
|
target, err := resolve(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
uid, gid := -1, -1
|
||||||
|
if fi, err := os.Stat(target); err == nil {
|
||||||
|
if !fi.Mode().IsRegular() {
|
||||||
|
return fmt.Errorf("atomicfile: %s is not a regular file", target)
|
||||||
|
}
|
||||||
|
// A file the user made read-only stays untouched: the rename would
|
||||||
|
// replace it although open(O_WRONLY) is refused (QA-13).
|
||||||
|
if err := unix.Access(target, unix.W_OK); err != nil {
|
||||||
|
return &fs.PathError{Op: "open", Path: target, Err: err}
|
||||||
|
}
|
||||||
|
perm = fi.Mode().Perm()
|
||||||
|
if st, ok := fi.Sys().(*syscall.Stat_t); ok && os.Geteuid() == 0 {
|
||||||
|
uid, gid = int(st.Uid), int(st.Gid)
|
||||||
|
}
|
||||||
|
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dir := filepath.Dir(target)
|
||||||
|
tmp, err := os.CreateTemp(dir, "."+filepath.Base(target)+".tmp-*")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tmpName := tmp.Name()
|
||||||
|
defer func() {
|
||||||
|
if err != nil {
|
||||||
|
tmp.Close()
|
||||||
|
os.Remove(tmpName)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err = tmp.Chmod(perm); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if uid >= 0 {
|
||||||
|
if err = tmp.Chown(uid, gid); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bw := bufio.NewWriter(tmp)
|
||||||
|
if err = fill(bw); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = bw.Flush(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = tmp.Sync(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = tmp.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err = os.Rename(tmpName, target); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
syncDir(dir)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolve follows a symlink at path to the file it names (which may not exist
|
||||||
|
// yet: a dangling link is written through).
|
||||||
|
func resolve(path string) (string, error) {
|
||||||
|
path, err := filepath.Abs(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
for range 40 {
|
||||||
|
fi, err := os.Lstat(path)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if fi.Mode()&fs.ModeSymlink == 0 {
|
||||||
|
return path, nil
|
||||||
|
}
|
||||||
|
link, err := os.Readlink(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if !filepath.IsAbs(link) {
|
||||||
|
link = filepath.Join(filepath.Dir(path), link)
|
||||||
|
}
|
||||||
|
path = link
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("atomicfile: %s: too many levels of symbolic links", path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncDir makes the rename durable. Some file systems refuse fsync on a
|
||||||
|
// directory; that is not worth failing the write for.
|
||||||
|
func syncDir(dir string) {
|
||||||
|
d, err := os.Open(dir)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = d.Sync()
|
||||||
|
d.Close()
|
||||||
|
}
|
||||||
120
internal/atomicfile/atomicfile_test.go
Normal file
120
internal/atomicfile/atomicfile_test.go
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
package atomicfile
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func names(t *testing.T, dir string) []string {
|
||||||
|
t.Helper()
|
||||||
|
ents, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out []string
|
||||||
|
for _, e := range ents {
|
||||||
|
out = append(out, e.Name())
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteCrashLeavesOld(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "session.toml")
|
||||||
|
if err := os.WriteFile(p, []byte("old content"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
boom := errors.New("disk full")
|
||||||
|
err := Write(p, 0o644, func(w io.Writer) error {
|
||||||
|
_, _ = io.WriteString(w, "half of the new")
|
||||||
|
return boom
|
||||||
|
})
|
||||||
|
if !errors.Is(err, boom) {
|
||||||
|
t.Fatalf("err = %v", err)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(p); string(b) != "old content" {
|
||||||
|
t.Fatalf("old file damaged: %q", b)
|
||||||
|
}
|
||||||
|
if n := names(t, dir); len(n) != 1 {
|
||||||
|
t.Fatalf("temp file left behind: %v", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteReplacesAndKeepsMode(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "f")
|
||||||
|
if err := WriteFile(p, []byte("one"), 0o640); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o640 {
|
||||||
|
t.Fatalf("new file mode %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
if err := os.Chmod(p, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := WriteFile(p, []byte("two"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(p); string(b) != "two" {
|
||||||
|
t.Fatalf("content %q", b)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("existing mode not kept: %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
if n := names(t, dir); len(n) != 1 {
|
||||||
|
t.Fatalf("leftovers: %v", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteThroughSymlink(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
real := filepath.Join(dir, "dotfiles", "vcom.toml")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(real), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(real, []byte("old"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
link := filepath.Join(dir, "vcom.toml")
|
||||||
|
if err := os.Symlink("dotfiles/vcom.toml", link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := WriteFile(link, []byte("new"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 {
|
||||||
|
t.Fatal("symlink replaced by a regular file")
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(real); string(b) != "new" {
|
||||||
|
t.Fatalf("target content %q", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteRefusesDirectory(t *testing.T) {
|
||||||
|
if err := WriteFile(t.TempDir(), []byte("x"), 0o644); err == nil {
|
||||||
|
t.Fatal("writing over a directory must fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAtomicWriteRefusesReadOnlyFile(t *testing.T) {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("root may write anything")
|
||||||
|
}
|
||||||
|
p := filepath.Join(t.TempDir(), "ro")
|
||||||
|
if err := os.WriteFile(p, []byte("keep"), 0o444); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
err := WriteFile(p, []byte("new"), 0o644)
|
||||||
|
if !errors.Is(err, os.ErrPermission) {
|
||||||
|
t.Fatalf("err = %v, want EACCES", err)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(p); string(b) != "keep" {
|
||||||
|
t.Fatalf("read-only file replaced: %q", b)
|
||||||
|
}
|
||||||
|
if n := names(t, filepath.Dir(p)); len(n) != 1 {
|
||||||
|
t.Fatalf("leftovers %v", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,16 +1,15 @@
|
||||||
|
// Package config holds the vcom.toml schema, loading and the in-place
|
||||||
|
// SetKey edit (design §9.2).
|
||||||
|
//
|
||||||
|
// Loading never aborts the program: a broken file yields Default() plus an
|
||||||
|
// error for the status line; unknown or deprecated keys yield warnings; an
|
||||||
|
// invalid value is replaced by its default with a warning.
|
||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"time"
|
||||||
|
|
||||||
toml "github.com/pelletier/go-toml/v2"
|
|
||||||
|
|
||||||
"vcom/internal/homedir"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
|
|
@ -19,6 +18,8 @@ type Config struct {
|
||||||
Browser BrowserConfig `toml:"browser"`
|
Browser BrowserConfig `toml:"browser"`
|
||||||
Preview PreviewConfig `toml:"preview"`
|
Preview PreviewConfig `toml:"preview"`
|
||||||
Behavior BehaviorConfig `toml:"behavior"`
|
Behavior BehaviorConfig `toml:"behavior"`
|
||||||
|
Transfer TransferConfig `toml:"transfer"`
|
||||||
|
SSH SSHConfig `toml:"ssh"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type StartupConfig struct {
|
type StartupConfig struct {
|
||||||
|
|
@ -27,15 +28,18 @@ type StartupConfig struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
type UIConfig struct {
|
type UIConfig struct {
|
||||||
AppTitle string `toml:"app_title"`
|
// AppTitle is deprecated (warning when set); only the old UI still shows
|
||||||
Theme string `toml:"theme"`
|
// it. It goes away with the old UI in stage 7.
|
||||||
IconMode string `toml:"icon_mode"`
|
AppTitle string `toml:"app_title"`
|
||||||
ShowTitleBar bool `toml:"show_title_bar"`
|
Theme string `toml:"theme"`
|
||||||
ShowFooter bool `toml:"show_footer"`
|
IconMode string `toml:"icon_mode"`
|
||||||
Border string `toml:"border"`
|
ShowFooter bool `toml:"show_footer"`
|
||||||
PathDisplay string `toml:"path_display"`
|
Border string `toml:"border"`
|
||||||
PaneGap int `toml:"pane_gap"`
|
PathDisplay string `toml:"path_display"`
|
||||||
CenterWidthPercent int `toml:"center_width_percent"`
|
PaneGap int `toml:"pane_gap"`
|
||||||
|
// PreviewWidthPercent is the preview width in the Info screen. The old
|
||||||
|
// name center_width_percent is accepted as an alias with a warning.
|
||||||
|
PreviewWidthPercent int `toml:"preview_width_percent"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type BrowserConfig struct {
|
type BrowserConfig struct {
|
||||||
|
|
@ -65,211 +69,159 @@ type PreviewConfig struct {
|
||||||
WrapText bool `toml:"wrap_text"`
|
WrapText bool `toml:"wrap_text"`
|
||||||
MaxPreviewBytes int64 `toml:"max_preview_bytes"`
|
MaxPreviewBytes int64 `toml:"max_preview_bytes"`
|
||||||
DirectoryPreviewLimit int `toml:"directory_preview_limit"`
|
DirectoryPreviewLimit int `toml:"directory_preview_limit"`
|
||||||
|
// ImageBackend: auto | kitty | ueberzugpp | none.
|
||||||
|
ImageBackend string `toml:"image_backend"`
|
||||||
|
// MaxRemoteImageBytes: larger remote images are not downloaded for preview.
|
||||||
|
MaxRemoteImageBytes int64 `toml:"max_remote_image_bytes"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type BehaviorConfig struct {
|
type BehaviorConfig struct {
|
||||||
ConfirmDelete bool `toml:"confirm_delete"`
|
ConfirmDelete bool `toml:"confirm_delete"` // asks before moving to the trash
|
||||||
ConfirmOverwrite bool `toml:"confirm_overwrite"`
|
ConfirmOverwrite bool `toml:"confirm_overwrite"`
|
||||||
CalculateDirSizeOnSpace bool `toml:"calculate_dir_size_on_space"`
|
CalculateDirSizeOnSpace bool `toml:"calculate_dir_size_on_space"`
|
||||||
FollowSymlinks bool `toml:"follow_symlinks"`
|
FollowSymlinks bool `toml:"follow_symlinks"` // default of the transfer dialog
|
||||||
|
ConfirmQuit bool `toml:"confirm_quit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type TransferConfig struct {
|
||||||
|
OnConflict string `toml:"on_conflict"` // ask | overwrite | skip | newer | rename
|
||||||
|
Preserve bool `toml:"preserve"` // keep mode and mtime
|
||||||
|
Fsync string `toml:"fsync"` // replace | always | never
|
||||||
|
MaxParallelJobs int `toml:"max_parallel_jobs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type SSHConfig struct {
|
||||||
|
KeepaliveInterval Duration `toml:"keepalive_interval"`
|
||||||
|
ConnectTimeout Duration `toml:"connect_timeout"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duration is a time.Duration written as a Go duration string ("15s").
|
||||||
|
type Duration struct{ time.Duration }
|
||||||
|
|
||||||
|
func (d Duration) MarshalText() ([]byte, error) { return []byte(d.String()), nil }
|
||||||
|
|
||||||
|
func (d *Duration) UnmarshalText(b []byte) error {
|
||||||
|
v, err := time.ParseDuration(string(b))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
d.Duration = v
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func Default() Config {
|
func Default() Config {
|
||||||
return Config{
|
return Config{
|
||||||
Startup: StartupConfig{},
|
|
||||||
UI: UIConfig{
|
UI: UIConfig{
|
||||||
AppTitle: "vcom",
|
AppTitle: "vcom",
|
||||||
Theme: "catppuccin-mocha",
|
Theme: "catppuccin-mocha",
|
||||||
IconMode: "auto",
|
IconMode: "auto",
|
||||||
ShowTitleBar: true,
|
ShowFooter: true,
|
||||||
ShowFooter: true,
|
Border: "rounded",
|
||||||
Border: "rounded",
|
PathDisplay: "short",
|
||||||
PathDisplay: "short",
|
PaneGap: 1,
|
||||||
PaneGap: 1,
|
PreviewWidthPercent: 50,
|
||||||
CenterWidthPercent: 30,
|
|
||||||
},
|
},
|
||||||
Browser: BrowserConfig{
|
Browser: BrowserConfig{
|
||||||
ShowHidden: true,
|
ShowHidden: true,
|
||||||
DirsFirst: true,
|
DirsFirst: true,
|
||||||
HumanReadableSize: true,
|
HumanReadableSize: true,
|
||||||
Sort: SortConfig{
|
Sort: SortConfig{By: "name"},
|
||||||
By: "name",
|
Columns: BrowserColumnsConfig{Name: true, Size: true, Modified: true},
|
||||||
Reverse: false,
|
|
||||||
},
|
|
||||||
Columns: BrowserColumnsConfig{
|
|
||||||
Name: true,
|
|
||||||
Size: true,
|
|
||||||
Modified: true,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
Preview: PreviewConfig{
|
Preview: PreviewConfig{
|
||||||
ShowMetadata: true,
|
ShowMetadata: true,
|
||||||
WrapText: false,
|
|
||||||
MaxPreviewBytes: 64 * 1024,
|
MaxPreviewBytes: 64 * 1024,
|
||||||
DirectoryPreviewLimit: 80,
|
DirectoryPreviewLimit: 80,
|
||||||
|
ImageBackend: "auto",
|
||||||
|
MaxRemoteImageBytes: 20 << 20,
|
||||||
},
|
},
|
||||||
Behavior: BehaviorConfig{
|
Behavior: BehaviorConfig{
|
||||||
ConfirmDelete: true,
|
ConfirmDelete: true,
|
||||||
ConfirmOverwrite: true,
|
ConfirmOverwrite: true,
|
||||||
CalculateDirSizeOnSpace: true,
|
CalculateDirSizeOnSpace: true,
|
||||||
FollowSymlinks: false,
|
ConfirmQuit: true,
|
||||||
|
},
|
||||||
|
Transfer: TransferConfig{
|
||||||
|
OnConflict: "ask",
|
||||||
|
Preserve: true,
|
||||||
|
Fsync: "replace",
|
||||||
|
MaxParallelJobs: 2,
|
||||||
|
},
|
||||||
|
SSH: SSHConfig{
|
||||||
|
KeepaliveInterval: Duration{15 * time.Second},
|
||||||
|
ConnectTimeout: Duration{20 * time.Second},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load(explicitPath string) (Config, string, error) {
|
// Validate normalises c and replaces invalid values with their defaults. It
|
||||||
cfg := Default()
|
// returns one warning per replaced value; it never fails.
|
||||||
|
func (c *Config) Validate() []string {
|
||||||
path, found, err := resolvePath(explicitPath)
|
d := Default()
|
||||||
if err != nil {
|
var warns []string
|
||||||
return Config{}, "", err
|
reset := func(key string, got any, fix func()) {
|
||||||
|
warns = append(warns, fmt.Sprintf("%s: invalid value %v, using the default", key, got))
|
||||||
|
fix()
|
||||||
}
|
}
|
||||||
if !found {
|
oneOf := func(key string, v *string, def string, allowed ...string) {
|
||||||
return cfg, "", nil
|
s := strings.ToLower(strings.TrimSpace(*v))
|
||||||
}
|
if s == "" {
|
||||||
|
*v = def
|
||||||
data, err := os.ReadFile(path)
|
return
|
||||||
if err != nil {
|
|
||||||
return Config{}, "", fmt.Errorf("read %s: %w", path, err)
|
|
||||||
}
|
|
||||||
if err := toml.Unmarshal(data, &cfg); err != nil {
|
|
||||||
return Config{}, "", fmt.Errorf("parse %s: %w", path, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := cfg.Validate(); err != nil {
|
|
||||||
return Config{}, "", fmt.Errorf("validate %s: %w", path, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return cfg, path, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func Save(cfg Config, path string) (string, error) {
|
|
||||||
if err := cfg.Validate(); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
targetPath := strings.TrimSpace(path)
|
|
||||||
if targetPath == "" {
|
|
||||||
var err error
|
|
||||||
targetPath, err = DefaultUserPath()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
}
|
||||||
|
for _, a := range allowed {
|
||||||
|
if s == a {
|
||||||
|
*v = s
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reset(key, *v, func() { *v = def })
|
||||||
}
|
}
|
||||||
|
|
||||||
absPath, err := filepath.Abs(targetPath)
|
if strings.TrimSpace(c.UI.Theme) == "" {
|
||||||
if err != nil {
|
c.UI.Theme = d.UI.Theme
|
||||||
return "", fmt.Errorf("resolve %s: %w", targetPath, err)
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil {
|
|
||||||
return "", fmt.Errorf("mkdir %s: %w", filepath.Dir(absPath), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := toml.Marshal(cfg)
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("marshal config: %w", err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(absPath, data, 0o644); err != nil {
|
|
||||||
return "", fmt.Errorf("write %s: %w", absPath, err)
|
|
||||||
}
|
|
||||||
return absPath, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) Validate() error {
|
|
||||||
if c.UI.Theme == "" {
|
|
||||||
return errors.New("ui.theme must not be empty")
|
|
||||||
}
|
|
||||||
switch strings.ToLower(strings.TrimSpace(c.UI.IconMode)) {
|
|
||||||
case "", "auto":
|
|
||||||
c.UI.IconMode = "auto"
|
|
||||||
case "nerd", "ascii":
|
|
||||||
default:
|
|
||||||
return errors.New("ui.icon_mode must be one of: auto, nerd, ascii")
|
|
||||||
}
|
}
|
||||||
if strings.TrimSpace(c.UI.AppTitle) == "" {
|
if strings.TrimSpace(c.UI.AppTitle) == "" {
|
||||||
c.UI.AppTitle = "vcom"
|
c.UI.AppTitle = d.UI.AppTitle
|
||||||
}
|
|
||||||
if c.Preview.MaxPreviewBytes <= 0 {
|
|
||||||
return errors.New("preview.max_preview_bytes must be > 0")
|
|
||||||
}
|
|
||||||
if c.Preview.DirectoryPreviewLimit <= 0 {
|
|
||||||
return errors.New("preview.directory_preview_limit must be > 0")
|
|
||||||
}
|
|
||||||
if !c.Browser.Columns.Name {
|
|
||||||
return errors.New("browser.columns.name must stay enabled")
|
|
||||||
}
|
}
|
||||||
|
oneOf("ui.icon_mode", &c.UI.IconMode, "auto", "auto", "nerd", "ascii")
|
||||||
if strings.TrimSpace(c.UI.PathDisplay) == "" {
|
if strings.TrimSpace(c.UI.PathDisplay) == "" {
|
||||||
c.UI.PathDisplay = "short"
|
c.UI.PathDisplay = d.UI.PathDisplay
|
||||||
}
|
}
|
||||||
if c.UI.PaneGap < 0 || c.UI.PaneGap > 4 {
|
if c.UI.PaneGap < 0 || c.UI.PaneGap > 4 {
|
||||||
return errors.New("ui.pane_gap must be between 0 and 4")
|
reset("ui.pane_gap", c.UI.PaneGap, func() { c.UI.PaneGap = d.UI.PaneGap })
|
||||||
}
|
}
|
||||||
if c.UI.CenterWidthPercent < 20 || c.UI.CenterWidthPercent > 60 {
|
if c.UI.PreviewWidthPercent < 20 || c.UI.PreviewWidthPercent > 80 {
|
||||||
return errors.New("ui.center_width_percent must be between 20 and 60")
|
reset("ui.preview_width_percent", c.UI.PreviewWidthPercent, func() { c.UI.PreviewWidthPercent = d.UI.PreviewWidthPercent })
|
||||||
}
|
}
|
||||||
switch strings.ToLower(strings.TrimSpace(c.Browser.Sort.By)) {
|
oneOf("browser.sort.by", &c.Browser.Sort.By, "name", "name", "modified", "size", "created", "extension")
|
||||||
case "", "name":
|
if !c.Browser.Columns.Name {
|
||||||
c.Browser.Sort.By = "name"
|
reset("browser.columns.name", false, func() { c.Browser.Columns.Name = true })
|
||||||
case "modified", "size", "created", "extension":
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("browser.sort.by must be one of: name, modified, size, created, extension")
|
|
||||||
}
|
}
|
||||||
return nil
|
if c.Preview.MaxPreviewBytes <= 0 {
|
||||||
}
|
reset("preview.max_preview_bytes", c.Preview.MaxPreviewBytes, func() { c.Preview.MaxPreviewBytes = d.Preview.MaxPreviewBytes })
|
||||||
|
}
|
||||||
func resolvePath(explicitPath string) (string, bool, error) {
|
if c.Preview.DirectoryPreviewLimit <= 0 {
|
||||||
var candidates []string
|
reset("preview.directory_preview_limit", c.Preview.DirectoryPreviewLimit, func() {
|
||||||
|
c.Preview.DirectoryPreviewLimit = d.Preview.DirectoryPreviewLimit
|
||||||
if explicitPath != "" {
|
})
|
||||||
candidates = append(candidates, explicitPath)
|
}
|
||||||
} else {
|
oneOf("preview.image_backend", &c.Preview.ImageBackend, "auto", "auto", "kitty", "ueberzugpp", "none")
|
||||||
homeDir := homedir.Dir()
|
if c.Preview.MaxRemoteImageBytes < 0 {
|
||||||
if homeDir == "" {
|
reset("preview.max_remote_image_bytes", c.Preview.MaxRemoteImageBytes, func() {
|
||||||
return "", false, fmt.Errorf("cannot determine home directory")
|
c.Preview.MaxRemoteImageBytes = d.Preview.MaxRemoteImageBytes
|
||||||
}
|
})
|
||||||
xdgDir := os.Getenv("XDG_CONFIG_HOME")
|
}
|
||||||
if xdgDir == "" {
|
oneOf("transfer.on_conflict", &c.Transfer.OnConflict, "ask", "ask", "overwrite", "skip", "newer", "rename")
|
||||||
xdgDir = filepath.Join(homeDir, ".config")
|
oneOf("transfer.fsync", &c.Transfer.Fsync, "replace", "replace", "always", "never")
|
||||||
}
|
if c.Transfer.MaxParallelJobs < 1 || c.Transfer.MaxParallelJobs > 16 {
|
||||||
|
reset("transfer.max_parallel_jobs", c.Transfer.MaxParallelJobs, func() { c.Transfer.MaxParallelJobs = d.Transfer.MaxParallelJobs })
|
||||||
candidates = append(candidates,
|
}
|
||||||
"vcom.toml",
|
if c.SSH.KeepaliveInterval.Duration < time.Second {
|
||||||
filepath.Join("config", "vcom.toml"),
|
reset("ssh.keepalive_interval", c.SSH.KeepaliveInterval, func() { c.SSH.KeepaliveInterval = d.SSH.KeepaliveInterval })
|
||||||
filepath.Join(xdgDir, "vcom", "vcom.toml"),
|
}
|
||||||
filepath.Join(homeDir, ".config", "vcom", "vcom.toml"),
|
if c.SSH.ConnectTimeout.Duration < time.Second {
|
||||||
)
|
reset("ssh.connect_timeout", c.SSH.ConnectTimeout, func() { c.SSH.ConnectTimeout = d.SSH.ConnectTimeout })
|
||||||
}
|
}
|
||||||
|
return warns
|
||||||
for _, candidate := range candidates {
|
|
||||||
if candidate == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
absPath, err := filepath.Abs(candidate)
|
|
||||||
if err != nil {
|
|
||||||
return "", false, fmt.Errorf("resolve %s: %w", candidate, err)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(absPath); err == nil {
|
|
||||||
return absPath, true, nil
|
|
||||||
} else if !isMissingPathError(err) {
|
|
||||||
return "", false, fmt.Errorf("stat %s: %w", absPath, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return "", false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isMissingPathError(err error) bool {
|
|
||||||
return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR)
|
|
||||||
}
|
|
||||||
|
|
||||||
func DefaultUserPath() (string, error) {
|
|
||||||
homeDir := homedir.Dir()
|
|
||||||
if homeDir == "" {
|
|
||||||
return "", fmt.Errorf("cannot determine home directory")
|
|
||||||
}
|
|
||||||
xdgDir := os.Getenv("XDG_CONFIG_HOME")
|
|
||||||
if xdgDir == "" {
|
|
||||||
xdgDir = filepath.Join(homeDir, ".config")
|
|
||||||
}
|
|
||||||
return filepath.Join(xdgDir, "vcom", "vcom.toml"), nil
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
148
internal/config/config_test.go
Normal file
148
internal/config/config_test.go
Normal file
|
|
@ -0,0 +1,148 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDefaultsValid(t *testing.T) {
|
||||||
|
c := Default()
|
||||||
|
if w := c.Validate(); len(w) != 0 {
|
||||||
|
t.Fatalf("defaults produce warnings: %v", w)
|
||||||
|
}
|
||||||
|
// New keys from design §9.2.
|
||||||
|
if !c.Behavior.ConfirmQuit || c.Transfer.OnConflict != "ask" || !c.Transfer.Preserve ||
|
||||||
|
c.Transfer.Fsync != "replace" || c.Transfer.MaxParallelJobs != 2 || c.Preview.ImageBackend != "auto" ||
|
||||||
|
c.Preview.MaxRemoteImageBytes != 20<<20 || c.SSH.KeepaliveInterval.Duration != 15*time.Second ||
|
||||||
|
c.SSH.ConnectTimeout.Duration != 20*time.Second || c.UI.PreviewWidthPercent != 50 {
|
||||||
|
t.Fatalf("defaults: %+v", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReferenceConfigParsesClean(t *testing.T) {
|
||||||
|
data, err := os.ReadFile("../../vcom.toml")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c, warns, err := Parse(data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(warns) != 0 {
|
||||||
|
t.Fatalf("reference vcom.toml produces warnings: %v", warns)
|
||||||
|
}
|
||||||
|
if c.UI.Theme != "github-dark" || c.SSH.ConnectTimeout.Duration != 20*time.Second {
|
||||||
|
t.Fatalf("parsed %+v", c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadUnknownKeysWarns(t *testing.T) {
|
||||||
|
data := []byte(`
|
||||||
|
[ui]
|
||||||
|
theme = "nord"
|
||||||
|
show_title_bar = true
|
||||||
|
app_title = "x"
|
||||||
|
center_width_percent = 40
|
||||||
|
mystery = 1
|
||||||
|
|
||||||
|
[behavior]
|
||||||
|
auto_refresh = true
|
||||||
|
auto_refresh_interval = 5
|
||||||
|
|
||||||
|
[nosuchsection]
|
||||||
|
k = "v"
|
||||||
|
|
||||||
|
[ssh]
|
||||||
|
connect_timeout = "7s"
|
||||||
|
`)
|
||||||
|
c, warns, err := Parse(data)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
joined := strings.Join(warns, "\n")
|
||||||
|
for _, want := range []string{
|
||||||
|
"unknown key ui.mystery",
|
||||||
|
"unknown key nosuchsection",
|
||||||
|
"ui.show_title_bar",
|
||||||
|
"ui.app_title",
|
||||||
|
"ui.center_width_percent is renamed to ui.preview_width_percent",
|
||||||
|
"behavior.auto_refresh is not implemented",
|
||||||
|
"behavior.auto_refresh_interval",
|
||||||
|
} {
|
||||||
|
if !strings.Contains(joined, want) {
|
||||||
|
t.Errorf("missing warning %q in:\n%s", want, joined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.UI.Theme != "nord" || c.SSH.ConnectTimeout.Duration != 7*time.Second {
|
||||||
|
t.Fatalf("known keys not applied: %+v", c)
|
||||||
|
}
|
||||||
|
if c.UI.PreviewWidthPercent != 40 {
|
||||||
|
t.Fatalf("alias center_width_percent not applied: %d", c.UI.PreviewWidthPercent)
|
||||||
|
}
|
||||||
|
// The new name wins over the alias.
|
||||||
|
c, _, _ = Parse([]byte("[ui]\ncenter_width_percent = 40\npreview_width_percent = 60\n"))
|
||||||
|
if c.UI.PreviewWidthPercent != 60 {
|
||||||
|
t.Fatalf("preview_width_percent = %d", c.UI.PreviewWidthPercent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadInvalidValueUsesDefault(t *testing.T) {
|
||||||
|
c, warns, err := Parse([]byte("[ui]\npane_gap = 9\nicon_mode = 'weird'\n[transfer]\nfsync = 'sometimes'\n"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
d := Default()
|
||||||
|
if c.UI.PaneGap != d.UI.PaneGap || c.UI.IconMode != "auto" || c.Transfer.Fsync != "replace" {
|
||||||
|
t.Fatalf("invalid values not reset: %+v", c)
|
||||||
|
}
|
||||||
|
if len(warns) != 3 {
|
||||||
|
t.Fatalf("warnings: %v", warns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadBrokenConfigFallsBackToDefaults(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "vcom.toml")
|
||||||
|
if err := os.WriteFile(p, []byte("[ui]\ntheme = \"nord\"\nborder = \n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c, info, err := Load(p)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("broken config must return an error")
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), "line 3") {
|
||||||
|
t.Errorf("error should point at the line: %v", err)
|
||||||
|
}
|
||||||
|
if c != Default() {
|
||||||
|
t.Fatalf("got %+v, want defaults", c)
|
||||||
|
}
|
||||||
|
if !info.Found || info.Path != p {
|
||||||
|
t.Fatalf("info %+v", info)
|
||||||
|
}
|
||||||
|
// A missing explicit file: defaults, no error.
|
||||||
|
c, info, err = Load(filepath.Join(dir, "none.toml"))
|
||||||
|
if err != nil || info.Found || c != Default() {
|
||||||
|
t.Fatalf("missing file: %+v %+v %v", c, info, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLoadIgnoresCwdConfig(t *testing.T) {
|
||||||
|
cwd := t.TempDir()
|
||||||
|
if err := os.WriteFile(filepath.Join(cwd, "vcom.toml"), []byte("[ui]\ntheme = 'nord'\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Chdir(cwd)
|
||||||
|
t.Setenv("HOME", t.TempDir())
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", "")
|
||||||
|
t.Setenv("VCOM_CONFIG", "")
|
||||||
|
c, info, err := Load("")
|
||||||
|
if err != nil || info.Found || c.UI.Theme == "nord" {
|
||||||
|
t.Fatalf("cwd config was used: %+v %+v %v", c.UI, info, err)
|
||||||
|
}
|
||||||
|
if len(info.Warnings) != 1 || !strings.Contains(info.Warnings[0], "not loaded") {
|
||||||
|
t.Fatalf("expected a hint about ./vcom.toml, got %v", info.Warnings)
|
||||||
|
}
|
||||||
|
}
|
||||||
133
internal/config/lookup.go
Normal file
133
internal/config/lookup.go
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
toml "github.com/pelletier/go-toml/v2"
|
||||||
|
|
||||||
|
"vcom/internal/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LoadInfo describes where the config came from.
|
||||||
|
type LoadInfo struct {
|
||||||
|
// Path is the file that was read, or — when Found is false — where
|
||||||
|
// SetKey would create one.
|
||||||
|
Path string
|
||||||
|
Found bool
|
||||||
|
// Warnings: unknown/deprecated keys, replaced invalid values, a stray
|
||||||
|
// ./vcom.toml that is no longer loaded.
|
||||||
|
Warnings []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// deprecated keys: accepted, ignored (or aliased), reported.
|
||||||
|
var deprecated = map[string]string{
|
||||||
|
"ui.show_title_bar": "ui.show_title_bar is no longer used and is ignored",
|
||||||
|
"ui.center_width_percent": "ui.center_width_percent is renamed to ui.preview_width_percent",
|
||||||
|
"behavior.auto_refresh": "behavior.auto_refresh is not implemented and is ignored",
|
||||||
|
"behavior.auto_refresh_interval": "behavior.auto_refresh_interval is not implemented and is ignored",
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads the config found by paths.ConfigFile(explicit). It never fails
|
||||||
|
// hard: on a read or parse error it returns Default() and the error, and the
|
||||||
|
// caller starts anyway and shows the error.
|
||||||
|
func Load(explicit string) (Config, LoadInfo, error) {
|
||||||
|
cfg := Default()
|
||||||
|
path, found, err := paths.ConfigFile(explicit)
|
||||||
|
info := LoadInfo{Path: path, Found: found}
|
||||||
|
if err != nil {
|
||||||
|
return cfg, info, fmt.Errorf("config: %w", err)
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
if stray, ok := paths.StrayCwdConfig(); ok {
|
||||||
|
info.Warnings = append(info.Warnings, fmt.Sprintf(
|
||||||
|
"%s is not loaded any more; move it to %s or pass -config", stray, path))
|
||||||
|
}
|
||||||
|
return cfg, info, nil
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return cfg, info, fmt.Errorf("config: %w", err)
|
||||||
|
}
|
||||||
|
c, warns, err := Parse(data)
|
||||||
|
info.Warnings = append(info.Warnings, warns...)
|
||||||
|
if err != nil {
|
||||||
|
return cfg, info, fmt.Errorf("config %s: %w (using defaults)", path, err)
|
||||||
|
}
|
||||||
|
return c, info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse decodes a config file on top of Default(), applies aliases, reports
|
||||||
|
// unknown and deprecated keys and validates values.
|
||||||
|
func Parse(data []byte) (Config, []string, error) {
|
||||||
|
cfg := Default()
|
||||||
|
if err := toml.Unmarshal(data, &cfg); err != nil {
|
||||||
|
return Default(), nil, describe(err)
|
||||||
|
}
|
||||||
|
var raw map[string]any
|
||||||
|
_ = toml.Unmarshal(data, &raw) // cannot fail after the decode above
|
||||||
|
|
||||||
|
var warns []string
|
||||||
|
present := func(key string) (any, bool) {
|
||||||
|
var cur any = raw
|
||||||
|
for _, part := range strings.Split(key, ".") {
|
||||||
|
m, ok := cur.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if cur, ok = m[part]; !ok {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cur, true
|
||||||
|
}
|
||||||
|
if v, ok := present("ui.center_width_percent"); ok {
|
||||||
|
if _, set := present("ui.preview_width_percent"); !set {
|
||||||
|
if n, ok := v.(int64); ok {
|
||||||
|
cfg.UI.PreviewWidthPercent = int(n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, ok := present("ui.app_title"); ok {
|
||||||
|
warns = append(warns, "ui.app_title is deprecated and will be ignored by the new UI")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Strict pass: only for the list of unknown keys.
|
||||||
|
var strict Config
|
||||||
|
dec := toml.NewDecoder(bytes.NewReader(data)).DisallowUnknownFields()
|
||||||
|
var sme *toml.StrictMissingError
|
||||||
|
if err := dec.Decode(&strict); errors.As(err, &sme) {
|
||||||
|
var unknown []string
|
||||||
|
for _, e := range sme.Errors {
|
||||||
|
key := strings.Join(e.Key(), ".")
|
||||||
|
if msg, ok := deprecated[key]; ok {
|
||||||
|
warns = append(warns, msg)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
unknown = append(unknown, key)
|
||||||
|
}
|
||||||
|
sort.Strings(unknown)
|
||||||
|
for _, k := range unknown {
|
||||||
|
warns = append(warns, fmt.Sprintf("unknown key %s (ignored)", k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
warns = append(warns, cfg.Validate()...)
|
||||||
|
return cfg, warns, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// describe adds the line/column go-toml knows to a decode error.
|
||||||
|
func describe(err error) error {
|
||||||
|
var de *toml.DecodeError
|
||||||
|
if errors.As(err, &de) {
|
||||||
|
row, col := de.Position()
|
||||||
|
return fmt.Errorf("line %d, column %d: %w", row, col, err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultUserPath is where a new config file is created.
|
||||||
|
func DefaultUserPath() (string, error) { return paths.DefaultConfigFile() }
|
||||||
189
internal/config/qa_rc2_test.go
Normal file
189
internal/config/qa_rc2_test.go
Normal file
|
|
@ -0,0 +1,189 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
// QA (v0.2.8 RC2): config loading and SetKey (stage 2C) from the user's
|
||||||
|
// side: symlinked/read-only/odd configs must never be lost or corrupted.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func qaIsolate(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
home := t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||||
|
t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state"))
|
||||||
|
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||||
|
t.Setenv("VCOM_CONFIG", "")
|
||||||
|
return home
|
||||||
|
}
|
||||||
|
|
||||||
|
func qaWrite(t *testing.T, p, s string, mode os.FileMode) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte(s), mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(p, mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dotfiles: the config is a symlink into a dotfiles repo. The link stays,
|
||||||
|
// the target gets the new theme, comments survive.
|
||||||
|
func TestQASetKeyThroughSymlink(t *testing.T) {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
target := filepath.Join(home, "dotfiles", "vcom.toml")
|
||||||
|
qaWrite(t, target, "# mine\n[ui]\ntheme = \"old\" # c\n", 0o640)
|
||||||
|
link := filepath.Join(home, ".config", "vcom", "vcom.toml")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink("../../dotfiles/vcom.toml", link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg, info, err := Load("")
|
||||||
|
if err != nil || !info.Found || cfg.UI.Theme != "old" {
|
||||||
|
t.Fatalf("load via symlink: %v %+v theme=%q", err, info, cfg.UI.Theme)
|
||||||
|
}
|
||||||
|
if _, err := SetKey(info.Path, "ui", "theme", "new"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fi, err := os.Lstat(link); err != nil || fi.Mode()&os.ModeSymlink == 0 {
|
||||||
|
t.Fatal("symlink replaced by a regular file")
|
||||||
|
}
|
||||||
|
b, _ := os.ReadFile(target)
|
||||||
|
if string(b) != "# mine\n[ui]\ntheme = \"new\" # c\n" {
|
||||||
|
t.Fatalf("target content %q", b)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(target); fi.Mode().Perm() != 0o640 {
|
||||||
|
t.Fatalf("target mode changed to %o", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A user who made the config read-only (chmod a-w) expects vcom not to
|
||||||
|
// change it. v0.2.7 failed with EACCES; atomic rename now replaces it.
|
||||||
|
func TestQASetKeyReadOnlyConfig(t *testing.T) {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
p := filepath.Join(home, ".config", "vcom", "vcom.toml")
|
||||||
|
qaWrite(t, p, "[ui]\ntheme = \"locked\"\n", 0o444)
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "other"); err == nil {
|
||||||
|
b, _ := os.ReadFile(p)
|
||||||
|
t.Fatalf("read-only config was rewritten: %q", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valid TOML forms of the same key: dotted key at the root and an inline
|
||||||
|
// table. SetKey must either edit them or fail without touching the file;
|
||||||
|
// failing means the theme silently stops being saved for these users.
|
||||||
|
func TestQASetKeyDottedAndInlineForms(t *testing.T) {
|
||||||
|
for name, content := range map[string]string{
|
||||||
|
"dotted": "ui.theme = \"old\"\nui.icon_mode = \"ascii\"\n",
|
||||||
|
"inline": "ui = { theme = \"old\" }\n",
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
p := filepath.Join(home, "vcom.toml")
|
||||||
|
qaWrite(t, p, content, 0o644)
|
||||||
|
if _, _, err := Parse([]byte(content)); err != nil {
|
||||||
|
t.Fatalf("fixture must be valid: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "new"); err != nil {
|
||||||
|
t.Fatalf("SetKey on a valid %s config: %v", name, err)
|
||||||
|
}
|
||||||
|
b, _ := os.ReadFile(p)
|
||||||
|
c, _, err := Parse(b)
|
||||||
|
if err != nil || c.UI.Theme != "new" {
|
||||||
|
t.Fatalf("result %q: theme=%q err=%v", b, c.UI.Theme, err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Even when SetKey fails on such a file, it must stay byte-identical.
|
||||||
|
func TestQASetKeyFailureLeavesFileIntact(t *testing.T) {
|
||||||
|
for _, content := range []string{
|
||||||
|
"ui.theme = \"old\"\n",
|
||||||
|
"ui = { theme = \"old\" }\n",
|
||||||
|
"[ui]\ntheme = \"\"\"multi\nline\"\"\"\n",
|
||||||
|
"[ui\ntheme = 1\n", // broken
|
||||||
|
} {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
p := filepath.Join(home, "vcom.toml")
|
||||||
|
qaWrite(t, p, content, 0o600)
|
||||||
|
_, _ = SetKey(p, "ui", "theme", "new")
|
||||||
|
b, _ := os.ReadFile(p)
|
||||||
|
c, _, perr := Parse(b)
|
||||||
|
if string(b) != content && (perr != nil || c.UI.Theme != "new") {
|
||||||
|
t.Fatalf("file damaged: before %q after %q", content, b)
|
||||||
|
}
|
||||||
|
if left, _ := filepath.Glob(filepath.Join(home, ".vcom.toml.tmp-*")); len(left) != 0 {
|
||||||
|
t.Fatalf("temp files left: %v", left)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UTF-8 BOM and CRLF (configs edited on Windows / by some editors).
|
||||||
|
func TestQASetKeyBOM(t *testing.T) {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
p := filepath.Join(home, "vcom.toml")
|
||||||
|
content := "\ufeff[ui]\r\ntheme = \"old\"\r\n"
|
||||||
|
qaWrite(t, p, content, 0o644)
|
||||||
|
if _, _, err := Parse([]byte(content)); err != nil {
|
||||||
|
t.Skipf("go-toml does not accept a BOM: %v", err)
|
||||||
|
}
|
||||||
|
_, err := SetKey(p, "ui", "theme", "new")
|
||||||
|
b, _ := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
if string(b) != content {
|
||||||
|
t.Fatalf("failed SetKey changed the file: %q", b)
|
||||||
|
}
|
||||||
|
t.Logf("SetKey refuses a BOM config: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if c, _, err := Parse(b); err != nil || c.UI.Theme != "new" || strings.Count(string(b), "[ui]") != 1 {
|
||||||
|
t.Fatalf("BOM config result %q (err %v)", b, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load: a directory or an unreadable file in place of the config gives
|
||||||
|
// defaults plus an error, never a crash.
|
||||||
|
func TestQALoadDirAndUnreadable(t *testing.T) {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
p := filepath.Join(home, ".config", "vcom", "vcom.toml")
|
||||||
|
if err := os.MkdirAll(p, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cfg, _, err := Load("")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("directory as config must report an error")
|
||||||
|
}
|
||||||
|
if cfg.UI.Theme != Default().UI.Theme {
|
||||||
|
t.Fatal("defaults not used")
|
||||||
|
}
|
||||||
|
os.Remove(p)
|
||||||
|
qaWrite(t, p, "[ui]\ntheme = \"x\"\n", 0o000)
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("root reads 0000 files")
|
||||||
|
}
|
||||||
|
if _, _, err := Load(""); err == nil {
|
||||||
|
t.Fatal("unreadable config must report an error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -config / $VCOM_CONFIG pointing to a missing file: Load reports where it
|
||||||
|
// would be created (info.Path = that file).
|
||||||
|
func TestQALoadExplicitMissing(t *testing.T) {
|
||||||
|
home := qaIsolate(t)
|
||||||
|
want := filepath.Join(home, "custom", "vcom.toml")
|
||||||
|
t.Setenv("VCOM_CONFIG", want)
|
||||||
|
_, info, err := Load("")
|
||||||
|
if err != nil || info.Found || info.Path != want {
|
||||||
|
t.Fatalf("info=%+v err=%v", info, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,86 +1,19 @@
|
||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import "vcom/internal/state"
|
||||||
"fmt"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
toml "github.com/pelletier/go-toml/v2"
|
// Session types and functions are thin aliases over internal/state, kept so
|
||||||
|
// the old UI compiles unchanged until stage 7.
|
||||||
"vcom/internal/homedir"
|
type (
|
||||||
|
SessionState = state.Session
|
||||||
|
PaneSession = state.PaneSession
|
||||||
)
|
)
|
||||||
|
|
||||||
// SessionState stores the UI state that should be restored on next launch.
|
// DefaultSessionPath returns the session file ($XDG_STATE_HOME/vcom/session.toml).
|
||||||
type SessionState struct {
|
func DefaultSessionPath() (string, error) { return state.File() }
|
||||||
ActivePane string `toml:"active_pane"`
|
|
||||||
Left PaneSession `toml:"left"`
|
|
||||||
Right PaneSession `toml:"right"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// PaneSession stores per-pane session state (path and selected entry name).
|
// LoadSession reads the session (migrating it from the old location once).
|
||||||
type PaneSession struct {
|
func LoadSession() (SessionState, error) { return state.Load() }
|
||||||
Path string `toml:"path"`
|
|
||||||
EntryName string `toml:"entry_name"`
|
|
||||||
CursorMemory map[string]string `toml:"cursor_memory"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefaultSessionPath returns the path to the session file.
|
// SaveSession writes the session atomically.
|
||||||
func DefaultSessionPath() (string, error) {
|
func SaveSession(s SessionState) error { return state.Save(s) }
|
||||||
homeDir := homedir.Dir()
|
|
||||||
if homeDir == "" {
|
|
||||||
return "", fmt.Errorf("cannot determine home directory")
|
|
||||||
}
|
|
||||||
xdgDir := os.Getenv("XDG_CONFIG_HOME")
|
|
||||||
if xdgDir == "" {
|
|
||||||
xdgDir = filepath.Join(homeDir, ".config")
|
|
||||||
}
|
|
||||||
return filepath.Join(xdgDir, "vcom", "session.toml"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoadSession reads the session state from disk.
|
|
||||||
// Returns (SessionState, nil) on success, (empty, error) if file doesn't exist.
|
|
||||||
func LoadSession() (SessionState, error) {
|
|
||||||
path, err := DefaultSessionPath()
|
|
||||||
if err != nil {
|
|
||||||
return SessionState{}, err
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := os.ReadFile(path)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return SessionState{}, nil
|
|
||||||
}
|
|
||||||
return SessionState{}, fmt.Errorf("read %s: %w", path, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var s SessionState
|
|
||||||
if err := toml.Unmarshal(data, &s); err != nil {
|
|
||||||
return SessionState{}, fmt.Errorf("parse %s: %w", path, err)
|
|
||||||
}
|
|
||||||
return s, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SaveSession writes the session state to disk.
|
|
||||||
func SaveSession(s SessionState) error {
|
|
||||||
path, err := DefaultSessionPath()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
absPath, err := filepath.Abs(path)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("resolve %s: %w", path, err)
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil {
|
|
||||||
return fmt.Errorf("mkdir %s: %w", filepath.Dir(absPath), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
data, err := toml.Marshal(s)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("marshal session: %w", err)
|
|
||||||
}
|
|
||||||
if err := os.WriteFile(absPath, data, 0o644); err != nil {
|
|
||||||
return fmt.Errorf("write %s: %w", path, err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
|
||||||
358
internal/config/setkey.go
Normal file
358
internal/config/setkey.go
Normal file
|
|
@ -0,0 +1,358 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
toml "github.com/pelletier/go-toml/v2"
|
||||||
|
|
||||||
|
"vcom/internal/atomicfile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SetKey sets section.key = value in the config file at path by editing that
|
||||||
|
// one line: comments, order, formatting and unknown keys are kept (design
|
||||||
|
// §9.2). A missing key is appended to its section, a missing section to the
|
||||||
|
// end of the file, a missing file is created (path "" means the default XDG
|
||||||
|
// location). The file must parse before the edit — a broken config is never
|
||||||
|
// touched — and the result is parsed again before it is written atomically.
|
||||||
|
//
|
||||||
|
// value is a string, bool, integer or float. section may be dotted
|
||||||
|
// ("browser.sort").
|
||||||
|
func SetKey(path, section, key string, value any) (string, error) {
|
||||||
|
if path == "" {
|
||||||
|
var err error
|
||||||
|
if path, err = DefaultUserPath(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lit, err := tomlValue(value)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
out := []byte("[" + section + "]\n" + key + " = " + lit + "\n")
|
||||||
|
if err := verify(out, section, key, value); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return path, atomicfile.WriteFile(path, out, 0o644)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
var probe map[string]any
|
||||||
|
if err := toml.Unmarshal(data, &probe); err != nil {
|
||||||
|
return "", fmt.Errorf("%s does not parse, not editing it: %w", path, describe(err))
|
||||||
|
}
|
||||||
|
out, err := editTOML(data, section, key, lit)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("edit %s: %w", path, err)
|
||||||
|
}
|
||||||
|
if err := verify(out, section, key, value); err != nil {
|
||||||
|
return "", fmt.Errorf("edit %s: %w", path, err)
|
||||||
|
}
|
||||||
|
return path, atomicfile.WriteFile(path, out, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
reHeader = regexp.MustCompile(`^\s*\[\s*([^\[\]]+?)\s*\]\s*(#.*)?$`)
|
||||||
|
reArray = regexp.MustCompile(`^\s*\[\[`)
|
||||||
|
)
|
||||||
|
|
||||||
|
// normSection canonicalises a table name: `a . "b"` → `a.b`.
|
||||||
|
func normSection(s string) string {
|
||||||
|
parts := strings.Split(s, ".")
|
||||||
|
for i, p := range parts {
|
||||||
|
p = strings.TrimSpace(p)
|
||||||
|
if len(p) >= 2 && (p[0] == '"' && p[len(p)-1] == '"' || p[0] == '\'' && p[len(p)-1] == '\'') {
|
||||||
|
p = p[1 : len(p)-1]
|
||||||
|
}
|
||||||
|
parts[i] = p
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ".")
|
||||||
|
}
|
||||||
|
|
||||||
|
// editTOML returns data with section.key set to the TOML literal lit.
|
||||||
|
func editTOML(data []byte, section, key, lit string) ([]byte, error) {
|
||||||
|
text := string(data)
|
||||||
|
nl := "\n"
|
||||||
|
if strings.Contains(text, "\r\n") {
|
||||||
|
nl = "\r\n"
|
||||||
|
}
|
||||||
|
lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
|
||||||
|
section = normSection(section)
|
||||||
|
reKey := regexp.MustCompile(`^(\s*(?:` + regexp.QuoteMeta(key) + `|"` + regexp.QuoteMeta(key) + `"|'` +
|
||||||
|
regexp.QuoteMeta(key) + `')\s*=\s*)(.*)$`)
|
||||||
|
|
||||||
|
if out, ok, err := editRootForms(lines, section, key, lit); err != nil || ok {
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return []byte(strings.Join(out, nl)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
cur := "" // the root table
|
||||||
|
inTarget := section == ""
|
||||||
|
lastContent := -1 // last key/value line of the target section
|
||||||
|
headerAt := -1
|
||||||
|
for i, line := range lines {
|
||||||
|
if reArray.MatchString(line) {
|
||||||
|
cur, inTarget = "\x00array", false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m := reHeader.FindStringSubmatch(line); m != nil {
|
||||||
|
cur = normSection(m[1])
|
||||||
|
inTarget = cur == section
|
||||||
|
if inTarget {
|
||||||
|
headerAt = i
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !inTarget {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if m := reKey.FindStringSubmatch(line); m != nil {
|
||||||
|
val, rest, err := splitValue(m[2])
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s.%s: %w", section, key, err)
|
||||||
|
}
|
||||||
|
lines[i] = m[1] + styleLike(val, lit) + rest
|
||||||
|
return []byte(strings.Join(lines, nl)), nil
|
||||||
|
}
|
||||||
|
if t := strings.TrimSpace(line); t != "" && !strings.HasPrefix(t, "#") {
|
||||||
|
lastContent = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
newLine := key + " = " + lit
|
||||||
|
switch {
|
||||||
|
case headerAt >= 0 || section == "":
|
||||||
|
at := lastContent
|
||||||
|
if at < 0 {
|
||||||
|
at = headerAt // empty section (or root): right after the header
|
||||||
|
}
|
||||||
|
lines = append(lines[:at+1], append([]string{newLine}, lines[at+1:]...)...)
|
||||||
|
default:
|
||||||
|
for len(lines) > 0 && lines[len(lines)-1] == "" {
|
||||||
|
lines = lines[:len(lines)-1]
|
||||||
|
}
|
||||||
|
if len(lines) > 0 {
|
||||||
|
lines = append(lines, "")
|
||||||
|
}
|
||||||
|
lines = append(lines, "["+section+"]", newLine, "")
|
||||||
|
}
|
||||||
|
return []byte(strings.Join(lines, nl)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// styleLike keeps the file's literal-string style ('...') when possible.
|
||||||
|
func styleLike(old, lit string) string {
|
||||||
|
if strings.HasPrefix(old, "'") && !strings.ContainsAny(lit, `'\`) && strings.HasPrefix(lit, `"`) {
|
||||||
|
if s, err := strconv.Unquote(lit); err == nil && !strings.ContainsAny(s, "'\n") {
|
||||||
|
return "'" + s + "'"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lit
|
||||||
|
}
|
||||||
|
|
||||||
|
// namePattern matches a TOML key path (bare or quoted parts, spaces around
|
||||||
|
// dots allowed).
|
||||||
|
func namePattern(dotted string) string {
|
||||||
|
var parts []string
|
||||||
|
for _, p := range strings.Split(dotted, ".") {
|
||||||
|
q := regexp.QuoteMeta(p)
|
||||||
|
parts = append(parts, `(?:`+q+`|"`+q+`"|'`+q+`')`)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, `\s*\.\s*`)
|
||||||
|
}
|
||||||
|
|
||||||
|
// editRootForms handles a section written without a [table] header, in the
|
||||||
|
// root table: dotted keys (`ui.theme = "x"`) or an inline table
|
||||||
|
// (`ui = { theme = "x" }`) — QA-14. ok reports whether it edited.
|
||||||
|
func editRootForms(lines []string, section, key, lit string) (out []string, ok bool, err error) {
|
||||||
|
if section == "" {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
sec, k := namePattern(section), namePattern(key)
|
||||||
|
reDotted := regexp.MustCompile(`^(\s*` + sec + `\s*\.\s*` + k + `\s*=\s*)(.*)$`)
|
||||||
|
reInline := regexp.MustCompile(`^(\s*` + sec + `\s*=\s*\{)(.*)\}(\s*(?:#.*)?)$`)
|
||||||
|
reInlineOpen := regexp.MustCompile(`^\s*` + sec + `\s*=\s*\{`)
|
||||||
|
rePrefix := regexp.MustCompile(`^\s*` + sec + `\s*\.`)
|
||||||
|
lastDotted := -1
|
||||||
|
for i, line := range lines {
|
||||||
|
if reHeader.MatchString(line) || reArray.MatchString(line) {
|
||||||
|
break // end of the root table
|
||||||
|
}
|
||||||
|
if m := reDotted.FindStringSubmatch(line); m != nil {
|
||||||
|
val, rest, err := splitValue(m[2])
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, fmt.Errorf("%s.%s: %w", section, key, err)
|
||||||
|
}
|
||||||
|
lines[i] = m[1] + styleLike(val, lit) + rest
|
||||||
|
return lines, true, nil
|
||||||
|
}
|
||||||
|
if m := reInline.FindStringSubmatch(line); m != nil {
|
||||||
|
inner, err := setInline(m[2], key, lit)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, fmt.Errorf("%s: %w", section, err)
|
||||||
|
}
|
||||||
|
lines[i] = m[1] + inner + "}" + m[3]
|
||||||
|
return lines, true, nil
|
||||||
|
}
|
||||||
|
if reInlineOpen.MatchString(line) {
|
||||||
|
return nil, false, fmt.Errorf("%s: multi-line inline tables are not supported", section)
|
||||||
|
}
|
||||||
|
if rePrefix.MatchString(line) {
|
||||||
|
lastDotted = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if lastDotted >= 0 { // the section exists only as dotted keys: add one more
|
||||||
|
nl := section + "." + key + " = " + lit
|
||||||
|
return append(lines[:lastDotted+1], append([]string{nl}, lines[lastDotted+1:]...)...), true, nil
|
||||||
|
}
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// setInline sets key in the body of a one-line inline table.
|
||||||
|
func setInline(inner, key, lit string) (string, error) {
|
||||||
|
re := regexp.MustCompile(`(^|,)(\s*` + namePattern(key) + `\s*=\s*)`)
|
||||||
|
loc := re.FindStringSubmatchIndex(inner)
|
||||||
|
if loc == nil {
|
||||||
|
t := strings.TrimRight(inner, " \t")
|
||||||
|
if strings.TrimSpace(t) == "" {
|
||||||
|
return " " + key + " = " + lit + " ", nil
|
||||||
|
}
|
||||||
|
return t + ", " + key + " = " + lit + " ", nil
|
||||||
|
}
|
||||||
|
start := loc[1]
|
||||||
|
rest := inner[start:]
|
||||||
|
var end int
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(rest, `"`) || strings.HasPrefix(rest, `'`):
|
||||||
|
val, _, err := splitValue(rest)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
end = len(val)
|
||||||
|
case strings.HasPrefix(rest, "[") || strings.HasPrefix(rest, "{"):
|
||||||
|
return "", errors.New("nested values in inline tables are not supported")
|
||||||
|
default:
|
||||||
|
end = strings.IndexByte(rest, ',')
|
||||||
|
if end < 0 {
|
||||||
|
end = len(rest)
|
||||||
|
}
|
||||||
|
end = len(strings.TrimRight(rest[:end], " \t"))
|
||||||
|
}
|
||||||
|
return inner[:start] + styleLike(rest[:end], lit) + rest[end:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitValue splits "value # comment" into the value token and the rest
|
||||||
|
// (whitespace and comment), respecting quoted strings.
|
||||||
|
func splitValue(s string) (val, rest string, err error) {
|
||||||
|
if strings.HasPrefix(s, `"""`) || strings.HasPrefix(s, `'''`) {
|
||||||
|
return "", "", errors.New("multi-line string values are not supported")
|
||||||
|
}
|
||||||
|
end := len(s)
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(s, `"`):
|
||||||
|
end = -1
|
||||||
|
for i := 1; i < len(s); i++ {
|
||||||
|
if s[i] == '\\' {
|
||||||
|
i++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if s[i] == '"' {
|
||||||
|
end = i + 1
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case strings.HasPrefix(s, `'`):
|
||||||
|
end = -1
|
||||||
|
if j := strings.IndexByte(s[1:], '\''); j >= 0 {
|
||||||
|
end = j + 2
|
||||||
|
}
|
||||||
|
case strings.HasPrefix(s, "[") || strings.HasPrefix(s, "{"):
|
||||||
|
return "", "", errors.New("array and inline-table values are not supported")
|
||||||
|
default:
|
||||||
|
if j := strings.IndexByte(s, '#'); j >= 0 {
|
||||||
|
end = j
|
||||||
|
}
|
||||||
|
end = len(strings.TrimRight(s[:end], " \t"))
|
||||||
|
}
|
||||||
|
if end < 0 {
|
||||||
|
return "", "", errors.New("unterminated string")
|
||||||
|
}
|
||||||
|
return s[:end], s[end:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// tomlValue renders value as a TOML literal.
|
||||||
|
func tomlValue(v any) (string, error) {
|
||||||
|
switch x := v.(type) {
|
||||||
|
case string:
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteByte('"')
|
||||||
|
for _, r := range x {
|
||||||
|
switch {
|
||||||
|
case r == '"':
|
||||||
|
b.WriteString(`\"`)
|
||||||
|
case r == '\\':
|
||||||
|
b.WriteString(`\\`)
|
||||||
|
case r == '\n':
|
||||||
|
b.WriteString(`\n`)
|
||||||
|
case r == '\t':
|
||||||
|
b.WriteString(`\t`)
|
||||||
|
case r < 0x20 || r == 0x7f:
|
||||||
|
fmt.Fprintf(&b, `\u%04X`, r)
|
||||||
|
default:
|
||||||
|
b.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteByte('"')
|
||||||
|
return b.String(), nil
|
||||||
|
case bool:
|
||||||
|
return strconv.FormatBool(x), nil
|
||||||
|
case int:
|
||||||
|
return strconv.Itoa(x), nil
|
||||||
|
case int64:
|
||||||
|
return strconv.FormatInt(x, 10), nil
|
||||||
|
case float64:
|
||||||
|
return strconv.FormatFloat(x, 'g', -1, 64), nil
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("config: unsupported value type %T", v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// verify parses out and checks that section.key now holds value.
|
||||||
|
func verify(out []byte, section, key string, value any) error {
|
||||||
|
var m map[string]any
|
||||||
|
if err := toml.Unmarshal(out, &m); err != nil {
|
||||||
|
return fmt.Errorf("result does not parse: %w", err)
|
||||||
|
}
|
||||||
|
var cur any = m
|
||||||
|
path := append(strings.Split(normSection(section), "."), key)
|
||||||
|
if section == "" {
|
||||||
|
path = []string{key}
|
||||||
|
}
|
||||||
|
for _, p := range path {
|
||||||
|
mm, ok := cur.(map[string]any)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("result: %s.%s not found", section, key)
|
||||||
|
}
|
||||||
|
cur = mm[p]
|
||||||
|
}
|
||||||
|
want := value
|
||||||
|
if n, ok := value.(int); ok {
|
||||||
|
want = int64(n)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(cur, want) {
|
||||||
|
return fmt.Errorf("result: %s.%s = %v, want %v", section, key, cur, value)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
178
internal/config/setkey_test.go
Normal file
178
internal/config/setkey_test.go
Normal file
|
|
@ -0,0 +1,178 @@
|
||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, p, s string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func readFile(t *testing.T, p string) string {
|
||||||
|
t.Helper()
|
||||||
|
b, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// diffLines returns the indexes of lines that differ (files of equal length).
|
||||||
|
func diffLines(t *testing.T, a, b string) []int {
|
||||||
|
t.Helper()
|
||||||
|
la, lb := strings.Split(a, "\n"), strings.Split(b, "\n")
|
||||||
|
if len(la) != len(lb) {
|
||||||
|
t.Fatalf("line count changed: %d -> %d\n%s", len(la), len(lb), b)
|
||||||
|
}
|
||||||
|
var d []int
|
||||||
|
for i := range la {
|
||||||
|
if la[i] != lb[i] {
|
||||||
|
d = append(d, i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetKeyPreservesComments(t *testing.T) {
|
||||||
|
orig, err := os.ReadFile("../../vcom.toml")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Plus an unknown key and an extra comment the user added.
|
||||||
|
before := string(orig) + "\n# my own note\n[extra]\nmine = 1 # keep\n"
|
||||||
|
p := filepath.Join(t.TempDir(), "vcom.toml")
|
||||||
|
writeFile(t, p, before)
|
||||||
|
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "nord"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
after := readFile(t, p)
|
||||||
|
d := diffLines(t, before, after)
|
||||||
|
if len(d) != 1 {
|
||||||
|
t.Fatalf("changed lines %v, want only the theme line:\n%s", d, after)
|
||||||
|
}
|
||||||
|
line := strings.Split(after, "\n")[d[0]]
|
||||||
|
if !strings.HasPrefix(line, "theme = 'nord'") {
|
||||||
|
t.Fatalf("theme line = %q (style of the original literal string expected)", line)
|
||||||
|
}
|
||||||
|
c, _, err := Parse([]byte(after))
|
||||||
|
if err != nil || c.UI.Theme != "nord" {
|
||||||
|
t.Fatalf("result: %v %+v", err, c.UI)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A value with a trailing comment keeps the comment; a nested section works.
|
||||||
|
if _, err := SetKey(p, "browser.sort", "by", "size"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(readFile(t, p), "by = 'size' # name | modified") {
|
||||||
|
t.Fatalf("trailing comment lost:\n%s", readFile(t, p))
|
||||||
|
}
|
||||||
|
if _, err := SetKey(p, "ui", "pane_gap", 2); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(readFile(t, p), "pane_gap = 2 # 0..4") {
|
||||||
|
t.Fatalf("int edit:\n%s", readFile(t, p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetKeyMissingSection(t *testing.T) {
|
||||||
|
p := filepath.Join(t.TempDir(), "vcom.toml")
|
||||||
|
before := "# top comment\n[browser]\nshow_hidden = false # mine\n"
|
||||||
|
writeFile(t, p, before)
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "nord"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
after := readFile(t, p)
|
||||||
|
if !strings.HasPrefix(after, before) {
|
||||||
|
t.Fatalf("existing content changed:\n%s", after)
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(after, "\n[ui]\ntheme = \"nord\"\n") {
|
||||||
|
t.Fatalf("section not appended:\n%q", after)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Missing key in an existing section: inserted after its last key.
|
||||||
|
writeFile(t, p, "[ui]\nborder = 'thin' # b\n\n# about browser\n[browser]\nshow_hidden = true\n")
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "nord"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := "[ui]\nborder = 'thin' # b\ntheme = \"nord\"\n\n# about browser\n[browser]\nshow_hidden = true\n"
|
||||||
|
if got := readFile(t, p); got != want {
|
||||||
|
t.Fatalf("got:\n%s\nwant:\n%s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetKeyNoFile(t *testing.T) {
|
||||||
|
xdg := t.TempDir()
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", xdg)
|
||||||
|
t.Setenv("VCOM_CONFIG", "")
|
||||||
|
path, err := SetKey("", "ui", "theme", "nord")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := filepath.Join(xdg, "vcom", "vcom.toml"); path != want {
|
||||||
|
t.Fatalf("created %s, want %s", path, want)
|
||||||
|
}
|
||||||
|
if got := readFile(t, path); got != "[ui]\ntheme = \"nord\"\n" {
|
||||||
|
t.Fatalf("content %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetKeyRefusesBrokenFile(t *testing.T) {
|
||||||
|
p := filepath.Join(t.TempDir(), "vcom.toml")
|
||||||
|
broken := "[ui]\ntheme = \"nord\nborder = 'x'\n"
|
||||||
|
writeFile(t, p, broken)
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "dracula"); err == nil {
|
||||||
|
t.Fatal("SetKey edited a file that does not parse")
|
||||||
|
}
|
||||||
|
if readFile(t, p) != broken {
|
||||||
|
t.Fatal("broken file was modified")
|
||||||
|
}
|
||||||
|
// Unsupported shapes are refused, not mangled.
|
||||||
|
writeFile(t, p, "[ui]\ntheme = \"\"\"\nnord\"\"\"\n")
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "x"); err == nil {
|
||||||
|
t.Fatal("multi-line string must be refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetKeyQuotingAndCRLF(t *testing.T) {
|
||||||
|
p := filepath.Join(t.TempDir(), "vcom.toml")
|
||||||
|
writeFile(t, p, "[ui]\r\ntheme = \"a#b\" # c\r\n")
|
||||||
|
if _, err := SetKey(p, "ui", "theme", `it's "q"`); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := readFile(t, p); got != "[ui]\r\ntheme = \"it's \\\"q\\\"\" # c\r\n" {
|
||||||
|
t.Fatalf("got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetKeyRootForms(t *testing.T) {
|
||||||
|
cases := map[string]struct{ in, want string }{
|
||||||
|
"dotted": {"ui.theme = 'old' # c\nui.icon_mode = \"ascii\"\n", "ui.theme = 'new' # c\nui.icon_mode = \"ascii\"\n"},
|
||||||
|
"dotted missing": {"ui.icon_mode = \"ascii\"\n[browser]\nshow_hidden = true\n", "ui.icon_mode = \"ascii\"\nui.theme = \"new\"\n[browser]\nshow_hidden = true\n"},
|
||||||
|
"inline": {"ui = { theme = \"old\", border = 'x' }\n", "ui = { theme = \"new\", border = 'x' }\n"},
|
||||||
|
"inline missing": {"ui = { border = 'x' }\n", "ui = { border = 'x', theme = \"new\" }\n"},
|
||||||
|
"inline empty": {"ui = {}\n", "ui = { theme = \"new\" }\n"},
|
||||||
|
}
|
||||||
|
for name, c := range cases {
|
||||||
|
p := filepath.Join(t.TempDir(), "vcom.toml")
|
||||||
|
writeFile(t, p, c.in)
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "new"); err != nil {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
if got := readFile(t, p); got != c.want {
|
||||||
|
t.Errorf("%s:\n got %q\nwant %q", name, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A multi-line inline table is refused, file untouched.
|
||||||
|
p := filepath.Join(t.TempDir(), "vcom.toml")
|
||||||
|
writeFile(t, p, "ui = {\n}\n")
|
||||||
|
if _, err := SetKey(p, "ui", "theme", "new"); err == nil {
|
||||||
|
t.Fatal("multi-line inline accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
@ -315,22 +316,103 @@ func ArchiveName(sources []string, format string) string {
|
||||||
// CreateArchive creates an archive from source paths using the given format.
|
// CreateArchive creates an archive from source paths using the given format.
|
||||||
// Supported formats: "zip", "tar", "tar.gz" (or "targz", "tgz").
|
// Supported formats: "zip", "tar", "tar.gz" (or "targz", "tgz").
|
||||||
// Progress is reported via the callback function.
|
// Progress is reported via the callback function.
|
||||||
|
//
|
||||||
|
// The archive is written to a temporary file next to archivePath and renamed
|
||||||
|
// over it only on success, so a failed or cancelled run leaves neither a
|
||||||
|
// partial archive nor a damaged previous one. An archivePath that is one of
|
||||||
|
// the sources or lies inside one is refused (U-P0-1).
|
||||||
func CreateArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
func CreateArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
||||||
if ctx == nil {
|
if ctx == nil {
|
||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
}
|
}
|
||||||
|
if err := CheckArchiveTarget(sources, archivePath); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var create func(context.Context, []string, string, func(CopyProgress)) error
|
||||||
lower := strings.ToLower(archivePath)
|
lower := strings.ToLower(archivePath)
|
||||||
switch {
|
switch {
|
||||||
case strings.HasSuffix(lower, ".zip"):
|
case strings.HasSuffix(lower, ".zip"):
|
||||||
return createZipArchive(ctx, sources, archivePath, progress)
|
create = createZipArchive
|
||||||
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
|
case strings.HasSuffix(lower, ".tar.gz"), strings.HasSuffix(lower, ".tgz"):
|
||||||
return createTarGzArchive(ctx, sources, archivePath, progress)
|
create = createTarGzArchive
|
||||||
case strings.HasSuffix(lower, ".tar"):
|
case strings.HasSuffix(lower, ".tar"):
|
||||||
return createTarArchive(ctx, sources, archivePath, progress)
|
create = createTarArchive
|
||||||
default:
|
default:
|
||||||
return fmt.Errorf("unsupported archive format: %s", filepath.Ext(archivePath))
|
return fmt.Errorf("unsupported archive format: %s", filepath.Ext(archivePath))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Short temp name: a long but valid archive name plus a prefix would
|
||||||
|
// exceed NAME_MAX (QA-7). CreateTemp makes it 0600 while it is written.
|
||||||
|
tmp, err := os.CreateTemp(filepath.Dir(archivePath), ".vcom-tmp-*")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create %s: %w", archivePath, err)
|
||||||
|
}
|
||||||
|
tmpPath := tmp.Name()
|
||||||
|
tmp.Close()
|
||||||
|
if err := create(ctx, sources, tmpPath, progress); err != nil {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// A replaced archive keeps its permissions (a private 0600 archive must
|
||||||
|
// not become world-readable, QA-6); a new one gets 0666 minus umask,
|
||||||
|
// as os.Create would.
|
||||||
|
mode := 0o666 &^ processUmask()
|
||||||
|
if st, err := os.Stat(archivePath); err == nil {
|
||||||
|
mode = st.Mode().Perm()
|
||||||
|
}
|
||||||
|
if err := os.Chmod(tmpPath, mode); err != nil {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Rename(tmpPath, archivePath); err != nil {
|
||||||
|
os.Remove(tmpPath)
|
||||||
|
return fmt.Errorf("rename %s: %w", archivePath, err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckArchiveTarget returns an error if writing archivePath would overwrite
|
||||||
|
// one of sources or place the archive inside a source directory (where it
|
||||||
|
// would be truncated before being read, or include itself). Symlinked
|
||||||
|
// parent directories are resolved.
|
||||||
|
func CheckArchiveTarget(sources []string, archivePath string) error {
|
||||||
|
target := []string{archivePath}
|
||||||
|
if r, ok := resolveParent(archivePath); ok {
|
||||||
|
target = append(target, r)
|
||||||
|
}
|
||||||
|
for _, src := range sources {
|
||||||
|
candidates := []string{src}
|
||||||
|
if r, ok := resolveParent(src); ok {
|
||||||
|
candidates = append(candidates, r)
|
||||||
|
}
|
||||||
|
for _, t := range target {
|
||||||
|
for _, c := range candidates {
|
||||||
|
within, err := pathWithin(t, c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if within {
|
||||||
|
return fmt.Errorf("archive %s would overwrite or be inside its source %s", filepath.Base(archivePath), src)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolveParent resolves symlinks in p's parent directory (p itself may not
|
||||||
|
// exist yet and is not followed).
|
||||||
|
func resolveParent(p string) (string, bool) {
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
dir, err := filepath.EvalSymlinks(filepath.Dir(abs))
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return filepath.Join(dir, filepath.Base(abs)), true
|
||||||
}
|
}
|
||||||
|
|
||||||
func createZipArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
func createZipArchive(ctx context.Context, sources []string, archivePath string, progress func(CopyProgress)) error {
|
||||||
|
|
@ -654,3 +736,19 @@ func commonBaseDir(paths []string) string {
|
||||||
}
|
}
|
||||||
return base
|
return base
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// processUmask reads the umask without changing it (syscall.Umask would
|
||||||
|
// briefly change it for the whole process). Falls back to 022.
|
||||||
|
func processUmask() os.FileMode {
|
||||||
|
data, err := os.ReadFile("/proc/self/status")
|
||||||
|
if err == nil {
|
||||||
|
for _, line := range strings.Split(string(data), "\n") {
|
||||||
|
if v, ok := strings.CutPrefix(line, "Umask:"); ok {
|
||||||
|
if n, err := strconv.ParseUint(strings.TrimSpace(v), 8, 32); err == nil {
|
||||||
|
return os.FileMode(n) & 0o777
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0o022
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -12,7 +12,7 @@ import (
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"vcom/internal/homedir"
|
"vcom/internal/vfs/localfs"
|
||||||
)
|
)
|
||||||
|
|
||||||
type TransferStats struct {
|
type TransferStats struct {
|
||||||
|
|
@ -94,10 +94,10 @@ func CopyPathWithProgressContext(ctx context.Context, srcPath string, dstDir str
|
||||||
progress = func(CopyProgress) {}
|
progress = func(CopyProgress) {}
|
||||||
}
|
}
|
||||||
tracker := copyProgressState{
|
tracker := copyProgressState{
|
||||||
ctx: ctx,
|
ctx: ctx,
|
||||||
stats: stats,
|
stats: stats,
|
||||||
callback: progress,
|
callback: progress,
|
||||||
stage: "Scanning files...",
|
stage: "Scanning files...",
|
||||||
discover: stats.FilesTotal == 0,
|
discover: stats.FilesTotal == 0,
|
||||||
}
|
}
|
||||||
tracker.emit(srcPath, true)
|
tracker.emit(srcPath, true)
|
||||||
|
|
@ -272,68 +272,22 @@ func DeletePath(path string) error {
|
||||||
return os.RemoveAll(path)
|
return os.RemoveAll(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MoveToTrash moves a file or directory to the FreeDesktop Trash directory
|
// MoveToTrash moves a file or directory to the freedesktop.org trash. It
|
||||||
// (~/.local/share/Trash). Follows the FreeDesktop Trash specification:
|
// delegates to the new local vfs (internal/vfs/localfs): topdir trash on other
|
||||||
// - The original item is moved to Trash/files/<basename>
|
// volumes instead of EXDEV, URL-encoded Path=, O_EXCL info files and the
|
||||||
// - A .trashinfo file is written to Trash/info/<basename>.trashinfo
|
// effective user's trash under sudo (N-P2-12).
|
||||||
// - If <basename> already exists in Trash/files, a numeric suffix is appended.
|
|
||||||
func MoveToTrash(path string) error {
|
func MoveToTrash(path string) error {
|
||||||
home := homedir.Dir()
|
return localfs.New().Trash(context.Background(), path)
|
||||||
if home == "" {
|
|
||||||
return fmt.Errorf("cannot determine home directory")
|
|
||||||
}
|
|
||||||
|
|
||||||
trashDir := filepath.Join(home, ".local", "share", "Trash")
|
|
||||||
filesDir := filepath.Join(trashDir, "files")
|
|
||||||
infoDir := filepath.Join(trashDir, "info")
|
|
||||||
|
|
||||||
if err := os.MkdirAll(filesDir, 0o700); err != nil {
|
|
||||||
return fmt.Errorf("cannot create trash files directory: %w", err)
|
|
||||||
}
|
|
||||||
if err := os.MkdirAll(infoDir, 0o700); err != nil {
|
|
||||||
return fmt.Errorf("cannot create trash info directory: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
baseName := filepath.Base(path)
|
|
||||||
|
|
||||||
// Generate a unique name in the trash directory
|
|
||||||
destName := baseName
|
|
||||||
for counter := 1; ; counter++ {
|
|
||||||
destPath := filepath.Join(filesDir, destName)
|
|
||||||
if _, err := os.Stat(destPath); os.IsNotExist(err) {
|
|
||||||
break
|
|
||||||
} else if err != nil {
|
|
||||||
return fmt.Errorf("cannot stat trash path: %w", err)
|
|
||||||
}
|
|
||||||
destName = fmt.Sprintf("%s.%d", baseName, counter)
|
|
||||||
}
|
|
||||||
|
|
||||||
destPath := filepath.Join(filesDir, destName)
|
|
||||||
if err := os.Rename(path, destPath); err != nil {
|
|
||||||
// Cross-filesystem move: fall back to copy+delete
|
|
||||||
return fmt.Errorf("cannot move to trash: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write .trashinfo file
|
|
||||||
absPath, err := filepath.Abs(path)
|
|
||||||
if err != nil {
|
|
||||||
absPath = path
|
|
||||||
}
|
|
||||||
now := time.Now().Format("2006-01-02T15:04:05")
|
|
||||||
infoContent := fmt.Sprintf("[Trash Info]\nPath=%s\nDeletionDate=%s\n", absPath, now)
|
|
||||||
infoPath := filepath.Join(infoDir, destName+".trashinfo")
|
|
||||||
if err := os.WriteFile(infoPath, []byte(infoContent), 0o600); err != nil {
|
|
||||||
// Best-effort: if info file fails, try to move the file back
|
|
||||||
_ = os.Rename(destPath, path)
|
|
||||||
return fmt.Errorf("cannot write trash info: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func MakeDir(parent string, name string) (string, error) {
|
func MakeDir(parent string, name string) (string, error) {
|
||||||
target := filepath.Join(parent, name)
|
target := filepath.Join(parent, name)
|
||||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
// Parents may be created ("a/b"), but the final directory must be new:
|
||||||
|
// MkdirAll silently "succeeded" on an existing name.
|
||||||
|
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.Mkdir(target, 0o755); err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return target, nil
|
return target, nil
|
||||||
|
|
|
||||||
|
|
@ -183,3 +183,58 @@ func TestRenamePathRejectsExistingTarget(t *testing.T) {
|
||||||
t.Fatalf("expected overwrite error %q, got %q", want, got)
|
t.Fatalf("expected overwrite error %q, got %q", want, got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCreateArchiveRefusesSourceAndSelfInclusion(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
src := filepath.Join(d, "data.tar")
|
||||||
|
if err := os.WriteFile(src, make([]byte, 100000), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(context.Background(), []string{src}, filepath.Join(d, ArchiveName([]string{src}, "tar")), nil); err == nil {
|
||||||
|
t.Fatal("archive over its own source must be refused")
|
||||||
|
}
|
||||||
|
if st, _ := os.Stat(src); st.Size() != 100000 {
|
||||||
|
t.Fatalf("source damaged: %d", st.Size())
|
||||||
|
}
|
||||||
|
|
||||||
|
proj := filepath.Join(d, "proj")
|
||||||
|
if err := os.MkdirAll(proj, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(context.Background(), []string{proj}, filepath.Join(proj, "proj.zip"), nil); err == nil {
|
||||||
|
t.Fatal("archive inside its source must be refused")
|
||||||
|
}
|
||||||
|
// Same through a symlinked parent.
|
||||||
|
if err := os.Symlink(proj, filepath.Join(d, "alias")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(context.Background(), []string{proj}, filepath.Join(d, "alias", "proj.zip"), nil); err == nil {
|
||||||
|
t.Fatal("archive inside its source via a symlinked dir must be refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateArchiveFailureKeepsOldArchive(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
arc := filepath.Join(d, "out.zip")
|
||||||
|
if err := os.WriteFile(arc, []byte("OLD"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
src := filepath.Join(d, "src")
|
||||||
|
if err := os.MkdirAll(src, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(filepath.Join(src, "f"), []byte("x"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := CreateArchive(ctx, []string{src}, arc, nil); err == nil {
|
||||||
|
t.Fatal("cancelled archive should fail")
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(arc); string(b) != "OLD" {
|
||||||
|
t.Fatalf("failed run replaced the old archive: %q", b)
|
||||||
|
}
|
||||||
|
if left, _ := filepath.Glob(filepath.Join(d, ".vcom-tmp-*")); len(left) != 0 {
|
||||||
|
t.Fatalf("temp files left: %v", left)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
437
internal/fs/qa_archive_trash_test.go
Normal file
437
internal/fs/qa_archive_trash_test.go
Normal file
|
|
@ -0,0 +1,437 @@
|
||||||
|
package vfs
|
||||||
|
|
||||||
|
// QA (v0.2.8): independent checks of the stage-1 fixes in archive.go and
|
||||||
|
// ops.go (U-P0-1 archive safety, U-P0-4 trash as default delete, MakeDir).
|
||||||
|
// Tests that expose a still-open bug are skipped with "BUG QA-n" and are
|
||||||
|
// described in plans/rework/05-qa-v0.2.8.md.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"archive/zip"
|
||||||
|
"compress/gzip"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func qaWrite(t *testing.T, p string, data string, mode os.FileMode) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte(data), mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every format: archiving a file whose archive name equals its own name
|
||||||
|
// into the same directory is refused and leaves the source intact.
|
||||||
|
func TestQAArchiveIntoSourceDirAllFormats(t *testing.T) {
|
||||||
|
cases := []struct{ name, format string }{
|
||||||
|
{"data.zip", "zip"},
|
||||||
|
{"data.tar", "tar"},
|
||||||
|
{"data.tar", "tar.gz"}, // data.tar -> data.tar.gz: allowed, different file
|
||||||
|
{"data.gz", "tar.gz"}, // data.gz -> data.tar.gz: allowed
|
||||||
|
}
|
||||||
|
for _, tc := range cases {
|
||||||
|
t.Run(tc.name+"->"+tc.format, func(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
src := filepath.Join(d, tc.name)
|
||||||
|
payload := strings.Repeat("z", 50000)
|
||||||
|
qaWrite(t, src, payload, 0o644)
|
||||||
|
arc := filepath.Join(d, ArchiveName([]string{src}, tc.format))
|
||||||
|
err := CreateArchive(context.Background(), []string{src}, arc, nil)
|
||||||
|
if arc == src {
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("archive equal to source must be refused")
|
||||||
|
}
|
||||||
|
} else if err != nil {
|
||||||
|
t.Fatalf("archive %s of %s should work: %v", arc, src, err)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(src); string(b) != payload {
|
||||||
|
t.Fatalf("source changed (len %d)", len(b))
|
||||||
|
}
|
||||||
|
if left, _ := filepath.Glob(filepath.Join(d, ".vcom-tmp-*")); len(left) != 0 {
|
||||||
|
t.Fatalf("temp files left: %v", left)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The produced archive must actually contain the source (zip, tar, tar.gz),
|
||||||
|
// i.e. the temp+rename path did not break the formats.
|
||||||
|
func TestQAArchiveContentsRoundTrip(t *testing.T) {
|
||||||
|
for _, format := range []string{"zip", "tar", "tar.gz"} {
|
||||||
|
t.Run(format, func(t *testing.T) {
|
||||||
|
d, out := t.TempDir(), t.TempDir()
|
||||||
|
qaWrite(t, filepath.Join(d, "proj", "a.txt"), "alpha", 0o644)
|
||||||
|
qaWrite(t, filepath.Join(d, "proj", "sub", "б.txt"), "бета", 0o644)
|
||||||
|
src := filepath.Join(d, "proj")
|
||||||
|
arc := filepath.Join(out, ArchiveName([]string{src}, format))
|
||||||
|
if err := CreateArchive(context.Background(), []string{src}, arc, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
names := qaListArchive(t, arc)
|
||||||
|
joined := strings.Join(names, "\n")
|
||||||
|
for _, want := range []string{"a.txt", "б.txt"} {
|
||||||
|
if !strings.Contains(joined, want) {
|
||||||
|
t.Fatalf("%s missing from %s: %v", want, arc, names)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func qaListArchive(t *testing.T, p string) []string {
|
||||||
|
t.Helper()
|
||||||
|
var names []string
|
||||||
|
switch {
|
||||||
|
case strings.HasSuffix(p, ".zip"):
|
||||||
|
zr, err := zip.OpenReader(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer zr.Close()
|
||||||
|
for _, f := range zr.File {
|
||||||
|
names = append(names, f.Name)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
f, err := os.Open(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
var r io.Reader = f
|
||||||
|
if strings.HasSuffix(p, ".gz") {
|
||||||
|
gz, err := gzip.NewReader(f)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r = gz
|
||||||
|
}
|
||||||
|
tr := tar.NewReader(r)
|
||||||
|
for {
|
||||||
|
h, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
names = append(names, h.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return names
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overwriting an existing archive after confirmation must not widen its
|
||||||
|
// permissions: a private 0600 archive became world-readable 0644.
|
||||||
|
func TestQAArchiveOverwriteKeepsPermissions(t *testing.T) {
|
||||||
|
d, out := t.TempDir(), t.TempDir()
|
||||||
|
qaWrite(t, filepath.Join(d, "secret.txt"), "pin 1234", 0o600)
|
||||||
|
arc := filepath.Join(out, "secret.zip")
|
||||||
|
qaWrite(t, arc, "old", 0o600)
|
||||||
|
if err := CreateArchive(context.Background(), []string{filepath.Join(d, "secret.txt")}, arc, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
st, err := os.Stat(arc)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if st.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("existing 0600 archive replaced with mode %o", st.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A long but valid file name (NAME_MAX is 255 bytes) can no longer be
|
||||||
|
// archived: the temp name ".vcom-tmp-<rand>-<name>" exceeds NAME_MAX.
|
||||||
|
func TestQAArchiveLongName(t *testing.T) {
|
||||||
|
d, out := t.TempDir(), t.TempDir()
|
||||||
|
base := strings.Repeat("n", 240)
|
||||||
|
src := filepath.Join(d, base+".txt")
|
||||||
|
qaWrite(t, src, "x", 0o644)
|
||||||
|
arc := filepath.Join(out, ArchiveName([]string{src}, "zip")) // 244 bytes: valid
|
||||||
|
if err := CreateArchive(context.Background(), []string{src}, arc, nil); err != nil {
|
||||||
|
t.Fatalf("archive with a valid %d-byte name failed: %v", len(filepath.Base(arc)), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A source that is a symlink to a directory, archived into that directory:
|
||||||
|
// the link is resolved by nobody, so the check does not see the archive is
|
||||||
|
// inside the (dereferenced) source. Make sure at least nothing is destroyed
|
||||||
|
// and the archive does not contain itself.
|
||||||
|
func TestQAArchiveSymlinkDirSourceIntoTarget(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
proj := filepath.Join(d, "proj")
|
||||||
|
qaWrite(t, filepath.Join(proj, "a.txt"), "alpha", 0o644)
|
||||||
|
link := filepath.Join(d, "link")
|
||||||
|
if err := os.Symlink(proj, link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
arc := filepath.Join(proj, "link.tar")
|
||||||
|
err := CreateArchive(context.Background(), []string{link}, arc, nil)
|
||||||
|
if b, _ := os.ReadFile(filepath.Join(proj, "a.txt")); string(b) != "alpha" {
|
||||||
|
t.Fatal("source content damaged")
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
for _, n := range qaListArchive(t, arc) {
|
||||||
|
if strings.Contains(n, "link.tar") || strings.Contains(n, ".vcom-tmp") {
|
||||||
|
t.Fatalf("archive contains itself: %v", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancelled archive into a directory with an existing archive: old archive
|
||||||
|
// stays, no temp file (tar and tar.gz paths, the developer only tested zip).
|
||||||
|
func TestQAArchiveCancelKeepsOldAllFormats(t *testing.T) {
|
||||||
|
for _, format := range []string{"zip", "tar", "tar.gz"} {
|
||||||
|
t.Run(format, func(t *testing.T) {
|
||||||
|
d, out := t.TempDir(), t.TempDir()
|
||||||
|
qaWrite(t, filepath.Join(d, "src", "f"), "x", 0o644)
|
||||||
|
src := filepath.Join(d, "src")
|
||||||
|
arc := filepath.Join(out, ArchiveName([]string{src}, format))
|
||||||
|
qaWrite(t, arc, "OLD", 0o644)
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cancel()
|
||||||
|
if err := CreateArchive(ctx, []string{src}, arc, nil); err == nil {
|
||||||
|
t.Fatal("cancelled archive should fail")
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(arc); string(b) != "OLD" {
|
||||||
|
t.Fatalf("old archive replaced: %q", b)
|
||||||
|
}
|
||||||
|
if left, _ := filepath.Glob(filepath.Join(out, ".vcom-tmp-*")); len(left) != 0 {
|
||||||
|
t.Fatalf("temp files left: %v", left)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Trash (now the default delete) ---------------------------------------
|
||||||
|
|
||||||
|
func qaTrashHome(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
home := t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
||||||
|
return filepath.Join(home, ".local", "share", "Trash")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Names with spaces and Cyrillic, and same-name collisions, all land in the
|
||||||
|
// trash under distinct names with a matching .trashinfo.
|
||||||
|
func TestQATrashNamesAndCollisions(t *testing.T) {
|
||||||
|
trash := qaTrashHome(t)
|
||||||
|
work := filepath.Join(os.Getenv("HOME"), "work") // same filesystem as HOME
|
||||||
|
names := []string{"my file.txt", "отчёт 2026.txt"}
|
||||||
|
for _, n := range names {
|
||||||
|
qaWrite(t, filepath.Join(work, "a", n), "A "+n, 0o644)
|
||||||
|
qaWrite(t, filepath.Join(work, "b", n), "B "+n, 0o644)
|
||||||
|
}
|
||||||
|
for _, sub := range []string{"a", "b"} {
|
||||||
|
for _, n := range names {
|
||||||
|
if err := MoveToTrash(filepath.Join(work, sub, n)); err != nil {
|
||||||
|
t.Fatalf("MoveToTrash(%s/%s): %v", sub, n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files, _ := os.ReadDir(filepath.Join(trash, "files"))
|
||||||
|
infos, _ := os.ReadDir(filepath.Join(trash, "info"))
|
||||||
|
if len(files) != 4 || len(infos) != 4 {
|
||||||
|
t.Fatalf("want 4 trashed files and 4 infos, got %d/%d", len(files), len(infos))
|
||||||
|
}
|
||||||
|
for _, f := range files {
|
||||||
|
if _, err := os.Stat(filepath.Join(trash, "info", f.Name()+".trashinfo")); err != nil {
|
||||||
|
t.Errorf("no trashinfo for %s", f.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The XDG trash spec requires Path= in .trashinfo to be percent-encoded
|
||||||
|
// (RFC 2396). Unencoded spaces/Cyrillic/newlines break restore in other
|
||||||
|
// tools (gio, trash-cli) — a newline in a file name corrupts the info file.
|
||||||
|
func TestQATrashInfoPathEncoded(t *testing.T) {
|
||||||
|
trash := qaTrashHome(t)
|
||||||
|
work := filepath.Join(os.Getenv("HOME"), "work")
|
||||||
|
p := filepath.Join(work, "my file\nx.txt")
|
||||||
|
qaWrite(t, p, "x", 0o644)
|
||||||
|
if err := MoveToTrash(p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, err := os.ReadFile(filepath.Join(trash, "info", "my file\nx.txt.trashinfo"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var pathLine string
|
||||||
|
for _, l := range strings.Split(string(b), "\n") {
|
||||||
|
if strings.HasPrefix(l, "Path=") {
|
||||||
|
pathLine = strings.TrimPrefix(l, "Path=")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
got, err := url.PathUnescape(pathLine)
|
||||||
|
if err != nil || got != p {
|
||||||
|
t.Fatalf("Path=%q does not decode to %q (err %v)", pathLine, p, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// XDG_DATA_HOME must be honoured ($XDG_DATA_HOME/Trash), otherwise vcom and
|
||||||
|
// the desktop use different trash cans.
|
||||||
|
func TestQATrashHonoursXDGDataHome(t *testing.T) {
|
||||||
|
home := t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
xdg := filepath.Join(home, "xdgdata")
|
||||||
|
t.Setenv("XDG_DATA_HOME", xdg)
|
||||||
|
p := filepath.Join(home, "f.txt")
|
||||||
|
qaWrite(t, p, "x", 0o644)
|
||||||
|
if err := MoveToTrash(p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(xdg, "Trash", "files", "f.txt")); err != nil {
|
||||||
|
t.Fatalf("file not in $XDG_DATA_HOME/Trash: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// otherDevice returns a writable directory on a different filesystem than
|
||||||
|
// home, or "" if none is available.
|
||||||
|
func otherDevice(t *testing.T, home string) string {
|
||||||
|
t.Helper()
|
||||||
|
var hs syscall.Stat_t
|
||||||
|
if err := syscall.Stat(home, &hs); err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
wd, _ := os.Getwd()
|
||||||
|
for _, cand := range []string{"/dev/shm", os.Getenv("XDG_RUNTIME_DIR"), "/var/tmp", wd} {
|
||||||
|
if cand == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var cs syscall.Stat_t
|
||||||
|
if err := syscall.Stat(cand, &cs); err != nil || cs.Dev == hs.Dev {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dir, err := os.MkdirTemp(cand, ".vcom-qa-*")
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||||
|
return dir
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// With trash as the default, deleting a file on another filesystem than
|
||||||
|
// $HOME (/tmp on tmpfs, /mnt, USB, a second disk) must still work: the spec
|
||||||
|
// uses $topdir/.Trash-$uid or a copy. Here MoveToTrash only does os.Rename
|
||||||
|
// and fails with EXDEV.
|
||||||
|
func TestQATrashCrossDevice(t *testing.T) {
|
||||||
|
home := qaTrashHome(t)
|
||||||
|
_ = home
|
||||||
|
dir := otherDevice(t, os.Getenv("HOME"))
|
||||||
|
if dir == "" {
|
||||||
|
t.Skip("no second filesystem available")
|
||||||
|
}
|
||||||
|
name := "vcom-qa-" + filepath.Base(dir) + ".txt"
|
||||||
|
p := filepath.Join(dir, name)
|
||||||
|
qaWrite(t, p, "x", 0o644)
|
||||||
|
cleanupTopdirTrash(t, dir, name)
|
||||||
|
if err := MoveToTrash(p); err != nil {
|
||||||
|
t.Fatalf("MoveToTrash across filesystems: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(p); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("file still in place")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A trashed broken symlink with the same name must not be silently replaced
|
||||||
|
// by the next trashed item (collision check uses Stat, which follows links).
|
||||||
|
func TestQATrashCollisionWithBrokenSymlink(t *testing.T) {
|
||||||
|
trash := qaTrashHome(t)
|
||||||
|
work := filepath.Join(os.Getenv("HOME"), "work")
|
||||||
|
if err := os.MkdirAll(work, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
link := filepath.Join(work, "x")
|
||||||
|
if err := os.Symlink("/nonexistent/target", link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := MoveToTrash(link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
qaWrite(t, link, "file now", 0o644)
|
||||||
|
if err := MoveToTrash(link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
files, _ := os.ReadDir(filepath.Join(trash, "files"))
|
||||||
|
if len(files) != 2 {
|
||||||
|
t.Fatalf("want 2 items in trash, got %d (first one overwritten)", len(files))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- MakeDir ---------------------------------------------------------------
|
||||||
|
|
||||||
|
func TestQAMakeDirEdgeCases(t *testing.T) {
|
||||||
|
d := t.TempDir()
|
||||||
|
if _, err := MakeDir(d, "a/b"); err != nil {
|
||||||
|
t.Fatalf("nested name: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := MakeDir(d, "a/b"); err == nil {
|
||||||
|
t.Fatal("existing nested dir must error")
|
||||||
|
}
|
||||||
|
if _, err := MakeDir(d, "a"); err == nil {
|
||||||
|
t.Fatal("existing parent must error")
|
||||||
|
}
|
||||||
|
qaWrite(t, filepath.Join(d, "file"), "x", 0o644)
|
||||||
|
if _, err := MakeDir(d, "file"); err == nil {
|
||||||
|
t.Fatal("name of an existing file must error")
|
||||||
|
}
|
||||||
|
if _, err := MakeDir(d, "папка с пробелом"); err != nil {
|
||||||
|
t.Fatalf("cyrillic name: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanupTopdirTrash removes name (and its .trashinfo) from the topdir trash
|
||||||
|
// of dir's filesystem after the test, and the trash dirs themselves if the
|
||||||
|
// test created them: the topdir is a real mount (/dev/shm, /run/user/...).
|
||||||
|
func cleanupTopdirTrash(t *testing.T, dir, name string) {
|
||||||
|
t.Helper()
|
||||||
|
var st syscall.Stat_t
|
||||||
|
if err := syscall.Stat(dir, &st); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
top := dir
|
||||||
|
for {
|
||||||
|
parent := filepath.Dir(top)
|
||||||
|
var ps syscall.Stat_t
|
||||||
|
if parent == top || syscall.Stat(parent, &ps) != nil || ps.Dev != st.Dev {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
top = parent
|
||||||
|
}
|
||||||
|
uid := strconv.Itoa(os.Getuid())
|
||||||
|
trashes := []string{filepath.Join(top, ".Trash-"+uid), filepath.Join(top, ".Trash", uid)}
|
||||||
|
existed := map[string]bool{}
|
||||||
|
for _, tr := range trashes {
|
||||||
|
if _, err := os.Lstat(tr); err == nil {
|
||||||
|
existed[tr] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
for _, tr := range trashes {
|
||||||
|
matches, _ := filepath.Glob(filepath.Join(tr, "files", name+"*"))
|
||||||
|
for _, m := range matches {
|
||||||
|
os.RemoveAll(m)
|
||||||
|
os.Remove(filepath.Join(tr, "info", filepath.Base(m)+".trashinfo"))
|
||||||
|
}
|
||||||
|
if !existed[tr] {
|
||||||
|
os.Remove(filepath.Join(tr, "files"))
|
||||||
|
os.Remove(filepath.Join(tr, "info"))
|
||||||
|
os.Remove(filepath.Join(tr, "expunged"))
|
||||||
|
os.Remove(tr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
26
internal/fs/qa_fixes_test.go
Normal file
26
internal/fs/qa_fixes_test.go
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
package vfs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QA-6: a new archive gets 0666 minus umask (as os.Create would), not the
|
||||||
|
// 0600 of the temp file and not a fixed 0644.
|
||||||
|
func TestNewArchiveModeFollowsUmask(t *testing.T) {
|
||||||
|
d, out := t.TempDir(), t.TempDir()
|
||||||
|
qaWrite(t, filepath.Join(d, "a.txt"), "x", 0o644)
|
||||||
|
arc := filepath.Join(out, "a.tar")
|
||||||
|
if err := CreateArchive(context.Background(), []string{filepath.Join(d, "a.txt")}, arc, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
st, err := os.Stat(arc)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if want := 0o666 &^ processUmask(); st.Mode().Perm() != want {
|
||||||
|
t.Fatalf("new archive mode %o, want %o", st.Mode().Perm(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -12,6 +12,7 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pkg/sftp"
|
"github.com/pkg/sftp"
|
||||||
|
|
@ -23,17 +24,61 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// SSHClient wraps an SSH connection and SFTP client for remote filesystem access.
|
// SSHClient wraps an SSH connection and SFTP client for remote filesystem access.
|
||||||
|
//
|
||||||
|
// It is safe for concurrent use: sshConn and sftpCli are set once by Connect
|
||||||
|
// and never reassigned, Close is serialized and only flips the closed flag
|
||||||
|
// and closes the underlying clients (which then fail calls with an error
|
||||||
|
// instead of panicking). Panels and jobs sharing a client use Acquire and
|
||||||
|
// Release; the client is closed when the last user releases it (N-P0-8).
|
||||||
type SSHClient struct {
|
type SSHClient struct {
|
||||||
// Host is the SSH host configuration used to establish the connection.
|
// Host is the SSH host configuration used to establish the connection.
|
||||||
Host SSHHost
|
Host SSHHost
|
||||||
|
|
||||||
sshConn *ssh.Client
|
sshConn *ssh.Client // immutable after Connect
|
||||||
sftpCli *sftp.Client
|
sftpCli *sftp.Client // immutable after Connect
|
||||||
|
|
||||||
|
closeMu sync.Mutex
|
||||||
|
closed atomic.Bool
|
||||||
|
users atomic.Int32
|
||||||
|
|
||||||
keepaliveStop chan struct{}
|
keepaliveStop chan struct{}
|
||||||
keepaliveWg sync.WaitGroup
|
keepaliveWg sync.WaitGroup
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var errNotConnected = errors.New("not connected")
|
||||||
|
|
||||||
|
// unusable reports whether the client cannot serve requests.
|
||||||
|
func (c *SSHClient) unusable() bool {
|
||||||
|
return c == nil || c.sftpCli == nil || c.sshConn == nil || c.closed.Load()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire registers one more user of the client (a panel or a job).
|
||||||
|
func (c *SSHClient) Acquire() {
|
||||||
|
if c != nil {
|
||||||
|
c.users.Add(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release drops one user; the last Release closes the client. Connect
|
||||||
|
// returns a client with one user (the caller).
|
||||||
|
func (c *SSHClient) Release() error {
|
||||||
|
if c == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if c.users.Add(-1) <= 0 {
|
||||||
|
return c.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Users reports the current number of users (for tests and logs).
|
||||||
|
func (c *SSHClient) Users() int {
|
||||||
|
if c == nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return int(c.users.Load())
|
||||||
|
}
|
||||||
|
|
||||||
// Connect establishes an SSH connection to the remote host and opens an SFTP session.
|
// Connect establishes an SSH connection to the remote host and opens an SFTP session.
|
||||||
// It uses key-based authentication if IdentityFile is set, otherwise falls back to password auth.
|
// It uses key-based authentication if IdentityFile is set, otherwise falls back to password auth.
|
||||||
func Connect(host SSHHost) (*SSHClient, error) {
|
func Connect(host SSHHost) (*SSHClient, error) {
|
||||||
|
|
@ -42,7 +87,7 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
||||||
return nil, fmt.Errorf("ssh auth: %w", err)
|
return nil, fmt.Errorf("ssh auth: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
hostKeyCB, err := tofuHostKeyCallback()
|
hostKeyCB, hostKeyAlgos, err := tofuHostKeyCallback(host.Addr())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("host key verification: %w", err)
|
return nil, fmt.Errorf("host key verification: %w", err)
|
||||||
}
|
}
|
||||||
|
|
@ -53,10 +98,11 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
config := &ssh.ClientConfig{
|
config := &ssh.ClientConfig{
|
||||||
User: user,
|
User: user,
|
||||||
Auth: authMethods,
|
Auth: authMethods,
|
||||||
HostKeyCallback: hostKeyCB,
|
HostKeyCallback: hostKeyCB,
|
||||||
Timeout: 15 * time.Second,
|
HostKeyAlgorithms: hostKeyAlgos,
|
||||||
|
Timeout: 15 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
addr := host.Addr()
|
addr := host.Addr()
|
||||||
|
|
@ -77,6 +123,7 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
||||||
sftpCli: sftpCli,
|
sftpCli: sftpCli,
|
||||||
keepaliveStop: make(chan struct{}),
|
keepaliveStop: make(chan struct{}),
|
||||||
}
|
}
|
||||||
|
client.users.Store(1)
|
||||||
|
|
||||||
// Start keepalive goroutine — sends keepalive@openssh.com every 30s
|
// Start keepalive goroutine — sends keepalive@openssh.com every 30s
|
||||||
// to prevent the SSH server from dropping the connection during inactivity.
|
// to prevent the SSH server from dropping the connection during inactivity.
|
||||||
|
|
@ -108,30 +155,33 @@ func Connect(host SSHHost) (*SSHClient, error) {
|
||||||
// previously recorded entry is rejected outright, since that's the signature
|
// previously recorded entry is rejected outright, since that's the signature
|
||||||
// of a man-in-the-middle attack or a legitimately reissued key that the user
|
// of a man-in-the-middle attack or a legitimately reissued key that the user
|
||||||
// must verify and update manually (e.g. via `ssh-keygen -R <host>`).
|
// must verify and update manually (e.g. via `ssh-keygen -R <host>`).
|
||||||
func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
|
//
|
||||||
|
// Lines of known_hosts that cannot be parsed (unknown key types) are skipped,
|
||||||
|
// see knownHostsDB. It also returns the host key algorithms to offer for addr.
|
||||||
|
func tofuHostKeyCallback(addr string) (ssh.HostKeyCallback, []string, error) {
|
||||||
khPath := KnownHostsPath()
|
khPath := KnownHostsPath()
|
||||||
if khPath == "" {
|
if khPath == "" {
|
||||||
return nil, fmt.Errorf("cannot determine known_hosts path")
|
return nil, nil, fmt.Errorf("cannot determine known_hosts path")
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := os.MkdirAll(filepath.Dir(khPath), 0o700); err != nil {
|
if err := os.MkdirAll(filepath.Dir(khPath), 0o700); err != nil {
|
||||||
return nil, fmt.Errorf("create ssh dir: %w", err)
|
return nil, nil, fmt.Errorf("create ssh dir: %w", err)
|
||||||
}
|
}
|
||||||
if _, err := os.Stat(khPath); os.IsNotExist(err) {
|
if _, err := os.Stat(khPath); os.IsNotExist(err) {
|
||||||
f, err := os.OpenFile(khPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
f, err := os.OpenFile(khPath, os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("create known_hosts: %w", err)
|
return nil, nil, fmt.Errorf("create known_hosts: %w", err)
|
||||||
}
|
}
|
||||||
f.Close()
|
f.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
verify, err := knownhosts.New(khPath)
|
db, err := loadKnownHosts(khPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("parse known_hosts: %w", err)
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||||
err := verify(hostname, remote, key)
|
err := db.verify(hostname, remote, key)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -141,6 +191,10 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
|
||||||
return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for %s! This may indicate a man-in-the-middle attack, or the server's key was legitimately reissued. Refusing to connect; run `ssh-keygen -R %s` to remove the stale entry once you've verified the new key: %w", hostname, hostname, err)
|
return fmt.Errorf("REMOTE HOST IDENTIFICATION HAS CHANGED for %s! This may indicate a man-in-the-middle attack, or the server's key was legitimately reissued. Refusing to connect; run `ssh-keygen -R %s` to remove the stale entry once you've verified the new key: %w", hostname, hostname, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if db.unsupportedOnly(hostname) {
|
||||||
|
return fmt.Errorf("the host key of %s is recorded in %s only with a key type vcom does not support yet; refusing to trust a different key automatically. Add a supported key for it (e.g. from `ssh-keyscan -t ed25519`) after verifying it: %w", hostname, khPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
// Unknown host: trust on first use and remember the key.
|
// Unknown host: trust on first use and remember the key.
|
||||||
line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
|
line := knownhosts.Line([]string{knownhosts.Normalize(hostname)}, key)
|
||||||
f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
f, ferr := os.OpenFile(khPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||||
|
|
@ -152,7 +206,7 @@ func tofuHostKeyCallback() (ssh.HostKeyCallback, error) {
|
||||||
return fmt.Errorf("cannot save host key for %s: %w", hostname, werr)
|
return fmt.Errorf("cannot save host key for %s: %w", hostname, werr)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}, nil
|
}, db.hostKeyAlgorithms(addr), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// sshAgentAuth connects to the running ssh-agent (via SSH_AUTH_SOCK) and
|
// sshAgentAuth connects to the running ssh-agent (via SSH_AUTH_SOCK) and
|
||||||
|
|
@ -258,56 +312,56 @@ func authMethodsForHost(host SSHHost) ([]ssh.AuthMethod, error) {
|
||||||
|
|
||||||
// ReadDir reads the contents of a remote directory and returns os.FileInfo entries.
|
// ReadDir reads the contents of a remote directory and returns os.FileInfo entries.
|
||||||
func (c *SSHClient) ReadDir(dirPath string) ([]os.FileInfo, error) {
|
func (c *SSHClient) ReadDir(dirPath string) ([]os.FileInfo, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return nil, fmt.Errorf("not connected")
|
return nil, errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.ReadDir(dirPath)
|
return c.sftpCli.ReadDir(dirPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Lstat returns file information without following symlinks.
|
// Lstat returns file information without following symlinks.
|
||||||
func (c *SSHClient) Lstat(path string) (os.FileInfo, error) {
|
func (c *SSHClient) Lstat(path string) (os.FileInfo, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return nil, fmt.Errorf("not connected")
|
return nil, errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.Lstat(path)
|
return c.sftpCli.Lstat(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stat returns file information following symlinks.
|
// Stat returns file information following symlinks.
|
||||||
func (c *SSHClient) Stat(path string) (os.FileInfo, error) {
|
func (c *SSHClient) Stat(path string) (os.FileInfo, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return nil, fmt.Errorf("not connected")
|
return nil, errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.Stat(path)
|
return c.sftpCli.Stat(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadLink reads the target of a symbolic link.
|
// ReadLink reads the target of a symbolic link.
|
||||||
func (c *SSHClient) ReadLink(linkPath string) (string, error) {
|
func (c *SSHClient) ReadLink(linkPath string) (string, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return "", fmt.Errorf("not connected")
|
return "", errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.ReadLink(linkPath)
|
return c.sftpCli.ReadLink(linkPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RealPath resolves a path to its absolute form on the remote server.
|
// RealPath resolves a path to its absolute form on the remote server.
|
||||||
func (c *SSHClient) RealPath(p string) (string, error) {
|
func (c *SSHClient) RealPath(p string) (string, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return "", fmt.Errorf("not connected")
|
return "", errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.RealPath(p)
|
return c.sftpCli.RealPath(p)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReadFile opens a remote file for reading.
|
// ReadFile opens a remote file for reading.
|
||||||
func (c *SSHClient) ReadFile(filePath string) (io.ReadCloser, error) {
|
func (c *SSHClient) ReadFile(filePath string) (io.ReadCloser, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return nil, fmt.Errorf("not connected")
|
return nil, errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.Open(filePath)
|
return c.sftpCli.Open(filePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateFile opens a remote file for writing, creating it if it doesn't exist.
|
// CreateFile opens a remote file for writing, creating it if it doesn't exist.
|
||||||
func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) {
|
func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return nil, fmt.Errorf("not connected")
|
return nil, errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.Create(filePath)
|
return c.sftpCli.Create(filePath)
|
||||||
}
|
}
|
||||||
|
|
@ -315,8 +369,8 @@ func (c *SSHClient) CreateFile(filePath string) (io.WriteCloser, error) {
|
||||||
// MkdirAll creates a remote directory and any necessary parents.
|
// MkdirAll creates a remote directory and any necessary parents.
|
||||||
// If the directory already exists, it returns nil (no error).
|
// If the directory already exists, it returns nil (no error).
|
||||||
func (c *SSHClient) MkdirAll(dirPath string) error {
|
func (c *SSHClient) MkdirAll(dirPath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
// sftp doesn't have MkdirAll, so we implement it manually
|
// sftp doesn't have MkdirAll, so we implement it manually
|
||||||
// First check if the path already exists
|
// First check if the path already exists
|
||||||
|
|
@ -339,71 +393,92 @@ func (c *SSHClient) MkdirAll(dirPath string) error {
|
||||||
|
|
||||||
// Mkdir creates a single remote directory.
|
// Mkdir creates a single remote directory.
|
||||||
func (c *SSHClient) Mkdir(dirPath string) error {
|
func (c *SSHClient) Mkdir(dirPath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
|
}
|
||||||
|
return c.sftpCli.Mkdir(dirPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MkdirNew creates dirPath (and missing parents) and fails if dirPath
|
||||||
|
// already exists, like the local MakeDir: F7 with a taken name must report
|
||||||
|
// an error (QA-10).
|
||||||
|
func (c *SSHClient) MkdirNew(dirPath string) error {
|
||||||
|
if c.unusable() {
|
||||||
|
return errNotConnected
|
||||||
|
}
|
||||||
|
if _, err := c.sftpCli.Lstat(dirPath); err == nil {
|
||||||
|
return &os.PathError{Op: "mkdir", Path: dirPath, Err: os.ErrExist}
|
||||||
|
} else if !os.IsNotExist(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if parent := path.Dir(dirPath); parent != dirPath && parent != "." {
|
||||||
|
if err := c.MkdirAll(parent); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return c.sftpCli.Mkdir(dirPath)
|
return c.sftpCli.Mkdir(dirPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Remove deletes a remote file.
|
// Remove deletes a remote file.
|
||||||
func (c *SSHClient) Remove(filePath string) error {
|
func (c *SSHClient) Remove(filePath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.Remove(filePath)
|
return c.sftpCli.Remove(filePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemoveDirectory removes a remote directory (must be empty).
|
// RemoveDirectory removes a remote directory (must be empty).
|
||||||
func (c *SSHClient) RemoveDirectory(dirPath string) error {
|
func (c *SSHClient) RemoveDirectory(dirPath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.RemoveDirectory(dirPath)
|
return c.sftpCli.RemoveDirectory(dirPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rename moves/renames a remote file or directory.
|
// Rename moves/renames a remote file or directory.
|
||||||
func (c *SSHClient) Rename(oldPath, newPath string) error {
|
func (c *SSHClient) Rename(oldPath, newPath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
return c.sftpCli.Rename(oldPath, newPath)
|
return c.sftpCli.Rename(oldPath, newPath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close closes the SFTP session and SSH connection.
|
// Close closes the SFTP session and SSH connection. It is idempotent and
|
||||||
|
// safe to call concurrently with other methods, which then return errors.
|
||||||
func (c *SSHClient) Close() error {
|
func (c *SSHClient) Close() error {
|
||||||
|
if c == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c.closeMu.Lock()
|
||||||
|
defer c.closeMu.Unlock()
|
||||||
|
if c.closed.Load() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c.closed.Store(true)
|
||||||
|
|
||||||
// Stop the keepalive goroutine first
|
// Stop the keepalive goroutine first
|
||||||
if c.keepaliveStop != nil {
|
if c.keepaliveStop != nil {
|
||||||
select {
|
close(c.keepaliveStop)
|
||||||
case <-c.keepaliveStop:
|
|
||||||
// already closed
|
|
||||||
default:
|
|
||||||
close(c.keepaliveStop)
|
|
||||||
}
|
|
||||||
c.keepaliveWg.Wait()
|
c.keepaliveWg.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
var firstErr error
|
var firstErr error
|
||||||
|
|
||||||
if c.sftpCli != nil {
|
if c.sftpCli != nil {
|
||||||
if err := c.sftpCli.Close(); err != nil {
|
if err := c.sftpCli.Close(); err != nil {
|
||||||
firstErr = err
|
firstErr = err
|
||||||
}
|
}
|
||||||
c.sftpCli = nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.sshConn != nil {
|
if c.sshConn != nil {
|
||||||
if err := c.sshConn.Close(); err != nil && firstErr == nil {
|
if err := c.sshConn.Close(); err != nil && firstErr == nil {
|
||||||
firstErr = err
|
firstErr = err
|
||||||
}
|
}
|
||||||
c.sshConn = nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return firstErr
|
return firstErr
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsConnected returns true if the client has an active connection.
|
// IsConnected returns true if the client has an active connection.
|
||||||
func (c *SSHClient) IsConnected() bool {
|
func (c *SSHClient) IsConnected() bool {
|
||||||
return c.sftpCli != nil && c.sshConn != nil
|
return !c.unusable()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShellQuote wraps s in single quotes so it's safe to interpolate into a
|
// ShellQuote wraps s in single quotes so it's safe to interpolate into a
|
||||||
|
|
@ -417,8 +492,8 @@ func ShellQuote(s string) string {
|
||||||
|
|
||||||
// Exec runs a shell command on the remote server and returns combined output.
|
// Exec runs a shell command on the remote server and returns combined output.
|
||||||
func (c *SSHClient) Exec(cmd string) ([]byte, error) {
|
func (c *SSHClient) Exec(cmd string) ([]byte, error) {
|
||||||
if c.sshConn == nil {
|
if c.unusable() {
|
||||||
return nil, fmt.Errorf("not connected")
|
return nil, errNotConnected
|
||||||
}
|
}
|
||||||
session, err := c.sshConn.NewSession()
|
session, err := c.sshConn.NewSession()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -431,8 +506,8 @@ func (c *SSHClient) Exec(cmd string) ([]byte, error) {
|
||||||
// ExecWithProgress runs a shell command on the remote server and calls onLine
|
// ExecWithProgress runs a shell command on the remote server and calls onLine
|
||||||
// for each line of stdout output.
|
// for each line of stdout output.
|
||||||
func (c *SSHClient) ExecWithProgress(cmd string, onLine func(line string)) error {
|
func (c *SSHClient) ExecWithProgress(cmd string, onLine func(line string)) error {
|
||||||
if c.sshConn == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
session, err := c.sshConn.NewSession()
|
session, err := c.sshConn.NewSession()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
@ -471,12 +546,17 @@ func (c *SSHClient) SameHostAs(other *SSHClient) bool {
|
||||||
|
|
||||||
// RemoveRecursive recursively deletes a remote file or directory.
|
// RemoveRecursive recursively deletes a remote file or directory.
|
||||||
// For directories, it walks and removes all children first.
|
// For directories, it walks and removes all children first.
|
||||||
func (c *SSHClient) RemoveRecursive(path string) error {
|
func (c *SSHClient) RemoveRecursive(target string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
|
// Clean first: lstat("link/") resolves the link on POSIX servers, and
|
||||||
|
// the target's contents would be deleted (QA-9).
|
||||||
|
path := path.Clean(target)
|
||||||
|
|
||||||
info, err := c.sftpCli.Stat(path)
|
// Lstat, not Stat: a symlink to a directory must be removed as a link.
|
||||||
|
// Following it would delete the contents of the link's target (N-P0-3).
|
||||||
|
info, err := c.sftpCli.Lstat(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
@ -525,8 +605,8 @@ func (c *SSHClient) RemoveRecursive(path string) error {
|
||||||
// CopyFileToRemote copies a local file to a remote destination via SFTP.
|
// CopyFileToRemote copies a local file to a remote destination via SFTP.
|
||||||
// It creates parent directories as needed.
|
// It creates parent directories as needed.
|
||||||
func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error {
|
func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
|
|
||||||
localFile, err := os.Open(localPath)
|
localFile, err := os.Open(localPath)
|
||||||
|
|
@ -558,8 +638,8 @@ func (c *SSHClient) CopyFileToRemote(localPath, remotePath string) error {
|
||||||
// CopyFileFromRemote copies a remote file to a local destination via SFTP.
|
// CopyFileFromRemote copies a remote file to a local destination via SFTP.
|
||||||
// It creates parent directories as needed.
|
// It creates parent directories as needed.
|
||||||
func (c *SSHClient) CopyFileFromRemote(remotePath, localPath string) error {
|
func (c *SSHClient) CopyFileFromRemote(remotePath, localPath string) error {
|
||||||
if c.sftpCli == nil {
|
if c.unusable() {
|
||||||
return fmt.Errorf("not connected")
|
return errNotConnected
|
||||||
}
|
}
|
||||||
|
|
||||||
remoteFile, err := c.sftpCli.Open(remotePath)
|
remoteFile, err := c.sftpCli.Open(remotePath)
|
||||||
|
|
@ -681,10 +761,10 @@ func (c *SSHClient) copyDirFromRemote(remoteDir, localDir string, onFile func(pa
|
||||||
// by streaming the file contents through the local machine. Both SFTP connections
|
// by streaming the file contents through the local machine. Both SFTP connections
|
||||||
// must be active (connected).
|
// must be active (connected).
|
||||||
func CopyFileBetweenRemotes(srcClient, dstClient *SSHClient, srcPath, dstPath string) error {
|
func CopyFileBetweenRemotes(srcClient, dstClient *SSHClient, srcPath, dstPath string) error {
|
||||||
if srcClient.sftpCli == nil {
|
if srcClient.unusable() {
|
||||||
return fmt.Errorf("source client not connected")
|
return fmt.Errorf("source client not connected")
|
||||||
}
|
}
|
||||||
if dstClient.sftpCli == nil {
|
if dstClient.unusable() {
|
||||||
return fmt.Errorf("destination client not connected")
|
return fmt.Errorf("destination client not connected")
|
||||||
}
|
}
|
||||||
if srcClient.SameHostAs(dstClient) && path.Clean(srcPath) == path.Clean(dstPath) {
|
if srcClient.SameHostAs(dstClient) && path.Clean(srcPath) == path.Clean(dstPath) {
|
||||||
|
|
@ -781,8 +861,10 @@ func (c *SSHClient) Walk(root string, walkFn walkFunc) error {
|
||||||
|
|
||||||
func (c *SSHClient) walk(dirPath string, walkFn walkFunc, info os.FileInfo) error {
|
func (c *SSHClient) walk(dirPath string, walkFn walkFunc, info os.FileInfo) error {
|
||||||
if info == nil {
|
if info == nil {
|
||||||
|
// The root is examined with Lstat like every other entry, so a
|
||||||
|
// symlink root is reported as a leaf and never descended into.
|
||||||
var statErr error
|
var statErr error
|
||||||
info, statErr = c.sftpCli.Stat(dirPath)
|
info, statErr = c.sftpCli.Lstat(dirPath)
|
||||||
if statErr != nil {
|
if statErr != nil {
|
||||||
if fnErr := walkFn(dirPath, nil, statErr); fnErr != nil && fnErr != filepathSkipDir {
|
if fnErr := walkFn(dirPath, nil, statErr); fnErr != nil && fnErr != filepathSkipDir {
|
||||||
return fnErr
|
return fnErr
|
||||||
|
|
|
||||||
134
internal/fs/remote/client_test.go
Normal file
134
internal/fs/remote/client_test.go
Normal file
|
|
@ -0,0 +1,134 @@
|
||||||
|
package remote
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// B1 / N-P0-3: deleting a remote symlink that points to a directory wiped
|
||||||
|
// the target directory.
|
||||||
|
func TestRemoveRecursiveSymlinkToDir(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
target := filepath.Join(dir, "precious")
|
||||||
|
writeFile(t, filepath.Join(target, "a.txt"), 10, 0o644)
|
||||||
|
writeFile(t, filepath.Join(target, "sub", "b.txt"), 10, 0o644)
|
||||||
|
link := filepath.Join(dir, "link")
|
||||||
|
if err := os.Symlink(target, link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := c.RemoveRecursive(link); err != nil {
|
||||||
|
t.Fatalf("RemoveRecursive(link): %v", err)
|
||||||
|
}
|
||||||
|
for _, p := range []string{"a.txt", "sub/b.txt"} {
|
||||||
|
if _, err := os.Stat(filepath.Join(target, p)); err != nil {
|
||||||
|
t.Errorf("deleting the link removed target content %s: %v", p, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(link); !os.IsNotExist(err) {
|
||||||
|
t.Errorf("the link itself must be gone, Lstat err=%v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemoveRecursiveDirKeepsLinkedTarget(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
outside := filepath.Join(dir, "outside")
|
||||||
|
writeFile(t, filepath.Join(outside, "keep.txt"), 10, 0o644)
|
||||||
|
tree := filepath.Join(dir, "tree")
|
||||||
|
writeFile(t, filepath.Join(tree, "f.txt"), 10, 0o644)
|
||||||
|
if err := os.Symlink(outside, filepath.Join(tree, "to-outside")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := c.RemoveRecursive(tree); err != nil {
|
||||||
|
t.Fatalf("RemoveRecursive(tree): %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(tree); !os.IsNotExist(err) {
|
||||||
|
t.Errorf("tree should be gone: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(outside, "keep.txt")); err != nil {
|
||||||
|
t.Errorf("symlink inside the tree was followed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRemoveRecursiveFileAndDir(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
f := filepath.Join(dir, "f.bin")
|
||||||
|
writeFile(t, f, 100, 0o644)
|
||||||
|
if err := c.RemoveRecursive(f); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
d := filepath.Join(dir, "d")
|
||||||
|
writeFile(t, filepath.Join(d, "x", "y", "z.bin"), 100, 0o644)
|
||||||
|
if err := c.RemoveRecursive(d); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, p := range []string{f, d} {
|
||||||
|
if _, err := os.Lstat(p); !os.IsNotExist(err) {
|
||||||
|
t.Errorf("%s still exists", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// B5 / N-P0-8: Close() concurrently with use raced on the client fields and
|
||||||
|
// could call a method on a nil *sftp.Client.
|
||||||
|
func TestCloseRace(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
done := make(chan struct{})
|
||||||
|
panicked := make(chan any, 1)
|
||||||
|
for w := 0; w < 4; w++ {
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
panicked <- r
|
||||||
|
}
|
||||||
|
done <- struct{}{}
|
||||||
|
}()
|
||||||
|
for i := 0; i < 500; i++ {
|
||||||
|
c.ReadDir(dir)
|
||||||
|
c.Lstat(dir)
|
||||||
|
c.IsConnected()
|
||||||
|
c.Exec("true")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
go c.Close()
|
||||||
|
c.Close()
|
||||||
|
for w := 0; w < 4; w++ {
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case r := <-panicked:
|
||||||
|
t.Fatalf("panic during concurrent Close: %v", r)
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
if c.IsConnected() {
|
||||||
|
t.Fatal("client still reports connected after Close")
|
||||||
|
}
|
||||||
|
if _, err := c.ReadDir(dir); err == nil {
|
||||||
|
t.Fatal("ReadDir after Close must fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcquireReleaseClosesOnLastUser(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
if c.Users() != 1 {
|
||||||
|
t.Fatalf("Connect should return one user, got %d", c.Users())
|
||||||
|
}
|
||||||
|
c.Acquire() // e.g. mirrored pane
|
||||||
|
c.Release() // first pane leaves the host
|
||||||
|
if _, err := c.ReadDir(dir); err != nil {
|
||||||
|
t.Fatalf("client closed while still in use: %v", err)
|
||||||
|
}
|
||||||
|
c.Release() // last user
|
||||||
|
if c.IsConnected() {
|
||||||
|
t.Fatal("last Release must close the client")
|
||||||
|
}
|
||||||
|
var nilClient *SSHClient
|
||||||
|
nilClient.Acquire()
|
||||||
|
if err := nilClient.Release(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
28
internal/fs/remote/harness_test.go
Normal file
28
internal/fs/remote/harness_test.go
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
package remote
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// setup starts an in-process SSH server (serving the real filesystem),
|
||||||
|
// connects an SSHClient to it with an isolated HOME and returns the client
|
||||||
|
// and a scratch directory.
|
||||||
|
func setup(t *testing.T) (*sshtest.Server, *SSHClient, string) {
|
||||||
|
t.Helper()
|
||||||
|
sshtest.IsolatedHome(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
c, err := Connect(SSHHost{Name: "test", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { c.Close() })
|
||||||
|
return srv, c, t.TempDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, p string, size int, mode os.FileMode) {
|
||||||
|
t.Helper()
|
||||||
|
sshtest.WriteRandom(t, p, size, mode)
|
||||||
|
}
|
||||||
202
internal/fs/remote/knownhosts.go
Normal file
202
internal/fs/remote/knownhosts.go
Normal file
|
|
@ -0,0 +1,202 @@
|
||||||
|
package remote
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
"golang.org/x/crypto/ssh/knownhosts"
|
||||||
|
)
|
||||||
|
|
||||||
|
// knownHostsDB is a tolerant view of ~/.ssh/known_hosts (QA-11).
|
||||||
|
//
|
||||||
|
// knownhosts.New rejects the whole file when a single line cannot be parsed,
|
||||||
|
// e.g. a key type x/crypto/ssh does not implement such as OpenSSH 10's
|
||||||
|
// "ssh-mldsa44-ed25519". OpenSSH skips such lines, and so do we: they are
|
||||||
|
// left out (with a warning in the log) and the rest of the file is used.
|
||||||
|
//
|
||||||
|
// A host whose skipped lines are its only record is not silently re-trusted
|
||||||
|
// on first use: unsupported records which apply to it make the unknown-host
|
||||||
|
// path refuse instead, since we cannot check the key the user already
|
||||||
|
// accepted.
|
||||||
|
type knownHostsDB struct {
|
||||||
|
verify ssh.HostKeyCallback
|
||||||
|
// unsupported matches the host patterns of skipped lines (with a
|
||||||
|
// placeholder key); nil when nothing was skipped.
|
||||||
|
unsupported ssh.HostKeyCallback
|
||||||
|
// hasCA: the file has @cert-authority lines, so known keys of a host
|
||||||
|
// cannot be told apart from CA keys; host key algorithms are then left
|
||||||
|
// at the x/crypto defaults.
|
||||||
|
hasCA bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// placeholderKey never matches a real host key; it is used to probe which
|
||||||
|
// keys are recorded for a host and as the key of placeholder lines.
|
||||||
|
var placeholderKey = func() ssh.PublicKey {
|
||||||
|
priv := ed25519.NewKeyFromSeed(make([]byte, ed25519.SeedSize))
|
||||||
|
pub, err := ssh.NewPublicKey(priv.Public())
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return pub
|
||||||
|
}()
|
||||||
|
|
||||||
|
var probeRemote = &net.TCPAddr{IP: net.IPv4zero, Port: 0}
|
||||||
|
|
||||||
|
// loadKnownHosts reads khPath, dropping lines knownhosts cannot parse.
|
||||||
|
func loadKnownHosts(khPath string) (*knownHostsDB, error) {
|
||||||
|
data, err := os.ReadFile(khPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("read known_hosts: %w", err)
|
||||||
|
}
|
||||||
|
lines := strings.Split(string(data), "\n")
|
||||||
|
|
||||||
|
verify, skipped, err := parseTolerant(lines, khPath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
db := &knownHostsDB{verify: verify}
|
||||||
|
for _, l := range lines {
|
||||||
|
if strings.HasPrefix(strings.TrimSpace(l), "@cert-authority") {
|
||||||
|
db.hasCA = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var placeholders []string
|
||||||
|
marshalled := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(placeholderKey)))
|
||||||
|
for _, n := range skipped {
|
||||||
|
fields := strings.Fields(lines[n])
|
||||||
|
if len(fields) == 0 || strings.HasPrefix(fields[0], "@") {
|
||||||
|
// @revoked / @cert-authority with an unsupported key: such a
|
||||||
|
// key can never be negotiated, nothing to protect.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
placeholders = append(placeholders, fields[0]+" "+marshalled)
|
||||||
|
}
|
||||||
|
if len(placeholders) > 0 {
|
||||||
|
unsupported, _, err := parseTolerant(placeholders, "")
|
||||||
|
if err == nil {
|
||||||
|
db.unsupported = unsupported
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseTolerant feeds lines to knownhosts.New, commenting out every line it
|
||||||
|
// rejects, and returns the callback and the indexes of the rejected lines.
|
||||||
|
// origin names the file in log warnings ("" = no warnings).
|
||||||
|
func parseTolerant(lines []string, origin string) (ssh.HostKeyCallback, []int, error) {
|
||||||
|
work := make([]string, len(lines))
|
||||||
|
copy(work, lines)
|
||||||
|
var skipped []int
|
||||||
|
skip := func(i int, why string) {
|
||||||
|
if origin != "" {
|
||||||
|
log.Printf("[SSH] %s:%d: skipping known_hosts line: %s", origin, i+1, why)
|
||||||
|
}
|
||||||
|
work[i] = "#"
|
||||||
|
skipped = append(skipped, i)
|
||||||
|
}
|
||||||
|
for i, l := range work {
|
||||||
|
// bufio.Scanner in knownhosts fails the whole file on an over-long line.
|
||||||
|
if len(l) >= bufio.MaxScanTokenSize-1 {
|
||||||
|
skip(i, "line too long")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tmp, err := os.CreateTemp("", "vcom-known_hosts-*")
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||||
|
}
|
||||||
|
tmpPath := tmp.Name()
|
||||||
|
tmp.Close()
|
||||||
|
defer os.Remove(tmpPath)
|
||||||
|
|
||||||
|
prefix := "knownhosts: " + tmpPath + ":"
|
||||||
|
for attempt := 0; attempt <= len(work); attempt++ {
|
||||||
|
if err := os.WriteFile(tmpPath, []byte(strings.Join(work, "\n")+"\n"), 0o600); err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||||
|
}
|
||||||
|
cb, err := knownhosts.New(tmpPath)
|
||||||
|
if err == nil {
|
||||||
|
return cb, skipped, nil
|
||||||
|
}
|
||||||
|
msg := err.Error()
|
||||||
|
rest, ok := strings.CutPrefix(msg, prefix)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||||
|
}
|
||||||
|
numStr, why, _ := strings.Cut(rest, ":")
|
||||||
|
n, perr := strconv.Atoi(numStr)
|
||||||
|
if perr != nil || n < 1 || n > len(work) || work[n-1] == "#" {
|
||||||
|
return nil, nil, fmt.Errorf("parse known_hosts: %w", err)
|
||||||
|
}
|
||||||
|
skip(n-1, strings.TrimSpace(why))
|
||||||
|
}
|
||||||
|
return nil, nil, errors.New("parse known_hosts: too many invalid lines")
|
||||||
|
}
|
||||||
|
|
||||||
|
// unsupportedOnly reports whether hostname has records only in lines that
|
||||||
|
// were skipped (so a new key must not be trusted on first use).
|
||||||
|
func (db *knownHostsDB) unsupportedOnly(hostname string) bool {
|
||||||
|
if db.unsupported == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
var keyErr *knownhosts.KeyError
|
||||||
|
err := db.unsupported(hostname, probeRemote, placeholderKey)
|
||||||
|
if err == nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return errors.As(err, &keyErr) && len(keyErr.Want) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// plainHostKeyAlgos is what the client can verify without certificates.
|
||||||
|
var plainHostKeyAlgos = []string{
|
||||||
|
ssh.KeyAlgoED25519,
|
||||||
|
ssh.KeyAlgoECDSA256, ssh.KeyAlgoECDSA384, ssh.KeyAlgoECDSA521,
|
||||||
|
ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA,
|
||||||
|
}
|
||||||
|
|
||||||
|
// hostKeyAlgorithms returns the host key algorithms to offer for addr:
|
||||||
|
// those of keys already recorded for it first (like OpenSSH), then the rest
|
||||||
|
// of the plain algorithms. Without that, x/crypto prefers ECDSA, and a
|
||||||
|
// server known only by its ed25519 key looks like a changed host key.
|
||||||
|
// Only algorithms x/crypto implements are returned, never the type of a
|
||||||
|
// skipped line. nil means "use the defaults".
|
||||||
|
func (db *knownHostsDB) hostKeyAlgorithms(addr string) []string {
|
||||||
|
if db.hasCA {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var keyErr *knownhosts.KeyError
|
||||||
|
if err := db.verify(addr, probeRemote, placeholderKey); !errors.As(err, &keyErr) || len(keyErr.Want) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
known := map[string]bool{}
|
||||||
|
for _, k := range keyErr.Want {
|
||||||
|
t := k.Key.Type()
|
||||||
|
if t == ssh.KeyAlgoRSA {
|
||||||
|
known[ssh.KeyAlgoRSASHA512] = true
|
||||||
|
known[ssh.KeyAlgoRSASHA256] = true
|
||||||
|
}
|
||||||
|
known[t] = true
|
||||||
|
}
|
||||||
|
var first, rest []string
|
||||||
|
for _, a := range plainHostKeyAlgos {
|
||||||
|
if known[a] {
|
||||||
|
first = append(first, a)
|
||||||
|
} else {
|
||||||
|
rest = append(rest, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(first) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return append(first, rest...)
|
||||||
|
}
|
||||||
146
internal/fs/remote/knownhosts_test.go
Normal file
146
internal/fs/remote/knownhosts_test.go
Normal file
|
|
@ -0,0 +1,146 @@
|
||||||
|
package remote
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
"golang.org/x/crypto/ssh/knownhosts"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Unsupported OpenSSH 10 post-quantum key (QA-11). The blob only has to look
|
||||||
|
// like base64; x/crypto rejects it by its algorithm name.
|
||||||
|
const mldsaKey = "ssh-mldsa44-ed25519 AAAAFHNzaC1tbGRzYTQ0LWVkMjU1MTkAAAAA"
|
||||||
|
|
||||||
|
func writeKnownHosts(t *testing.T, lines ...string) string {
|
||||||
|
t.Helper()
|
||||||
|
p := filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts")
|
||||||
|
if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectTo(srv *sshtest.Server) (*SSHClient, error) {
|
||||||
|
return Connect(SSHHost{Name: "h", HostName: "127.0.0.1", Port: srv.Port(), User: "u", Password: srv.Password})
|
||||||
|
}
|
||||||
|
|
||||||
|
func hostPattern(srv *sshtest.Server) string {
|
||||||
|
return knownhosts.Normalize(fmt.Sprintf("127.0.0.1:%s", srv.Port()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unparseable lines for other hosts (unknown key type, garbage, bad hash)
|
||||||
|
// are skipped; the connection proceeds and the new key is recorded.
|
||||||
|
func TestKnownHostsSkipsUnparseableLines(t *testing.T) {
|
||||||
|
sshtest.IsolatedHome(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
kh := writeKnownHosts(t,
|
||||||
|
"# comment",
|
||||||
|
"otherhost "+mldsaKey,
|
||||||
|
"garbage-without-key",
|
||||||
|
"|2|bad|hash ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl",
|
||||||
|
"@revoked * "+mldsaKey,
|
||||||
|
)
|
||||||
|
c, err := connectTo(srv)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect: %v", err)
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
data, _ := os.ReadFile(kh)
|
||||||
|
if !strings.Contains(string(data), "otherhost "+mldsaKey) {
|
||||||
|
t.Fatal("skipped lines must stay in known_hosts untouched")
|
||||||
|
}
|
||||||
|
if !strings.Contains(string(data), hostPattern(srv)+" ") {
|
||||||
|
t.Fatalf("new host key was not recorded:\n%s", data)
|
||||||
|
}
|
||||||
|
// Second connection verifies against the recorded key.
|
||||||
|
c, err = connectTo(srv)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("reconnect: %v", err)
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// The maintainer's case: the host is recorded with an unsupported PQ key and
|
||||||
|
// with its ed25519 key only. The server also has an ECDSA key, which
|
||||||
|
// x/crypto would prefer by default and then report as a changed key; the
|
||||||
|
// recorded algorithm must be negotiated instead.
|
||||||
|
func TestKnownHostsPrefersRecordedAlgorithm(t *testing.T) {
|
||||||
|
sshtest.IsolatedHome(t)
|
||||||
|
ed, ec := sshtest.GenKeys(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed, ec}})
|
||||||
|
writeKnownHosts(t,
|
||||||
|
hostPattern(srv)+" "+mldsaKey,
|
||||||
|
knownhosts.Line([]string{hostPattern(srv)}, ed.PublicKey()),
|
||||||
|
)
|
||||||
|
c, err := connectTo(srv)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect: %v", err)
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// A recorded key of a type we cannot check must not be replaced silently
|
||||||
|
// by trust-on-first-use of another key.
|
||||||
|
func TestKnownHostsUnsupportedOnlyRefuses(t *testing.T) {
|
||||||
|
sshtest.IsolatedHome(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
kh := writeKnownHosts(t, hostPattern(srv)+" "+mldsaKey)
|
||||||
|
if c, err := connectTo(srv); err == nil {
|
||||||
|
c.Close()
|
||||||
|
t.Fatal("connected although the only recorded key is of an unsupported type")
|
||||||
|
} else if !strings.Contains(err.Error(), "does not support") {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
data, _ := os.ReadFile(kh)
|
||||||
|
if strings.Count(string(data), "\n") != 1 {
|
||||||
|
t.Fatalf("known_hosts modified:\n%s", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A changed key is still refused when the file also has unsupported lines.
|
||||||
|
func TestKnownHostsMismatchStillRefused(t *testing.T) {
|
||||||
|
sshtest.IsolatedHome(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
other, _ := sshtest.GenKeys(t)
|
||||||
|
writeKnownHosts(t,
|
||||||
|
"otherhost "+mldsaKey,
|
||||||
|
knownhosts.Line([]string{hostPattern(srv)}, other.PublicKey()),
|
||||||
|
)
|
||||||
|
if c, err := connectTo(srv); err == nil {
|
||||||
|
c.Close()
|
||||||
|
t.Fatal("connected with a mismatching recorded key")
|
||||||
|
} else if !strings.Contains(err.Error(), "HAS CHANGED") {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHostKeyAlgorithmsNeverUnsupported(t *testing.T) {
|
||||||
|
sshtest.IsolatedHome(t)
|
||||||
|
ed, _ := sshtest.GenKeys(t)
|
||||||
|
kh := writeKnownHosts(t,
|
||||||
|
"h.example "+mldsaKey,
|
||||||
|
knownhosts.Line([]string{"h.example"}, ed.PublicKey()),
|
||||||
|
)
|
||||||
|
db, err := loadKnownHosts(kh)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
algos := db.hostKeyAlgorithms("h.example:22")
|
||||||
|
if len(algos) == 0 || algos[0] != ssh.KeyAlgoED25519 {
|
||||||
|
t.Fatalf("recorded algorithm not first: %v", algos)
|
||||||
|
}
|
||||||
|
for _, a := range algos {
|
||||||
|
if strings.Contains(a, "mldsa") {
|
||||||
|
t.Fatalf("unsupported algorithm offered: %v", algos)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := db.hostKeyAlgorithms("unknown.example:22"); got != nil {
|
||||||
|
t.Fatalf("unknown host: want defaults, got %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
50
internal/fs/remote/qa_fixes_test.go
Normal file
50
internal/fs/remote/qa_fixes_test.go
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
package remote
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// QA-10: MkdirNew creates missing parents but refuses an existing name
|
||||||
|
// (directory, file or symlink).
|
||||||
|
func TestMkdirNew(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
nested := filepath.Join(dir, "a", "b")
|
||||||
|
if err := c.MkdirNew(nested); err != nil {
|
||||||
|
t.Fatalf("nested mkdir: %v", err)
|
||||||
|
}
|
||||||
|
if fi, err := os.Stat(nested); err != nil || !fi.IsDir() {
|
||||||
|
t.Fatalf("not created: %v", err)
|
||||||
|
}
|
||||||
|
writeFile(t, filepath.Join(dir, "file"), 1, 0o644)
|
||||||
|
if err := os.Symlink("/nonexistent", filepath.Join(dir, "broken")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, n := range []string{"a", "a/b", "file", "broken"} {
|
||||||
|
if err := c.MkdirNew(filepath.Join(dir, n)); !errors.Is(err, os.ErrExist) {
|
||||||
|
t.Errorf("MkdirNew(%s) = %v, want ErrExist", n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// QA-9: a path with "/." or "//" variants of the link name is cleaned too.
|
||||||
|
func TestRemoveRecursiveCleansPath(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
target := filepath.Join(dir, "target")
|
||||||
|
writeFile(t, filepath.Join(target, "keep"), 10, 0o644)
|
||||||
|
link := filepath.Join(dir, "link")
|
||||||
|
if err := os.Symlink(target, link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := c.RemoveRecursive(link + "/."); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(link); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("link not removed")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(target, "keep")); err != nil {
|
||||||
|
t.Fatal("target contents deleted")
|
||||||
|
}
|
||||||
|
}
|
||||||
176
internal/fs/remote/qa_remote_test.go
Normal file
176
internal/fs/remote/qa_remote_test.go
Normal file
|
|
@ -0,0 +1,176 @@
|
||||||
|
package remote
|
||||||
|
|
||||||
|
// QA (v0.2.8): independent checks of N-P0-3 (RemoveRecursive never follows
|
||||||
|
// symlinks) and N-P0-8 (Close is safe under concurrent use, refcount).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestQARemoveRecursiveSymlinkVariants(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
target := filepath.Join(dir, "target")
|
||||||
|
writeFile(t, filepath.Join(target, "keep.txt"), 10, 0o644)
|
||||||
|
file := filepath.Join(dir, "file.txt")
|
||||||
|
writeFile(t, file, 10, 0o644)
|
||||||
|
|
||||||
|
mk := func(name, to string) string {
|
||||||
|
p := filepath.Join(dir, name)
|
||||||
|
if err := os.Symlink(to, p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
cases := map[string]string{
|
||||||
|
"broken": mk("broken", filepath.Join(dir, "nowhere")),
|
||||||
|
"to-file": mk("to-file", file),
|
||||||
|
"relative": mk("relative", "target"),
|
||||||
|
"to-parent": mk("to-parent", ".."),
|
||||||
|
}
|
||||||
|
for name, p := range cases {
|
||||||
|
if err := c.RemoveRecursive(p); err != nil {
|
||||||
|
t.Errorf("%s: RemoveRecursive: %v", name, err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(p); !os.IsNotExist(err) {
|
||||||
|
t.Errorf("%s: link not removed", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(target, "keep.txt")); err != nil {
|
||||||
|
t.Fatalf("target content removed: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(file); err != nil {
|
||||||
|
t.Fatalf("link target file removed: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A directory containing symlinks to a sibling directory and to a file
|
||||||
|
// outside: only the links go, targets survive.
|
||||||
|
func TestQARemoveRecursiveDirWithOutsideLinks(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
outside := filepath.Join(dir, "outside")
|
||||||
|
writeFile(t, filepath.Join(outside, "a.txt"), 10, 0o644)
|
||||||
|
writeFile(t, filepath.Join(outside, "b.txt"), 10, 0o644)
|
||||||
|
victim := filepath.Join(dir, "victim")
|
||||||
|
writeFile(t, filepath.Join(victim, "own.txt"), 10, 0o644)
|
||||||
|
if err := os.MkdirAll(filepath.Join(victim, "deep", "deeper"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(outside, filepath.Join(victim, "deep", "deeper", "dirlink")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(filepath.Join(outside, "b.txt"), filepath.Join(victim, "filelink")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := c.RemoveRecursive(victim); err != nil {
|
||||||
|
t.Fatalf("RemoveRecursive: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(victim); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("victim dir still exists")
|
||||||
|
}
|
||||||
|
for _, f := range []string{"a.txt", "b.txt"} {
|
||||||
|
if _, err := os.Stat(filepath.Join(outside, f)); err != nil {
|
||||||
|
t.Fatalf("outside/%s removed through a link: %v", f, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// "link/" (trailing slash) makes lstat resolve the link on POSIX servers.
|
||||||
|
// The UI never builds such paths today, but RemoveRecursive is a public
|
||||||
|
// helper: with a trailing slash it still empties the target.
|
||||||
|
func TestQARemoveRecursiveSymlinkTrailingSlash(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
target := filepath.Join(dir, "target")
|
||||||
|
writeFile(t, filepath.Join(target, "keep.txt"), 10, 0o644)
|
||||||
|
link := filepath.Join(dir, "link")
|
||||||
|
if err := os.Symlink(target, link); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = c.RemoveRecursive(link + "/")
|
||||||
|
if _, err := os.Stat(filepath.Join(target, "keep.txt")); err != nil {
|
||||||
|
t.Fatalf("target content removed via link/: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close while uploads and downloads are streaming: errors, no panic, no race.
|
||||||
|
func TestQACloseDuringTransfers(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
src := filepath.Join(dir, "big.bin")
|
||||||
|
writeFile(t, src, 4<<20, 0o644)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
panics := make(chan any, 16)
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
wg.Add(2)
|
||||||
|
go func(i int) {
|
||||||
|
defer wg.Done()
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
panics <- r
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
_ = c.CopyFileToRemote(src, filepath.Join(dir, "up", "u"+string(rune('0'+i))))
|
||||||
|
}(i)
|
||||||
|
go func(i int) {
|
||||||
|
defer wg.Done()
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
panics <- r
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
_ = c.CopyFileFromRemote(src, filepath.Join(dir, "down", "d"+string(rune('0'+i))))
|
||||||
|
_ = c.RemoveRecursive(filepath.Join(dir, "up"))
|
||||||
|
_ = c.ExecWithProgress("true", func(string) {})
|
||||||
|
_ = c.MkdirAll(filepath.Join(dir, "m", "n"))
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
var cw sync.WaitGroup
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
cw.Add(1)
|
||||||
|
go func() { defer cw.Done(); c.Close() }()
|
||||||
|
}
|
||||||
|
cw.Wait()
|
||||||
|
wg.Wait()
|
||||||
|
close(panics)
|
||||||
|
for p := range panics {
|
||||||
|
t.Fatalf("panic during Close: %v", p)
|
||||||
|
}
|
||||||
|
if c.IsConnected() {
|
||||||
|
t.Fatal("still connected after Close")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Concurrent Acquire/Release from panels and jobs: the client is closed
|
||||||
|
// exactly when the last user leaves, never earlier.
|
||||||
|
func TestQAAcquireReleaseConcurrent(t *testing.T) {
|
||||||
|
_, c, dir := setup(t)
|
||||||
|
const n = 50
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
c.Acquire()
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
_, _ = c.ReadDir(dir)
|
||||||
|
c.Release()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
if !c.IsConnected() {
|
||||||
|
t.Fatal("client closed while the original user still holds it")
|
||||||
|
}
|
||||||
|
if c.Users() != 1 {
|
||||||
|
t.Fatalf("users=%d, want 1", c.Users())
|
||||||
|
}
|
||||||
|
c.Release()
|
||||||
|
if c.IsConnected() {
|
||||||
|
t.Fatal("last Release must close")
|
||||||
|
}
|
||||||
|
// Extra Release (double release by a buggy caller) must not panic.
|
||||||
|
c.Release()
|
||||||
|
}
|
||||||
282
internal/imgview/actor.go
Normal file
282
internal/imgview/actor.go
Normal file
|
|
@ -0,0 +1,282 @@
|
||||||
|
package imgview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"image"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"vcom/internal/preview"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Backend selects how images are drawn.
|
||||||
|
type Backend uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
None Backend = iota
|
||||||
|
Kitty
|
||||||
|
Ueberzug
|
||||||
|
)
|
||||||
|
|
||||||
|
func (b Backend) String() string { return [...]string{"none", "kitty", "ueberzugpp"}[b] }
|
||||||
|
|
||||||
|
// Rect is a cell rectangle (0-based column/row).
|
||||||
|
type Rect struct{ X, Y, W, H int }
|
||||||
|
|
||||||
|
// Desired is what the UI wants on screen; the actor converges to the latest.
|
||||||
|
type Desired struct {
|
||||||
|
Visible bool
|
||||||
|
Image preview.ImageRef
|
||||||
|
Rect Rect
|
||||||
|
Gen uint64 // content generation, used by the UI's change detection
|
||||||
|
Seq uint64 // effect order; zero keeps the standalone API unordered
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d Desired) same(o Desired) bool {
|
||||||
|
if d.Visible != o.Visible {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !d.Visible {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return d.Rect == o.Rect && d.Image.Local == o.Image.Local && d.Image.Size == o.Image.Size &&
|
||||||
|
d.Image.ModTime.Equal(o.Image.ModTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event reports a problem to the UI (shown as a notification).
|
||||||
|
type Event struct {
|
||||||
|
Err error
|
||||||
|
Disabled bool // the backend was switched off (e.g. stuck helper)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options configure Start.
|
||||||
|
type Options struct {
|
||||||
|
Backend Backend
|
||||||
|
TTY *SyncTTY
|
||||||
|
// CellW, CellH: pixel size of a cell; 0 → asked from the TTY, else 8×16.
|
||||||
|
CellW, CellH int
|
||||||
|
// TmpDir enables kitty's file transmission (local terminal only); "" →
|
||||||
|
// direct transmission.
|
||||||
|
TmpDir string
|
||||||
|
Tmux bool
|
||||||
|
// Ueberzug: the helper command (default "ueberzugpp layer --silent").
|
||||||
|
Ueberzug []string
|
||||||
|
OnEvent func(Event) // called from the actor goroutine
|
||||||
|
}
|
||||||
|
|
||||||
|
// Actor owns the image output.
|
||||||
|
type Actor struct {
|
||||||
|
o Options
|
||||||
|
mu sync.Mutex
|
||||||
|
want Desired
|
||||||
|
dirty bool
|
||||||
|
signal chan struct{}
|
||||||
|
done chan struct{}
|
||||||
|
quit chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
|
||||||
|
backend Backend
|
||||||
|
kitty *kitty
|
||||||
|
uz *ueberzug
|
||||||
|
shown Desired
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start launches the actor goroutine. A backend that cannot start falls
|
||||||
|
// back to None with an Event.
|
||||||
|
func Start(o Options) *Actor {
|
||||||
|
a := &Actor{o: o, signal: make(chan struct{}, 1), done: make(chan struct{}), quit: make(chan struct{}), backend: o.Backend}
|
||||||
|
if a.o.CellW <= 0 || a.o.CellH <= 0 {
|
||||||
|
a.o.CellW, a.o.CellH = 8, 16
|
||||||
|
if o.TTY != nil {
|
||||||
|
if w, h, ok := o.TTY.CellSize(); ok {
|
||||||
|
a.o.CellW, a.o.CellH = w, h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
switch o.Backend {
|
||||||
|
case Kitty:
|
||||||
|
a.kitty = &kitty{tty: o.TTY, tmpDir: o.TmpDir, tmux: o.Tmux}
|
||||||
|
case Ueberzug:
|
||||||
|
cmd := o.Ueberzug
|
||||||
|
if len(cmd) == 0 {
|
||||||
|
cmd = []string{"ueberzugpp", "layer", "--silent"}
|
||||||
|
}
|
||||||
|
uz, err := startUeberzug(cmd[0], cmd[1:]...)
|
||||||
|
if err != nil {
|
||||||
|
a.backend = None
|
||||||
|
a.event(Event{Err: err, Disabled: true})
|
||||||
|
} else {
|
||||||
|
a.uz = uz
|
||||||
|
}
|
||||||
|
}
|
||||||
|
go a.loop()
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backend reports the backend in use (None after a failure).
|
||||||
|
func (a *Actor) Backend() Backend {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
return a.backend
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply records the desired state and returns at once; only the latest
|
||||||
|
// state is drawn. Non-zero Seq values reject commands delivered out of order.
|
||||||
|
func (a *Actor) Apply(d Desired) {
|
||||||
|
a.mu.Lock()
|
||||||
|
if d.Seq != 0 && a.want.Seq > d.Seq {
|
||||||
|
a.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.want, a.dirty = d, true
|
||||||
|
a.mu.Unlock()
|
||||||
|
select {
|
||||||
|
case a.signal <- struct{}{}:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop hides the image, kills ueberzugpp, removes temp files and waits for
|
||||||
|
// the actor goroutine.
|
||||||
|
func (a *Actor) Stop() {
|
||||||
|
a.once.Do(func() { close(a.quit) })
|
||||||
|
<-a.done
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Actor) event(e Event) {
|
||||||
|
if a.o.OnEvent != nil {
|
||||||
|
a.o.OnEvent(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Actor) take() (Desired, bool) {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
d, ok := a.want, a.dirty
|
||||||
|
a.dirty = false
|
||||||
|
return d, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// stale reports whether a newer desired state has arrived.
|
||||||
|
func (a *Actor) stale() bool {
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
return a.dirty
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Actor) loop() {
|
||||||
|
defer close(a.done)
|
||||||
|
defer a.teardown()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-a.quit:
|
||||||
|
return
|
||||||
|
case <-a.signal:
|
||||||
|
}
|
||||||
|
d, ok := a.take()
|
||||||
|
if !ok || d.same(a.shown) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
a.draw(d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Actor) draw(d Desired) {
|
||||||
|
if a.Backend() == None {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
switch {
|
||||||
|
case !d.Visible || d.Image.Local == "":
|
||||||
|
err = a.hide()
|
||||||
|
d.Visible = d.Visible && d.Image.Local != ""
|
||||||
|
case a.kitty != nil:
|
||||||
|
var img *image.RGBA
|
||||||
|
img, err = loadScaled(context.Background(), d.Image.Local, d.Rect.W*a.o.CellW, d.Rect.H*a.o.CellH)
|
||||||
|
if err == nil && a.stale() {
|
||||||
|
return // superseded while decoding: draw the newer state instead
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
err = a.kitty.show(img, d.Rect)
|
||||||
|
}
|
||||||
|
case a.uz != nil:
|
||||||
|
if err = checkSize(d.Image.Local); err == nil {
|
||||||
|
err = a.uz.show(d.Image.Local, d.Rect)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
disabled := errors.Is(err, ErrStuck)
|
||||||
|
if disabled {
|
||||||
|
a.disable()
|
||||||
|
}
|
||||||
|
a.event(Event{Err: err, Disabled: disabled})
|
||||||
|
a.shown = Desired{}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.shown = d
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Actor) hide() error {
|
||||||
|
switch {
|
||||||
|
case a.kitty != nil:
|
||||||
|
return a.kitty.hide()
|
||||||
|
case a.uz != nil:
|
||||||
|
return a.uz.hide()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// disable kills a stuck helper and switches to None.
|
||||||
|
func (a *Actor) disable() {
|
||||||
|
if a.uz != nil {
|
||||||
|
a.uz.stop()
|
||||||
|
a.uz = nil
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
a.backend = None
|
||||||
|
a.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *Actor) teardown() {
|
||||||
|
if a.kitty != nil {
|
||||||
|
a.kitty.stop()
|
||||||
|
}
|
||||||
|
if a.uz != nil {
|
||||||
|
_ = a.uz.hide()
|
||||||
|
a.uz.stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// checkSize refuses huge images for ueberzugpp too (it would decode them).
|
||||||
|
func checkSize(path string) error {
|
||||||
|
_, err := imageConfig(path)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detect picks the backend for preview.image_backend (auto | kitty |
|
||||||
|
// ueberzugpp | none). auto: kitty in kitty, WezTerm or ghostty outside tmux,
|
||||||
|
// else ueberzugpp if installed, else none. An explicit "kitty" works in tmux
|
||||||
|
// (passthrough).
|
||||||
|
func Detect(setting string, getenv func(string) string) Backend {
|
||||||
|
inTmux := getenv("TMUX") != ""
|
||||||
|
switch strings.ToLower(setting) {
|
||||||
|
case "none":
|
||||||
|
return None
|
||||||
|
case "kitty":
|
||||||
|
return Kitty
|
||||||
|
case "ueberzugpp", "ueberzug":
|
||||||
|
return Ueberzug
|
||||||
|
}
|
||||||
|
term, prog := getenv("TERM"), getenv("TERM_PROGRAM")
|
||||||
|
kittyLike := term == "xterm-kitty" || getenv("KITTY_WINDOW_ID") != "" ||
|
||||||
|
prog == "WezTerm" || prog == "ghostty" || term == "xterm-ghostty"
|
||||||
|
if kittyLike && !inTmux {
|
||||||
|
return Kitty
|
||||||
|
}
|
||||||
|
if _, err := exec.LookPath("ueberzugpp"); err == nil {
|
||||||
|
return Ueberzug
|
||||||
|
}
|
||||||
|
return None
|
||||||
|
}
|
||||||
BIN
internal/imgview/imgview.test
Executable file
BIN
internal/imgview/imgview.test
Executable file
Binary file not shown.
351
internal/imgview/imgview_test.go
Normal file
351
internal/imgview/imgview_test.go
Normal file
|
|
@ -0,0 +1,351 @@
|
||||||
|
package imgview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"hash/crc32"
|
||||||
|
"image"
|
||||||
|
"image/jpeg"
|
||||||
|
"image/png"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/preview"
|
||||||
|
)
|
||||||
|
|
||||||
|
// slowWriter writes byte by byte, yielding in between, so unsynchronised
|
||||||
|
// writers would interleave.
|
||||||
|
type slowWriter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
buf bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *slowWriter) Write(p []byte) (int, error) {
|
||||||
|
for _, b := range p {
|
||||||
|
w.mu.Lock()
|
||||||
|
w.buf.WriteByte(b)
|
||||||
|
w.mu.Unlock()
|
||||||
|
runtime.Gosched()
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSyncTTYNoInterleave(t *testing.T) {
|
||||||
|
w := &slowWriter{}
|
||||||
|
tty := NewSyncWriter(w)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := range 8 {
|
||||||
|
wg.Add(2)
|
||||||
|
go func() { // renderer frames
|
||||||
|
defer wg.Done()
|
||||||
|
for j := range 20 {
|
||||||
|
_, _ = tty.Write([]byte(fmt.Sprintf("<frame %d.%d|%s>", i, j, strings.Repeat("x", 50))))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
go func() { // kitty blocks in several parts
|
||||||
|
defer wg.Done()
|
||||||
|
for j := range 20 {
|
||||||
|
_ = tty.WriteBlock([]byte(fmt.Sprintf("<kitty %d.%d|", i, j)), []byte(strings.Repeat("k", 50)), []byte(">"))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
out := w.buf.String()
|
||||||
|
// Every '<' must be followed by a whole unit up to its '>' with no '<' inside.
|
||||||
|
n := 0
|
||||||
|
for len(out) > 0 {
|
||||||
|
if out[0] != '<' {
|
||||||
|
t.Fatalf("garbage at %q", out[:min(40, len(out))])
|
||||||
|
}
|
||||||
|
end := strings.IndexByte(out, '>')
|
||||||
|
if end < 0 || strings.Contains(out[1:end], "<") {
|
||||||
|
t.Fatalf("interleaved output near %q", out[:min(80, len(out))])
|
||||||
|
}
|
||||||
|
out = out[end+1:]
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
if n != 8*20*2 {
|
||||||
|
t.Fatalf("%d units", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writePNG(t testing.TB, dir, name string, w, h int) string {
|
||||||
|
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||||
|
for i := range img.Pix {
|
||||||
|
img.Pix[i] = byte(i)
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, name)
|
||||||
|
f, err := os.Create(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := png.Encode(f, img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
f.Close()
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActorLatestWins(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
var decodes atomic.Int32
|
||||||
|
decodeHook = func() { decodes.Add(1); time.Sleep(20 * time.Millisecond) }
|
||||||
|
t.Cleanup(func() { decodeHook = nil })
|
||||||
|
var out bytes.Buffer
|
||||||
|
var mu sync.Mutex
|
||||||
|
tty := NewSyncWriter(writerFunc(func(p []byte) (int, error) { mu.Lock(); defer mu.Unlock(); return out.Write(p) }))
|
||||||
|
a := Start(Options{Backend: Kitty, TTY: tty, CellW: 8, CellH: 16})
|
||||||
|
defer a.Stop()
|
||||||
|
|
||||||
|
var paths []string
|
||||||
|
for i := range 5 {
|
||||||
|
paths = append(paths, writePNG(t, dir, fmt.Sprintf("%d.png", i), 64+i, 32))
|
||||||
|
}
|
||||||
|
t0 := time.Now()
|
||||||
|
for i := range 100 {
|
||||||
|
a.Apply(Desired{Visible: true, Rect: Rect{X: 1, Y: 1, W: 10, H: 5}, Gen: uint64(i),
|
||||||
|
Image: preview.ImageRef{Local: paths[i%5], Size: int64(i)}})
|
||||||
|
}
|
||||||
|
if el := time.Since(t0); el > 50*time.Millisecond {
|
||||||
|
t.Fatalf("100 Apply took %v: Apply must not block", el)
|
||||||
|
}
|
||||||
|
deadline := time.Now().Add(2 * time.Second)
|
||||||
|
for {
|
||||||
|
mu.Lock()
|
||||||
|
got := strings.Count(out.String(), "a=T")
|
||||||
|
mu.Unlock()
|
||||||
|
if got > 0 && !a.stale() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("nothing drawn")
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
time.Sleep(60 * time.Millisecond)
|
||||||
|
if n := decodes.Load(); n > 2 {
|
||||||
|
t.Fatalf("%d decodes for 100 Apply calls, want ≤ 2", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type writerFunc func([]byte) (int, error)
|
||||||
|
|
||||||
|
func (f writerFunc) Write(p []byte) (int, error) { return f(p) }
|
||||||
|
|
||||||
|
// hugePNG writes a valid PNG whose IHDR claims w×h (the pixel data is tiny
|
||||||
|
// and wrong: a full decode would fail or take ages; DecodeConfig must stop
|
||||||
|
// first).
|
||||||
|
func hugePNG(t *testing.T, w, h uint32) string {
|
||||||
|
var b bytes.Buffer
|
||||||
|
_ = png.Encode(&b, image.NewGray(image.Rect(0, 0, 1, 1)))
|
||||||
|
data := b.Bytes()
|
||||||
|
ihdr := data[8+8 : 8+8+13] // after signature, length and type
|
||||||
|
binary.BigEndian.PutUint32(ihdr[0:4], w)
|
||||||
|
binary.BigEndian.PutUint32(ihdr[4:8], h)
|
||||||
|
crc := crc32.ChecksumIEEE(data[8+4 : 8+8+13])
|
||||||
|
binary.BigEndian.PutUint32(data[8+8+13:], crc)
|
||||||
|
p := filepath.Join(t.TempDir(), "huge.png")
|
||||||
|
_ = os.WriteFile(p, data, 0o644)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRejectHugeImage(t *testing.T) {
|
||||||
|
p := hugePNG(t, 10000, 10000) // 100 Mpx
|
||||||
|
var decodes atomic.Int32
|
||||||
|
decodeHook = func() { decodes.Add(1) }
|
||||||
|
t.Cleanup(func() { decodeHook = nil })
|
||||||
|
t0 := time.Now()
|
||||||
|
_, err := loadScaled(t.Context(), p, 800, 600)
|
||||||
|
if !errors.Is(err, ErrTooLarge) || decodes.Load() != 0 {
|
||||||
|
t.Fatalf("err=%v decodes=%d", err, decodes.Load())
|
||||||
|
}
|
||||||
|
if el := time.Since(t0); el > 50*time.Millisecond {
|
||||||
|
t.Fatalf("took %v", el)
|
||||||
|
}
|
||||||
|
// Through the actor the error becomes an event, nothing is drawn.
|
||||||
|
events := make(chan Event, 4)
|
||||||
|
var out bytes.Buffer
|
||||||
|
a := Start(Options{Backend: Kitty, TTY: NewSyncWriter(&out), CellW: 8, CellH: 16, OnEvent: func(e Event) { events <- e }})
|
||||||
|
a.Apply(Desired{Visible: true, Rect: Rect{W: 10, H: 5}, Image: preview.ImageRef{Local: p}})
|
||||||
|
select {
|
||||||
|
case e := <-events:
|
||||||
|
if !errors.Is(e.Err, ErrTooLarge) {
|
||||||
|
t.Fatalf("event %+v", e)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("no event")
|
||||||
|
}
|
||||||
|
a.Stop()
|
||||||
|
if strings.Contains(out.String(), "a=T") {
|
||||||
|
t.Fatal("drawn anyway")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUeberzugStuckIsKilled(t *testing.T) {
|
||||||
|
stuck := filepath.Join(t.TempDir(), "ueberzug")
|
||||||
|
pidFile := stuck + ".pid"
|
||||||
|
// Never reads stdin; records its pid.
|
||||||
|
_ = os.WriteFile(stuck, []byte("#!/bin/sh\necho $$ > "+pidFile+"\nexec sleep 60\n"), 0o755)
|
||||||
|
events := make(chan Event, 8)
|
||||||
|
a := Start(Options{Backend: Ueberzug, Ueberzug: []string{stuck}, OnEvent: func(e Event) { events <- e }})
|
||||||
|
defer a.Stop()
|
||||||
|
if a.Backend() != Ueberzug {
|
||||||
|
t.Fatal("did not start")
|
||||||
|
}
|
||||||
|
img := writePNG(t, t.TempDir(), "a.png", 4, 4)
|
||||||
|
// Long paths fill the 64 KiB pipe after a few commands.
|
||||||
|
longDir := filepath.Join(t.TempDir(), strings.Repeat("d", 200), strings.Repeat("e", 200))
|
||||||
|
_ = os.MkdirAll(longDir, 0o755)
|
||||||
|
long := filepath.Join(longDir, "a.png")
|
||||||
|
_ = os.Link(img, long)
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
var disabledAt time.Time
|
||||||
|
for i := 0; disabledAt.IsZero() && time.Since(start) < 3*time.Second; i++ {
|
||||||
|
t0 := time.Now()
|
||||||
|
a.Apply(Desired{Visible: true, Rect: Rect{X: i % 7, W: 10 + i%5, H: 5}, Image: preview.ImageRef{Local: long + strings.Repeat("/.", 0)}})
|
||||||
|
if el := time.Since(t0); el > 5*time.Millisecond {
|
||||||
|
t.Fatalf("Apply blocked for %v", el)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case e := <-events:
|
||||||
|
if e.Disabled && errors.Is(e.Err, ErrStuck) {
|
||||||
|
disabledAt = time.Now()
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Millisecond):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if disabledAt.IsZero() {
|
||||||
|
t.Fatal("stuck helper never detected")
|
||||||
|
}
|
||||||
|
if a.Backend() != None {
|
||||||
|
t.Fatal("backend not switched off")
|
||||||
|
}
|
||||||
|
// The helper is gone.
|
||||||
|
pid, _ := os.ReadFile(pidFile)
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
if _, err := os.Stat("/proc/" + strings.TrimSpace(string(pid))); err == nil {
|
||||||
|
t.Fatalf("helper %s still running", pid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUeberzugCommands(t *testing.T) {
|
||||||
|
log := filepath.Join(t.TempDir(), "log")
|
||||||
|
helper := filepath.Join(t.TempDir(), "uz")
|
||||||
|
_ = os.WriteFile(helper, []byte("#!/bin/sh\ncat > "+log+"\n"), 0o755)
|
||||||
|
a := Start(Options{Backend: Ueberzug, Ueberzug: []string{helper}})
|
||||||
|
img := writePNG(t, t.TempDir(), "a.png", 4, 4)
|
||||||
|
a.Apply(Desired{Visible: true, Rect: Rect{X: 3, Y: 2, W: 10, H: 5}, Image: preview.ImageRef{Local: img}})
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
a.Apply(Desired{Visible: false})
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
a.Stop()
|
||||||
|
b, _ := os.ReadFile(log)
|
||||||
|
s := string(b)
|
||||||
|
if !strings.Contains(s, `"action":"add"`) || !strings.Contains(s, `"x":3`) || !strings.Contains(s, `"action":"remove"`) {
|
||||||
|
t.Fatalf("commands:\n%s", s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKittyBlock(t *testing.T) {
|
||||||
|
var out bytes.Buffer
|
||||||
|
k := &kitty{tty: NewSyncWriter(&out)}
|
||||||
|
img := scaleToFit(image.NewRGBA(image.Rect(0, 0, 100, 100)), 40, 20)
|
||||||
|
if img.Rect.Dx() != 20 || img.Rect.Dy() != 20 {
|
||||||
|
t.Fatalf("scaled %v", img.Rect)
|
||||||
|
}
|
||||||
|
if err := k.show(img, Rect{X: 4, Y: 2, W: 5, H: 3}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s := out.String()
|
||||||
|
if !strings.Contains(s, "\x1b7\x1b[3;5H\x1b_Ga=T,f=32,s=20,v=20,") || !strings.HasSuffix(s, "\x1b8") || !strings.Contains(s, "C=1") {
|
||||||
|
t.Fatalf("block %q", s[:min(120, len(s))])
|
||||||
|
}
|
||||||
|
// Chunked: every APC but the last says m=1.
|
||||||
|
if strings.Count(s, "m=1") != strings.Count(s, "\x1b_G")-2 { // minus the delete and the last chunk
|
||||||
|
t.Fatalf("chunks: %d m=1, %d APC", strings.Count(s, "m=1"), strings.Count(s, "\x1b_G"))
|
||||||
|
}
|
||||||
|
// File transmission and tmux passthrough.
|
||||||
|
out.Reset()
|
||||||
|
tmp := t.TempDir()
|
||||||
|
k = &kitty{tty: NewSyncWriter(&out), tmpDir: tmp, tmux: true}
|
||||||
|
if err := k.show(img, Rect{W: 5, H: 3}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(out.String(), "t=t") || !strings.HasPrefix(out.String(), "\x1bPtmux;\x1b\x1b_G") {
|
||||||
|
t.Fatalf("tmux/file %q", out.String()[:min(80, out.Len())])
|
||||||
|
}
|
||||||
|
k.stop()
|
||||||
|
if files, _ := filepath.Glob(filepath.Join(tmp, "*")); len(files) != 0 {
|
||||||
|
t.Fatalf("temp files after stop: %v", files)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDetect(t *testing.T) {
|
||||||
|
env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
|
||||||
|
if Detect("auto", env(map[string]string{"TERM": "xterm-kitty"})) != Kitty {
|
||||||
|
t.Error("kitty")
|
||||||
|
}
|
||||||
|
if Detect("auto", env(map[string]string{"TERM_PROGRAM": "WezTerm"})) != Kitty {
|
||||||
|
t.Error("wezterm")
|
||||||
|
}
|
||||||
|
if Detect("auto", env(map[string]string{"KITTY_WINDOW_ID": "1", "TMUX": "x"})) == Kitty {
|
||||||
|
t.Error("kitty auto in tmux")
|
||||||
|
}
|
||||||
|
if Detect("kitty", env(map[string]string{"TMUX": "x"})) != Kitty || Detect("none", env(nil)) != None {
|
||||||
|
t.Error("explicit")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkKittyPayload6000x4000(b *testing.B) {
|
||||||
|
dir := b.TempDir()
|
||||||
|
img := image.NewYCbCr(image.Rect(0, 0, 6000, 4000), image.YCbCrSubsampleRatio420)
|
||||||
|
for i := range img.Y {
|
||||||
|
img.Y[i] = byte(i * 7)
|
||||||
|
}
|
||||||
|
p := filepath.Join(dir, "photo.jpg")
|
||||||
|
f, _ := os.Create(p)
|
||||||
|
_ = jpeg.Encode(f, img, &jpeg.Options{Quality: 85})
|
||||||
|
f.Close()
|
||||||
|
k := &kitty{tty: NewSyncWriter(writerFunc(func(p []byte) (int, error) { return len(p), nil }))}
|
||||||
|
b.ResetTimer()
|
||||||
|
for range b.N {
|
||||||
|
scaled, err := loadScaled(b.Context(), p, 100*8, 40*16)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := k.kittyBlock(scaled, Rect{W: 100, H: 40}); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scale + payload only (the stdlib JPEG decoder dominates the benchmark
|
||||||
|
// above: ~180 of ~200 ms for 24 Mpx).
|
||||||
|
func BenchmarkKittyPayloadDecoded6000x4000(b *testing.B) {
|
||||||
|
img := image.NewYCbCr(image.Rect(0, 0, 6000, 4000), image.YCbCrSubsampleRatio420)
|
||||||
|
k := &kitty{tty: NewSyncWriter(writerFunc(func(p []byte) (int, error) { return len(p), nil }))}
|
||||||
|
b.ResetTimer()
|
||||||
|
for range b.N {
|
||||||
|
if _, err := k.kittyBlock(scaleToFit(img, 800, 640), Rect{W: 100, H: 40}); err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestActorRejectsOutOfOrderDesired(t *testing.T) {
|
||||||
|
a := &Actor{signal: make(chan struct{}, 1)}
|
||||||
|
a.Apply(Desired{Visible: true, Seq: 2})
|
||||||
|
a.Apply(Desired{Visible: false, Seq: 1})
|
||||||
|
if !a.want.Visible || a.want.Seq != 2 {
|
||||||
|
t.Fatalf("older desired state replaced the newer one: %#v", a.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
105
internal/imgview/kitty.go
Normal file
105
internal/imgview/kitty.go
Normal file
|
|
@ -0,0 +1,105 @@
|
||||||
|
package imgview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// kittyImageID identifies vcom's single placement.
|
||||||
|
const kittyImageID = 31337
|
||||||
|
|
||||||
|
// kitty draws with the kitty graphics protocol. Each draw is one block
|
||||||
|
// "ESC 7, CUP, APC…, ESC 8" under the SyncTTY mutex: the cursor does not
|
||||||
|
// move and the renderer is not disturbed. With a local terminal the pixels
|
||||||
|
// go through a temp file (t=t), avoiding base64 of megabytes.
|
||||||
|
type kitty struct {
|
||||||
|
tty *SyncTTY
|
||||||
|
tmpDir string // "" → direct transmission
|
||||||
|
tmux bool
|
||||||
|
shown bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// kittyBlock builds the escape sequences for img at rect.
|
||||||
|
func (k *kitty) kittyBlock(img *image.RGBA, r Rect) ([]byte, error) {
|
||||||
|
w, h := img.Rect.Dx(), img.Rect.Dy()
|
||||||
|
ctrl := fmt.Sprintf("a=T,f=32,s=%d,v=%d,i=%d,c=%d,r=%d,C=1,q=2", w, h, kittyImageID, r.W, r.H)
|
||||||
|
var b strings.Builder
|
||||||
|
b.WriteString("\x1b7")
|
||||||
|
fmt.Fprintf(&b, "\x1b[%d;%dH", r.Y+1, r.X+1)
|
||||||
|
if k.tmpDir != "" {
|
||||||
|
f, err := os.CreateTemp(k.tmpDir, "tty-graphics-protocol-*.rgba")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, err = f.Write(img.Pix)
|
||||||
|
if cerr := f.Close(); err == nil {
|
||||||
|
err = cerr
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
os.Remove(f.Name())
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// t=t: the terminal reads and deletes the file itself.
|
||||||
|
b.WriteString(k.apc(ctrl+",t=t", base64.StdEncoding.EncodeToString([]byte(f.Name()))))
|
||||||
|
} else {
|
||||||
|
payload := base64.StdEncoding.EncodeToString(img.Pix)
|
||||||
|
const chunk = 4096
|
||||||
|
for i := 0; i < len(payload); i += chunk {
|
||||||
|
end := min(i+chunk, len(payload))
|
||||||
|
more := 0
|
||||||
|
if end < len(payload) {
|
||||||
|
more = 1
|
||||||
|
}
|
||||||
|
c := fmt.Sprintf("m=%d", more)
|
||||||
|
if i == 0 {
|
||||||
|
c = ctrl + "," + c
|
||||||
|
}
|
||||||
|
b.WriteString(k.apc(c, payload[i:end]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b.WriteString("\x1b8")
|
||||||
|
return []byte(b.String()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// apc wraps one graphics command (in tmux passthrough if needed).
|
||||||
|
func (k *kitty) apc(ctrl, payload string) string {
|
||||||
|
s := "\x1b_G" + ctrl + ";" + payload + "\x1b\\"
|
||||||
|
if k.tmux {
|
||||||
|
s = "\x1bPtmux;" + strings.ReplaceAll(s, "\x1b", "\x1b\x1b") + "\x1b\\"
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k *kitty) show(img *image.RGBA, r Rect) error {
|
||||||
|
block, err := k.kittyBlock(img, r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := k.tty.WriteBlock([]byte(k.apc(fmt.Sprintf("a=d,d=I,i=%d,q=2", kittyImageID), "")), block); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
k.shown = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k *kitty) hide() error {
|
||||||
|
if !k.shown {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
k.shown = false
|
||||||
|
return k.tty.WriteBlock([]byte(k.apc(fmt.Sprintf("a=d,d=I,i=%d,q=2", kittyImageID), "")))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k *kitty) stop() {
|
||||||
|
_ = k.hide()
|
||||||
|
if k.tmpDir != "" {
|
||||||
|
files, _ := filepath.Glob(filepath.Join(k.tmpDir, "tty-graphics-protocol-*"))
|
||||||
|
for _, f := range files {
|
||||||
|
os.Remove(f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
92
internal/imgview/scale.go
Normal file
92
internal/imgview/scale.go
Normal file
|
|
@ -0,0 +1,92 @@
|
||||||
|
package imgview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
_ "image/gif" // decoders
|
||||||
|
_ "image/jpeg"
|
||||||
|
_ "image/png"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/image/draw"
|
||||||
|
_ "golang.org/x/image/webp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxPixels: images above this (by DecodeConfig) are refused without a
|
||||||
|
// full decode.
|
||||||
|
const MaxPixels = 50_000_000
|
||||||
|
|
||||||
|
// ErrTooLarge: the image has more than MaxPixels.
|
||||||
|
var ErrTooLarge = errors.New("image too large to display")
|
||||||
|
|
||||||
|
// decodeHook counts full decodes (tests).
|
||||||
|
var decodeHook func()
|
||||||
|
|
||||||
|
// loadScaled decodes the file and scales it to fit maxW×maxH pixels
|
||||||
|
// (keeping the aspect ratio, never enlarging).
|
||||||
|
func loadScaled(ctx context.Context, path string, maxW, maxH int) (*image.RGBA, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
if _, err := configOf(f); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if _, err := f.Seek(0, 0); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if decodeHook != nil {
|
||||||
|
decodeHook()
|
||||||
|
}
|
||||||
|
src, _, err := image.Decode(f)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return scaleToFit(src, maxW, maxH), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// scaleToFit returns src scaled into maxW×maxH with ApproxBiLinear.
|
||||||
|
func scaleToFit(src image.Image, maxW, maxH int) *image.RGBA {
|
||||||
|
b := src.Bounds()
|
||||||
|
w, h := b.Dx(), b.Dy()
|
||||||
|
if maxW > 0 && maxH > 0 && (w > maxW || h > maxH) {
|
||||||
|
if w*maxH > h*maxW {
|
||||||
|
w, h = maxW, max(1, h*maxW/w)
|
||||||
|
} else {
|
||||||
|
w, h = max(1, w*maxH/h), maxH
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||||
|
draw.ApproxBiLinear.Scale(dst, dst.Bounds(), src, b, draw.Src, nil)
|
||||||
|
return dst
|
||||||
|
}
|
||||||
|
|
||||||
|
func configOf(f *os.File) (image.Config, error) {
|
||||||
|
cfg, _, err := image.DecodeConfig(f)
|
||||||
|
if err != nil {
|
||||||
|
return cfg, err
|
||||||
|
}
|
||||||
|
if int64(cfg.Width)*int64(cfg.Height) > MaxPixels {
|
||||||
|
return cfg, fmt.Errorf("%w: %dx%d", ErrTooLarge, cfg.Width, cfg.Height)
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageConfig reads only the header and enforces MaxPixels.
|
||||||
|
func imageConfig(path string) (image.Config, error) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return image.Config{}, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
return configOf(f)
|
||||||
|
}
|
||||||
82
internal/imgview/synctty.go
Normal file
82
internal/imgview/synctty.go
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
// Package imgview draws preview images next to the Bubble Tea UI (design
|
||||||
|
// §5.5) without side effects in View: an actor goroutine takes the latest
|
||||||
|
// desired state, decodes and scales off the UI goroutine and writes kitty
|
||||||
|
// graphics (or drives ueberzugpp) through a SyncTTY shared with the
|
||||||
|
// renderer, so escape sequences never interleave with a frame.
|
||||||
|
package imgview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SyncTTY serialises writes to the terminal. Bubble Tea writes each frame
|
||||||
|
// with one Write (tea.WithOutput(tty)); image blocks go through WriteBlock
|
||||||
|
// under the same mutex. It implements term.File (Read, Write, Close, Fd).
|
||||||
|
type SyncTTY struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
w io.Writer
|
||||||
|
f *os.File
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSyncTTY wraps the terminal file.
|
||||||
|
func NewSyncTTY(f *os.File) *SyncTTY { return &SyncTTY{w: f, f: f} }
|
||||||
|
|
||||||
|
// NewSyncWriter wraps any writer (tests, non-terminal output).
|
||||||
|
func NewSyncWriter(w io.Writer) *SyncTTY { return &SyncTTY{w: w} }
|
||||||
|
|
||||||
|
func (t *SyncTTY) Write(p []byte) (int, error) {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
return t.w.Write(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteBlock writes several pieces atomically with respect to frames.
|
||||||
|
func (t *SyncTTY) WriteBlock(parts ...[]byte) error {
|
||||||
|
t.mu.Lock()
|
||||||
|
defer t.mu.Unlock()
|
||||||
|
for _, p := range parts {
|
||||||
|
if _, err := t.w.Write(p); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SyncTTY) Read(p []byte) (int, error) {
|
||||||
|
if t.f == nil {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
return t.f.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *SyncTTY) Close() error {
|
||||||
|
if t.f == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return t.f.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fd returns the terminal descriptor (^0 when not a file).
|
||||||
|
func (t *SyncTTY) Fd() uintptr {
|
||||||
|
if t.f == nil {
|
||||||
|
return ^uintptr(0)
|
||||||
|
}
|
||||||
|
return t.f.Fd()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CellSize returns the pixel size of a character cell, if the terminal
|
||||||
|
// reports it (TIOCGWINSZ ws_xpixel/ws_ypixel).
|
||||||
|
func (t *SyncTTY) CellSize() (w, h int, ok bool) {
|
||||||
|
if t.f == nil {
|
||||||
|
return 0, 0, false
|
||||||
|
}
|
||||||
|
ws, err := unix.IoctlGetWinsize(int(t.f.Fd()), unix.TIOCGWINSZ)
|
||||||
|
if err != nil || ws.Col == 0 || ws.Row == 0 || ws.Xpixel == 0 || ws.Ypixel == 0 {
|
||||||
|
return 0, 0, false
|
||||||
|
}
|
||||||
|
return int(ws.Xpixel) / int(ws.Col), int(ws.Ypixel) / int(ws.Row), true
|
||||||
|
}
|
||||||
83
internal/imgview/ueberzug.go
Normal file
83
internal/imgview/ueberzug.go
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
package imgview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// writeTimeout: a ueberzugpp that does not read its stdin for this long is
|
||||||
|
// considered stuck and killed (the UI never waits on it).
|
||||||
|
const writeTimeout = 200 * time.Millisecond
|
||||||
|
|
||||||
|
// ErrStuck: the image helper stopped reading commands.
|
||||||
|
var ErrStuck = errors.New("image helper is not responding")
|
||||||
|
|
||||||
|
// ueberzug drives `ueberzugpp layer` through JSON lines on its stdin. Writes
|
||||||
|
// happen on the actor goroutine with a deadline on the pipe.
|
||||||
|
type ueberzug struct {
|
||||||
|
cmd *exec.Cmd
|
||||||
|
w *os.File
|
||||||
|
}
|
||||||
|
|
||||||
|
func startUeberzug(prog string, args ...string) (*ueberzug, error) {
|
||||||
|
if len(args) == 0 {
|
||||||
|
args = []string{"layer", "--silent"}
|
||||||
|
}
|
||||||
|
r, w, err := os.Pipe()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cmd := exec.Command(prog, args...)
|
||||||
|
cmd.Stdin = r
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
r.Close()
|
||||||
|
w.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
r.Close()
|
||||||
|
return &ueberzug{cmd: cmd, w: w}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *ueberzug) send(cmd map[string]any) error {
|
||||||
|
b, err := json.Marshal(cmd)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b = append(b, '\n')
|
||||||
|
if err := u.w.SetWriteDeadline(time.Now().Add(writeTimeout)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := u.w.Write(b); err != nil {
|
||||||
|
if errors.Is(err, os.ErrDeadlineExceeded) {
|
||||||
|
return fmt.Errorf("%w (%v without reading)", ErrStuck, writeTimeout)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *ueberzug) show(path string, r Rect) error {
|
||||||
|
return u.send(map[string]any{
|
||||||
|
"action": "add", "identifier": "vcom", "path": path,
|
||||||
|
"x": r.X, "y": r.Y, "max_width": r.W, "max_height": r.H, "scaler": "fit_contain",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *ueberzug) hide() error {
|
||||||
|
return u.send(map[string]any{"action": "remove", "identifier": "vcom"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// stop kills the helper and its children and reaps it.
|
||||||
|
func (u *ueberzug) stop() {
|
||||||
|
_ = u.w.Close()
|
||||||
|
if u.cmd.Process != nil {
|
||||||
|
_ = syscall.Kill(-u.cmd.Process.Pid, syscall.SIGKILL)
|
||||||
|
_ = u.cmd.Wait()
|
||||||
|
}
|
||||||
|
}
|
||||||
105
internal/jobs/events.go
Normal file
105
internal/jobs/events.go
Normal file
|
|
@ -0,0 +1,105 @@
|
||||||
|
package jobs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ID identifies a job within a Manager.
|
||||||
|
type ID uint64
|
||||||
|
|
||||||
|
// Kind names what a job does ("copy", "move", "delete", "trash", "archive",
|
||||||
|
// "unpack", "mount", "dirsize", "connect", "edit-upload", ...).
|
||||||
|
type Kind string
|
||||||
|
|
||||||
|
// State of a job.
|
||||||
|
type State uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Queued State = iota
|
||||||
|
Running // fn is executing
|
||||||
|
Waiting // blocked in Handle.Ask until the user answers
|
||||||
|
Done // fn returned nil
|
||||||
|
Failed // fn returned an error or panicked
|
||||||
|
Cancelled // cancelled (before start, or fn returned context.Canceled)
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s State) String() string {
|
||||||
|
switch s {
|
||||||
|
case Queued:
|
||||||
|
return "queued"
|
||||||
|
case Running:
|
||||||
|
return "running"
|
||||||
|
case Waiting:
|
||||||
|
return "waiting"
|
||||||
|
case Done:
|
||||||
|
return "done"
|
||||||
|
case Failed:
|
||||||
|
return "failed"
|
||||||
|
case Cancelled:
|
||||||
|
return "cancelled"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("State(%d)", uint8(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finished reports whether s is terminal.
|
||||||
|
func (s State) Finished() bool { return s >= Done }
|
||||||
|
|
||||||
|
// Progress is the latest progress a job reported.
|
||||||
|
type Progress struct {
|
||||||
|
Phase string
|
||||||
|
FilesDone int
|
||||||
|
FilesTotal int
|
||||||
|
BytesDone int64
|
||||||
|
BytesTotal int64
|
||||||
|
Current string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot is a copy of a job's state.
|
||||||
|
type Snapshot struct {
|
||||||
|
ID ID
|
||||||
|
Kind Kind
|
||||||
|
Title string
|
||||||
|
State State
|
||||||
|
Progress Progress
|
||||||
|
Started time.Time // when Start was called
|
||||||
|
Background bool
|
||||||
|
Result any // what fn returned (e.g. a transfer report), for Done/Failed/Cancelled
|
||||||
|
Err error // why it Failed or was Cancelled
|
||||||
|
}
|
||||||
|
|
||||||
|
// Question is something a job asks the user (conflict, item error, host
|
||||||
|
// key, password, ...). Payload is defined by the job's domain; the UI picks a
|
||||||
|
// dialog by its type and answers with Manager.Answer(QID, answer).
|
||||||
|
type Question struct {
|
||||||
|
Job ID
|
||||||
|
QID uint64
|
||||||
|
Payload any
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event is delivered to the notify callback given to New.
|
||||||
|
type Event interface{ isEvent() }
|
||||||
|
|
||||||
|
// Started: a job was accepted (State Queued or Running).
|
||||||
|
type Started struct{ Snapshot Snapshot }
|
||||||
|
|
||||||
|
// ProgressTick carries the jobs whose progress or state changed since the
|
||||||
|
// previous tick. At most 10 per second.
|
||||||
|
type ProgressTick struct{ Snapshots []Snapshot }
|
||||||
|
|
||||||
|
// Asked: a job is waiting for an answer.
|
||||||
|
type Asked struct{ Question Question }
|
||||||
|
|
||||||
|
// Unasked: a question was withdrawn without an answer (the job or the Ask
|
||||||
|
// context was cancelled); close its dialog.
|
||||||
|
type Unasked struct{ Question Question }
|
||||||
|
|
||||||
|
// Finished: a job reached a terminal state. It is the last event for that
|
||||||
|
// job.
|
||||||
|
type Finished struct{ Snapshot Snapshot }
|
||||||
|
|
||||||
|
func (Started) isEvent() {}
|
||||||
|
func (ProgressTick) isEvent() {}
|
||||||
|
func (Asked) isEvent() {}
|
||||||
|
func (Unasked) isEvent() {}
|
||||||
|
func (Finished) isEvent() {}
|
||||||
82
internal/jobs/handle.go
Normal file
82
internal/jobs/handle.go
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
package jobs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Handle is a job's view of the Manager. It is passed to the job function
|
||||||
|
// and valid only while it runs.
|
||||||
|
type Handle struct {
|
||||||
|
m *Manager
|
||||||
|
j *job
|
||||||
|
}
|
||||||
|
|
||||||
|
// ID of the job.
|
||||||
|
func (h *Handle) ID() ID { return h.j.id }
|
||||||
|
|
||||||
|
// SetProgress records the latest progress. It is O(1), never blocks on the
|
||||||
|
// UI and may be called as often as wanted: the Manager publishes at most 10
|
||||||
|
// ticks per second, each with the last value.
|
||||||
|
func (h *Handle) SetProgress(p Progress) {
|
||||||
|
h.m.mu.Lock()
|
||||||
|
h.j.progress = p
|
||||||
|
h.j.dirty = true
|
||||||
|
h.m.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ask publishes a question and blocks this job's goroutine (State Waiting)
|
||||||
|
// until Manager.Answer, the job's cancellation or ctx. Other jobs and the
|
||||||
|
// UI keep running.
|
||||||
|
func (h *Handle) Ask(ctx context.Context, payload any) (any, error) {
|
||||||
|
m, j := h.m, h.j
|
||||||
|
ans := make(chan any, 1)
|
||||||
|
m.mu.Lock()
|
||||||
|
m.nextQID++
|
||||||
|
q := Question{Job: j.id, QID: m.nextQID, Payload: payload}
|
||||||
|
m.questions[q.QID] = &pending{q: q, ch: ans, j: j}
|
||||||
|
j.asking++
|
||||||
|
j.state = Waiting
|
||||||
|
j.dirty = true
|
||||||
|
m.emitLocked(Asked{Question: q})
|
||||||
|
m.mu.Unlock()
|
||||||
|
|
||||||
|
var (
|
||||||
|
a any
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
select {
|
||||||
|
case a = <-ans:
|
||||||
|
case <-ctx.Done():
|
||||||
|
err = ctx.Err()
|
||||||
|
case <-j.ctx.Done():
|
||||||
|
err = j.ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
m.mu.Lock()
|
||||||
|
if err != nil {
|
||||||
|
if _, still := m.questions[q.QID]; still {
|
||||||
|
delete(m.questions, q.QID)
|
||||||
|
m.emitLocked(Unasked{Question: q})
|
||||||
|
} else {
|
||||||
|
// Answered concurrently with the cancellation: the answer wins
|
||||||
|
// only if the job itself is not cancelled.
|
||||||
|
select {
|
||||||
|
case a = <-ans:
|
||||||
|
if j.ctx.Err() == nil {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
j.asking--
|
||||||
|
if j.asking == 0 && j.state == Waiting {
|
||||||
|
j.state = Running
|
||||||
|
j.dirty = true
|
||||||
|
}
|
||||||
|
m.mu.Unlock()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return a, nil
|
||||||
|
}
|
||||||
436
internal/jobs/manager.go
Normal file
436
internal/jobs/manager.go
Normal file
|
|
@ -0,0 +1,436 @@
|
||||||
|
// Package jobs runs background operations (copy, delete, archive, connect,
|
||||||
|
// ...) independently of the UI framework (design §6, D4).
|
||||||
|
//
|
||||||
|
// A Manager runs at most maxParallel jobs at once and queues the rest. Jobs
|
||||||
|
// report progress with Handle.SetProgress ("latest value wins"); the Manager
|
||||||
|
// publishes changes at most 10 times per second, so a job copying thousands
|
||||||
|
// of small files never waits for the UI. Questions to the user
|
||||||
|
// (Handle.Ask) block only the asking job. Every goroutine recovers panics:
|
||||||
|
// a panicking job ends as Failed instead of taking the process down.
|
||||||
|
//
|
||||||
|
// Events reach the notify callback from a single dispatcher goroutine in
|
||||||
|
// order. notify may block (Bubble Tea's Send does until the program reads
|
||||||
|
// it); that delays later events but never a job.
|
||||||
|
package jobs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"runtime/debug"
|
||||||
|
"sort"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultMaxParallel is used when New gets maxParallel <= 0.
|
||||||
|
const DefaultMaxParallel = 2
|
||||||
|
|
||||||
|
// tickInterval bounds ProgressTick to 10 Hz.
|
||||||
|
var tickInterval = 100 * time.Millisecond
|
||||||
|
|
||||||
|
// keepFinished is how many finished jobs Snapshot keeps for the job list.
|
||||||
|
const keepFinished = 100
|
||||||
|
|
||||||
|
// ErrShutdown is the Err of a job started after Shutdown.
|
||||||
|
var ErrShutdown = errors.New("job manager is shut down")
|
||||||
|
|
||||||
|
// Releaser is something a job holds while it runs (a connection lease, a
|
||||||
|
// mounted archive). The Manager calls Release exactly once when the job
|
||||||
|
// ends, whatever the outcome.
|
||||||
|
type Releaser interface{ Release() }
|
||||||
|
|
||||||
|
// Func is a job body. It must return soon after ctx is cancelled.
|
||||||
|
type Func func(ctx context.Context, h *Handle) (result any, err error)
|
||||||
|
|
||||||
|
type job struct {
|
||||||
|
id ID
|
||||||
|
kind Kind
|
||||||
|
title string
|
||||||
|
state State
|
||||||
|
progress Progress
|
||||||
|
dirty bool
|
||||||
|
started time.Time
|
||||||
|
background bool
|
||||||
|
result any
|
||||||
|
err error
|
||||||
|
asking int
|
||||||
|
|
||||||
|
fn Func
|
||||||
|
holds []Releaser
|
||||||
|
ctx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
}
|
||||||
|
|
||||||
|
type pending struct {
|
||||||
|
q Question
|
||||||
|
ch chan any
|
||||||
|
j *job
|
||||||
|
}
|
||||||
|
|
||||||
|
// Manager runs jobs. It is safe for concurrent use.
|
||||||
|
type Manager struct {
|
||||||
|
notify func(Event)
|
||||||
|
maxParallel int
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
nextID ID
|
||||||
|
nextQID uint64
|
||||||
|
jobs map[ID]*job
|
||||||
|
finished []ID // finished job IDs, oldest first
|
||||||
|
queue []*job
|
||||||
|
running int // Running or Waiting
|
||||||
|
questions map[uint64]*pending
|
||||||
|
shutdown bool
|
||||||
|
|
||||||
|
events []Event
|
||||||
|
dispatching bool
|
||||||
|
ticking bool
|
||||||
|
changed chan struct{} // closed and replaced on every idle-relevant change
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a Manager. notify receives every Event (main forwards them
|
||||||
|
// with program.Send); nil discards them.
|
||||||
|
func New(notify func(Event), maxParallel int) *Manager {
|
||||||
|
if maxParallel <= 0 {
|
||||||
|
maxParallel = DefaultMaxParallel
|
||||||
|
}
|
||||||
|
if notify == nil {
|
||||||
|
notify = func(Event) {}
|
||||||
|
}
|
||||||
|
return &Manager{
|
||||||
|
notify: notify,
|
||||||
|
maxParallel: maxParallel,
|
||||||
|
jobs: map[ID]*job{},
|
||||||
|
questions: map[uint64]*pending{},
|
||||||
|
changed: make(chan struct{}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// broadcastLocked wakes Shutdown waiters.
|
||||||
|
func (m *Manager) broadcastLocked() {
|
||||||
|
close(m.changed)
|
||||||
|
m.changed = make(chan struct{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// safeGo runs fn in a goroutine that logs and swallows panics.
|
||||||
|
func safeGo(what string, fn func()) {
|
||||||
|
go func() {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
slog.Error("jobs: panic", "in", what, "panic", r, "stack", string(debug.Stack()))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
fn()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// emitLocked queues e for the dispatcher; m.mu is held.
|
||||||
|
func (m *Manager) emitLocked(e Event) {
|
||||||
|
m.events = append(m.events, e)
|
||||||
|
if !m.dispatching {
|
||||||
|
m.dispatching = true
|
||||||
|
safeGo("dispatch", m.dispatch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) dispatch() {
|
||||||
|
defer func() {
|
||||||
|
// notify panicked: keep delivering on a fresh goroutine.
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
slog.Error("jobs: notify panicked", "panic", r, "stack", string(debug.Stack()))
|
||||||
|
m.mu.Lock()
|
||||||
|
m.dispatching = false
|
||||||
|
if len(m.events) > 0 {
|
||||||
|
m.dispatching = true
|
||||||
|
safeGo("dispatch", m.dispatch)
|
||||||
|
}
|
||||||
|
m.broadcastLocked()
|
||||||
|
m.mu.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for {
|
||||||
|
m.mu.Lock()
|
||||||
|
if len(m.events) == 0 {
|
||||||
|
m.dispatching = false
|
||||||
|
m.broadcastLocked()
|
||||||
|
m.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
batch := m.events
|
||||||
|
m.events = nil
|
||||||
|
m.mu.Unlock()
|
||||||
|
for i, e := range batch {
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
m.mu.Lock()
|
||||||
|
m.events = append(batch[i+1:len(batch):len(batch)], m.events...)
|
||||||
|
m.mu.Unlock()
|
||||||
|
panic(r)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
m.notify(e)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j *job) snapshot() Snapshot {
|
||||||
|
return Snapshot{
|
||||||
|
ID: j.id, Kind: j.kind, Title: j.title, State: j.state, Progress: j.progress,
|
||||||
|
Started: j.started, Background: j.background, Result: j.result, Err: j.err,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start queues a job and returns its ID. holds are released when the job
|
||||||
|
// ends (also when it is cancelled before running, or started after
|
||||||
|
// Shutdown).
|
||||||
|
func (m *Manager) Start(k Kind, title string, fn Func, holds ...Releaser) ID {
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
m.nextID++
|
||||||
|
j := &job{
|
||||||
|
id: m.nextID, kind: k, title: title, state: Queued, started: time.Now(),
|
||||||
|
fn: fn, holds: holds, ctx: ctx, cancel: cancel,
|
||||||
|
}
|
||||||
|
m.jobs[j.id] = j
|
||||||
|
if m.shutdown {
|
||||||
|
m.emitLocked(Started{Snapshot: j.snapshot()})
|
||||||
|
m.finishLocked(j, Cancelled, nil, ErrShutdown)
|
||||||
|
return j.id
|
||||||
|
}
|
||||||
|
m.queue = append(m.queue, j)
|
||||||
|
m.scheduleLocked()
|
||||||
|
m.emitLocked(Started{Snapshot: j.snapshot()})
|
||||||
|
return j.id
|
||||||
|
}
|
||||||
|
|
||||||
|
// scheduleLocked starts queued jobs while slots are free.
|
||||||
|
func (m *Manager) scheduleLocked() {
|
||||||
|
for m.running < m.maxParallel && len(m.queue) > 0 {
|
||||||
|
j := m.queue[0]
|
||||||
|
m.queue = m.queue[1:]
|
||||||
|
m.running++
|
||||||
|
j.state = Running
|
||||||
|
j.dirty = true
|
||||||
|
m.startTickerLocked()
|
||||||
|
safeGo("job", func() { m.run(j) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) run(j *job) {
|
||||||
|
var (
|
||||||
|
res any
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
slog.Error("jobs: job panicked", "job", j.id, "kind", j.kind, "panic", r, "stack", string(debug.Stack()))
|
||||||
|
err = fmt.Errorf("job %q panicked: %v", j.title, r)
|
||||||
|
res = nil
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
res, err = j.fn(j.ctx, &Handle{m: m, j: j})
|
||||||
|
}()
|
||||||
|
state := Done
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
case errors.Is(err, context.Canceled):
|
||||||
|
state = Cancelled
|
||||||
|
default:
|
||||||
|
state = Failed
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
m.running--
|
||||||
|
m.finishLocked(j, state, res, err)
|
||||||
|
m.scheduleLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
// finishLocked moves j to a terminal state, releases its holds and emits
|
||||||
|
// Finished.
|
||||||
|
func (m *Manager) finishLocked(j *job, s State, res any, err error) {
|
||||||
|
j.state, j.result, j.err, j.dirty = s, res, err, false
|
||||||
|
j.cancel()
|
||||||
|
for qid, p := range m.questions {
|
||||||
|
if p.j == j {
|
||||||
|
delete(m.questions, qid)
|
||||||
|
m.emitLocked(Unasked{Question: p.q})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, h := range j.holds {
|
||||||
|
release(h)
|
||||||
|
}
|
||||||
|
j.holds = nil
|
||||||
|
j.fn = nil
|
||||||
|
m.emitLocked(Finished{Snapshot: j.snapshot()})
|
||||||
|
m.finished = append(m.finished, j.id)
|
||||||
|
if len(m.finished) > keepFinished {
|
||||||
|
delete(m.jobs, m.finished[0])
|
||||||
|
m.finished = m.finished[1:]
|
||||||
|
}
|
||||||
|
m.broadcastLocked()
|
||||||
|
}
|
||||||
|
|
||||||
|
func release(h Releaser) {
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
slog.Error("jobs: Release panicked", "panic", r, "stack", string(debug.Stack()))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
h.Release()
|
||||||
|
}
|
||||||
|
|
||||||
|
// startTickerLocked runs the progress ticker while jobs are active.
|
||||||
|
func (m *Manager) startTickerLocked() {
|
||||||
|
if m.ticking {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.ticking = true
|
||||||
|
safeGo("ticker", m.tick)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) tick() {
|
||||||
|
t := time.NewTicker(tickInterval)
|
||||||
|
defer t.Stop()
|
||||||
|
for range t.C {
|
||||||
|
m.mu.Lock()
|
||||||
|
var snaps []Snapshot
|
||||||
|
for _, j := range m.jobs {
|
||||||
|
if j.dirty && !j.state.Finished() {
|
||||||
|
j.dirty = false
|
||||||
|
snaps = append(snaps, j.snapshot())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(snaps) > 0 {
|
||||||
|
sort.Slice(snaps, func(a, b int) bool { return snaps[a].ID < snaps[b].ID })
|
||||||
|
m.emitLocked(ProgressTick{Snapshots: snaps})
|
||||||
|
}
|
||||||
|
if m.running == 0 && len(m.queue) == 0 {
|
||||||
|
m.ticking = false
|
||||||
|
m.broadcastLocked()
|
||||||
|
m.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Answer delivers the user's answer to question qid. Unknown or already
|
||||||
|
// withdrawn questions are ignored.
|
||||||
|
func (m *Manager) Answer(qid uint64, answer any) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
p := m.questions[qid]
|
||||||
|
if p == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delete(m.questions, qid)
|
||||||
|
p.ch <- answer // buffered, never blocks
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cancel cancels a job: a queued job ends at once as Cancelled, a running
|
||||||
|
// one gets its ctx cancelled (and any pending Ask returns).
|
||||||
|
func (m *Manager) Cancel(id ID) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
j := m.jobs[id]
|
||||||
|
if j == nil || j.state.Finished() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if j.state == Queued {
|
||||||
|
m.dequeueLocked(j)
|
||||||
|
m.finishLocked(j, Cancelled, nil, context.Canceled)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
j.cancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Manager) dequeueLocked(j *job) {
|
||||||
|
for i, q := range m.queue {
|
||||||
|
if q == j {
|
||||||
|
m.queue = append(m.queue[:i], m.queue[i+1:]...)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetBackground marks a job as running in the background (the UI closes its
|
||||||
|
// progress dialog).
|
||||||
|
func (m *Manager) SetBackground(id ID, bg bool) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
if j := m.jobs[id]; j != nil && j.background != bg {
|
||||||
|
j.background = bg
|
||||||
|
if !j.state.Finished() {
|
||||||
|
j.dirty = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot returns all known jobs (active and the last finished ones) by ID.
|
||||||
|
func (m *Manager) Snapshot() []Snapshot {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
out := make([]Snapshot, 0, len(m.jobs))
|
||||||
|
for _, j := range m.jobs {
|
||||||
|
out = append(out, j.snapshot())
|
||||||
|
}
|
||||||
|
sort.Slice(out, func(a, b int) bool { return out[a].ID < out[b].ID })
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get returns one job's snapshot.
|
||||||
|
func (m *Manager) Get(id ID) (Snapshot, bool) {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
j := m.jobs[id]
|
||||||
|
if j == nil {
|
||||||
|
return Snapshot{}, false
|
||||||
|
}
|
||||||
|
return j.snapshot(), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Active counts queued, running and waiting jobs.
|
||||||
|
func (m *Manager) Active() int {
|
||||||
|
m.mu.Lock()
|
||||||
|
defer m.mu.Unlock()
|
||||||
|
return m.running + len(m.queue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shutdown cancels every job, refuses new ones and waits until running jobs
|
||||||
|
// have returned (so they can remove temp files) and all events have been
|
||||||
|
// delivered, or until ctx is done.
|
||||||
|
func (m *Manager) Shutdown(ctx context.Context) error {
|
||||||
|
m.mu.Lock()
|
||||||
|
m.shutdown = true
|
||||||
|
for len(m.queue) > 0 {
|
||||||
|
j := m.queue[0]
|
||||||
|
m.queue = m.queue[1:]
|
||||||
|
m.finishLocked(j, Cancelled, nil, context.Canceled)
|
||||||
|
}
|
||||||
|
for _, j := range m.jobs {
|
||||||
|
if !j.state.Finished() {
|
||||||
|
j.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m.mu.Unlock()
|
||||||
|
for {
|
||||||
|
m.mu.Lock()
|
||||||
|
idle := m.running == 0 && !m.dispatching && !m.ticking
|
||||||
|
ch := m.changed
|
||||||
|
m.mu.Unlock()
|
||||||
|
if idle {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ch:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
447
internal/jobs/manager_test.go
Normal file
447
internal/jobs/manager_test.go
Normal file
|
|
@ -0,0 +1,447 @@
|
||||||
|
package jobs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// noLeak runs fn as a subtest and checks the goroutine count returns to the
|
||||||
|
// baseline afterwards.
|
||||||
|
func noLeak(t *testing.T, fn func(t *testing.T)) {
|
||||||
|
t.Helper()
|
||||||
|
runtime.GC()
|
||||||
|
base := runtime.NumGoroutine()
|
||||||
|
t.Run("body", fn)
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
var n int
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if n = runtime.NumGoroutine(); n <= base {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
buf := make([]byte, 1<<20)
|
||||||
|
t.Errorf("goroutines: base=%d after=%d\n%s", base, n, buf[:runtime.Stack(buf, true)])
|
||||||
|
}
|
||||||
|
|
||||||
|
// recorder collects events.
|
||||||
|
type recorder struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
ev []Event
|
||||||
|
at []time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recorder) notify(e Event) {
|
||||||
|
r.mu.Lock()
|
||||||
|
r.ev = append(r.ev, e)
|
||||||
|
r.at = append(r.at, time.Now())
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recorder) events() []Event {
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
return append([]Event(nil), r.ev...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recorder) finished(id ID) (Snapshot, bool) {
|
||||||
|
for _, e := range r.events() {
|
||||||
|
if f, ok := e.(Finished); ok && f.Snapshot.ID == id {
|
||||||
|
return f.Snapshot, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Snapshot{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *recorder) asked() []Question {
|
||||||
|
var qs []Question
|
||||||
|
for _, e := range r.events() {
|
||||||
|
if a, ok := e.(Asked); ok {
|
||||||
|
qs = append(qs, a.Question)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return qs
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitFor(t *testing.T, what string, cond func() bool) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
for !cond() {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("timed out waiting for %s", what)
|
||||||
|
}
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func shutdown(t *testing.T, m *Manager) {
|
||||||
|
t.Helper()
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := m.Shutdown(ctx); err != nil {
|
||||||
|
t.Fatalf("Shutdown: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type hold struct{ n atomic.Int32 }
|
||||||
|
|
||||||
|
func (h *hold) Release() { h.n.Add(1) }
|
||||||
|
|
||||||
|
// U section 2: progress went through a 256-slot channel with a full View per
|
||||||
|
// file. 100k SetProgress must neither slow the job down (even if nobody
|
||||||
|
// reads events) nor produce more than ~10 ticks per second.
|
||||||
|
func TestProgressCoalesced(t *testing.T) {
|
||||||
|
t.Run("NoReader", func(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
unblock := make(chan struct{})
|
||||||
|
m := New(func(Event) { <-unblock }, 2) // like an unread program.Send
|
||||||
|
done := make(chan time.Duration, 1)
|
||||||
|
m.Start("copy", "fast", func(ctx context.Context, h *Handle) (any, error) {
|
||||||
|
start := time.Now()
|
||||||
|
for i := 0; i < 100_000; i++ {
|
||||||
|
h.SetProgress(Progress{FilesDone: i, BytesDone: int64(i) * 10})
|
||||||
|
}
|
||||||
|
done <- time.Since(start)
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
select {
|
||||||
|
case el := <-done:
|
||||||
|
if el > 100*time.Millisecond {
|
||||||
|
t.Errorf("100k SetProgress took %v", el)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("job blocked by an unread notify")
|
||||||
|
}
|
||||||
|
waitFor(t, "job finished", func() bool { return m.Active() == 0 })
|
||||||
|
close(unblock)
|
||||||
|
shutdown(t, m)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.Run("TickRate", func(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 2)
|
||||||
|
id := m.Start("copy", "steady", func(ctx context.Context, h *Handle) (any, error) {
|
||||||
|
end := time.Now().Add(time.Second)
|
||||||
|
for i := 0; time.Now().Before(end); i++ {
|
||||||
|
h.SetProgress(Progress{FilesDone: i})
|
||||||
|
if i%100 == 0 {
|
||||||
|
runtime.Gosched()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.SetProgress(Progress{FilesDone: -1, Phase: "final"})
|
||||||
|
return "ok", nil
|
||||||
|
})
|
||||||
|
waitFor(t, "finished", func() bool { _, ok := rec.finished(id); return ok })
|
||||||
|
shutdown(t, m)
|
||||||
|
ticks := 0
|
||||||
|
for _, e := range rec.events() {
|
||||||
|
if _, ok := e.(ProgressTick); ok {
|
||||||
|
ticks++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ticks > 11 || ticks < 5 {
|
||||||
|
t.Errorf("%d ticks in ~1s, want 5..11", ticks)
|
||||||
|
}
|
||||||
|
// Finished is last for the job and carries the final progress.
|
||||||
|
evs := rec.events()
|
||||||
|
f, ok := evs[len(evs)-1].(Finished)
|
||||||
|
if !ok || f.Snapshot.Progress.Phase != "final" || f.Snapshot.State != Done || f.Snapshot.Result != "ok" {
|
||||||
|
t.Errorf("last event = %#v", evs[len(evs)-1])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAskBlocksOnlyJob(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 2)
|
||||||
|
got := make(chan any, 1)
|
||||||
|
asker := m.Start("copy", "asker", func(ctx context.Context, h *Handle) (any, error) {
|
||||||
|
a, err := h.Ask(ctx, "overwrite?")
|
||||||
|
got <- a
|
||||||
|
return a, err
|
||||||
|
})
|
||||||
|
waitFor(t, "question", func() bool { return len(rec.asked()) == 1 })
|
||||||
|
if s, _ := m.Get(asker); s.State != Waiting {
|
||||||
|
t.Errorf("asker state = %v", s.State)
|
||||||
|
}
|
||||||
|
other := m.Start("delete", "other", func(ctx context.Context, h *Handle) (any, error) { return 42, nil })
|
||||||
|
waitFor(t, "other job done while asker waits", func() bool { _, ok := rec.finished(other); return ok })
|
||||||
|
if m.Active() != 1 {
|
||||||
|
t.Errorf("Active = %d", m.Active())
|
||||||
|
}
|
||||||
|
q := rec.asked()[0]
|
||||||
|
if q.Job != asker || q.Payload != "overwrite?" {
|
||||||
|
t.Errorf("question = %+v", q)
|
||||||
|
}
|
||||||
|
m.Answer(q.QID, "yes")
|
||||||
|
m.Answer(q.QID, "again") // ignored
|
||||||
|
if a := <-got; a != "yes" {
|
||||||
|
t.Errorf("answer = %v", a)
|
||||||
|
}
|
||||||
|
waitFor(t, "asker done", func() bool { _, ok := rec.finished(asker); return ok })
|
||||||
|
if s, _ := rec.finished(asker); s.State != Done || s.Result != "yes" {
|
||||||
|
t.Errorf("asker = %+v", s)
|
||||||
|
}
|
||||||
|
shutdown(t, m)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCancelWhileWaiting(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 2)
|
||||||
|
h1 := &hold{}
|
||||||
|
askErr := make(chan error, 1)
|
||||||
|
id := m.Start("copy", "c", func(ctx context.Context, h *Handle) (any, error) {
|
||||||
|
_, err := h.Ask(ctx, "conflict")
|
||||||
|
askErr <- err
|
||||||
|
return nil, err
|
||||||
|
}, h1)
|
||||||
|
waitFor(t, "question", func() bool { return len(rec.asked()) == 1 })
|
||||||
|
m.Cancel(id)
|
||||||
|
select {
|
||||||
|
case err := <-askErr:
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("Ask err = %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("Ask not released by Cancel")
|
||||||
|
}
|
||||||
|
waitFor(t, "finished", func() bool { _, ok := rec.finished(id); return ok })
|
||||||
|
s, _ := rec.finished(id)
|
||||||
|
if s.State != Cancelled || h1.n.Load() != 1 {
|
||||||
|
t.Errorf("state %v, releases %d", s.State, h1.n.Load())
|
||||||
|
}
|
||||||
|
unasked := false
|
||||||
|
for _, e := range rec.events() {
|
||||||
|
if u, ok := e.(Unasked); ok && u.Question.QID == rec.asked()[0].QID {
|
||||||
|
unasked = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !unasked {
|
||||||
|
t.Error("no Unasked event")
|
||||||
|
}
|
||||||
|
m.Answer(rec.asked()[0].QID, "late") // no-op, must not block or panic
|
||||||
|
|
||||||
|
// The Ask ctx alone withdraws the question; the job continues.
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
id2 := m.Start("copy", "c2", func(_ context.Context, h *Handle) (any, error) {
|
||||||
|
_, err := h.Ask(ctx, "q")
|
||||||
|
return "continued after " + err.Error(), nil
|
||||||
|
})
|
||||||
|
waitFor(t, "second question", func() bool { return len(rec.asked()) == 2 })
|
||||||
|
cancel()
|
||||||
|
waitFor(t, "second finished", func() bool { _, ok := rec.finished(id2); return ok })
|
||||||
|
if s, _ := rec.finished(id2); s.State != Done {
|
||||||
|
t.Errorf("job after Ask ctx cancel = %+v", s)
|
||||||
|
}
|
||||||
|
shutdown(t, m)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPanicBecomesFailed(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 1)
|
||||||
|
h1 := &hold{}
|
||||||
|
id := m.Start("copy", "boom", func(ctx context.Context, h *Handle) (any, error) {
|
||||||
|
var p *Progress
|
||||||
|
_ = p.Phase // nil dereference
|
||||||
|
return nil, nil
|
||||||
|
}, h1)
|
||||||
|
next := m.Start("copy", "next", func(ctx context.Context, h *Handle) (any, error) { return nil, nil })
|
||||||
|
waitFor(t, "both finished", func() bool {
|
||||||
|
_, a := rec.finished(id)
|
||||||
|
_, b := rec.finished(next)
|
||||||
|
return a && b
|
||||||
|
})
|
||||||
|
s, _ := rec.finished(id)
|
||||||
|
if s.State != Failed || s.Err == nil || !strings.Contains(s.Err.Error(), "panicked") || h1.n.Load() != 1 {
|
||||||
|
t.Errorf("panicking job = %+v, releases %d", s, h1.n.Load())
|
||||||
|
}
|
||||||
|
if s, _ := rec.finished(next); s.State != Done {
|
||||||
|
t.Errorf("next job = %+v", s)
|
||||||
|
}
|
||||||
|
// A panicking notify does not stop event delivery.
|
||||||
|
var calls atomic.Int32
|
||||||
|
m2 := New(func(e Event) {
|
||||||
|
if calls.Add(1) == 1 {
|
||||||
|
panic("ui bug")
|
||||||
|
}
|
||||||
|
}, 1)
|
||||||
|
m2.Start("copy", "x", func(ctx context.Context, h *Handle) (any, error) { return nil, nil })
|
||||||
|
waitFor(t, "events after notify panic", func() bool { return calls.Load() >= 2 })
|
||||||
|
shutdown(t, m2)
|
||||||
|
shutdown(t, m)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHoldsReleasedOnAllPaths(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
m := New(nil, 1)
|
||||||
|
var holds []*hold
|
||||||
|
h := func() *hold { x := &hold{}; holds = append(holds, x); return x }
|
||||||
|
block := make(chan struct{})
|
||||||
|
m.Start("copy", "ok", func(ctx context.Context, _ *Handle) (any, error) { return nil, nil }, h(), h())
|
||||||
|
m.Start("copy", "err", func(ctx context.Context, _ *Handle) (any, error) { return nil, errors.New("x") }, h())
|
||||||
|
m.Start("copy", "panic", func(ctx context.Context, _ *Handle) (any, error) { panic("p") }, h())
|
||||||
|
running := m.Start("copy", "cancel-running", func(ctx context.Context, _ *Handle) (any, error) {
|
||||||
|
close(block)
|
||||||
|
<-ctx.Done()
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}, h())
|
||||||
|
queued := m.Start("copy", "cancel-queued", func(ctx context.Context, _ *Handle) (any, error) { return nil, nil }, h())
|
||||||
|
<-block
|
||||||
|
m.Cancel(queued)
|
||||||
|
m.Cancel(running)
|
||||||
|
m.Start("copy", "on-shutdown-queue", func(ctx context.Context, _ *Handle) (any, error) {
|
||||||
|
<-ctx.Done()
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}, h())
|
||||||
|
shutdown(t, m)
|
||||||
|
after := m.Start("copy", "after-shutdown", func(ctx context.Context, _ *Handle) (any, error) {
|
||||||
|
t.Error("job ran after Shutdown")
|
||||||
|
return nil, nil
|
||||||
|
}, h())
|
||||||
|
if s, _ := m.Get(after); s.State != Cancelled || !errors.Is(s.Err, ErrShutdown) {
|
||||||
|
t.Errorf("after shutdown: %+v", s)
|
||||||
|
}
|
||||||
|
for i, x := range holds {
|
||||||
|
if n := x.n.Load(); n != 1 {
|
||||||
|
t.Errorf("hold %d released %d times", i, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want := map[string]State{"ok": Done, "err": Failed, "panic": Failed, "cancel-running": Cancelled,
|
||||||
|
"cancel-queued": Cancelled, "on-shutdown-queue": Cancelled, "after-shutdown": Cancelled}
|
||||||
|
for _, s := range m.Snapshot() {
|
||||||
|
if s.State != want[s.Title] {
|
||||||
|
t.Errorf("%s: state %v, want %v", s.Title, s.State, want[s.Title])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// U section 3: "Transfer is already running" — now jobs queue.
|
||||||
|
func TestQueueRespectsMaxParallel(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 2)
|
||||||
|
var cur, peak atomic.Int32
|
||||||
|
var mu sync.Mutex
|
||||||
|
var order []int
|
||||||
|
var ids []ID
|
||||||
|
for i := 0; i < 6; i++ {
|
||||||
|
ids = append(ids, m.Start("copy", "j", func(ctx context.Context, _ *Handle) (any, error) {
|
||||||
|
mu.Lock()
|
||||||
|
order = append(order, i)
|
||||||
|
mu.Unlock()
|
||||||
|
n := cur.Add(1)
|
||||||
|
for {
|
||||||
|
p := peak.Load()
|
||||||
|
if n <= p || peak.CompareAndSwap(p, n) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
cur.Add(-1)
|
||||||
|
return nil, nil
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
if s, _ := m.Get(ids[5]); s.State != Queued {
|
||||||
|
t.Errorf("6th job state = %v, want queued", s.State)
|
||||||
|
}
|
||||||
|
waitFor(t, "all done", func() bool { return m.Active() == 0 })
|
||||||
|
shutdown(t, m)
|
||||||
|
if p := peak.Load(); p != 2 {
|
||||||
|
t.Errorf("peak parallel = %d, want 2", p)
|
||||||
|
}
|
||||||
|
if order[0] > 1 || order[5] < 4 {
|
||||||
|
t.Errorf("not FIFO: %v", order)
|
||||||
|
}
|
||||||
|
for _, id := range ids {
|
||||||
|
if s, ok := rec.finished(id); !ok || s.State != Done {
|
||||||
|
t.Errorf("job %d: %+v", id, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestShutdownWaitsCleanup(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 2)
|
||||||
|
var cleaned atomic.Bool
|
||||||
|
id := m.Start("copy", "c", func(ctx context.Context, _ *Handle) (any, error) {
|
||||||
|
<-ctx.Done()
|
||||||
|
time.Sleep(100 * time.Millisecond) // remove temp files
|
||||||
|
cleaned.Store(true)
|
||||||
|
return nil, ctx.Err()
|
||||||
|
})
|
||||||
|
waitFor(t, "running", func() bool { s, _ := m.Get(id); return s.State == Running })
|
||||||
|
shutdown(t, m)
|
||||||
|
if !cleaned.Load() {
|
||||||
|
t.Error("Shutdown returned before the job cleaned up")
|
||||||
|
}
|
||||||
|
if _, ok := rec.finished(id); !ok {
|
||||||
|
t.Error("Finished not delivered before Shutdown returned")
|
||||||
|
}
|
||||||
|
|
||||||
|
// A job ignoring cancellation: Shutdown gives up at the deadline.
|
||||||
|
m2 := New(nil, 1)
|
||||||
|
release := make(chan struct{})
|
||||||
|
m2.Start("copy", "stubborn", func(ctx context.Context, _ *Handle) (any, error) {
|
||||||
|
<-release
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
start := time.Now()
|
||||||
|
if err := m2.Shutdown(ctx); !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Errorf("Shutdown = %v", err)
|
||||||
|
}
|
||||||
|
if el := time.Since(start); el > 500*time.Millisecond {
|
||||||
|
t.Errorf("Shutdown waited %v", el)
|
||||||
|
}
|
||||||
|
close(release)
|
||||||
|
shutdown(t, m2)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBackgroundAndSnapshot(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
var rec recorder
|
||||||
|
m := New(rec.notify, 1)
|
||||||
|
stop := make(chan struct{})
|
||||||
|
id := m.Start("copy", "bg", func(ctx context.Context, h *Handle) (any, error) {
|
||||||
|
<-stop
|
||||||
|
return nil, nil
|
||||||
|
})
|
||||||
|
m.SetBackground(id, true)
|
||||||
|
waitFor(t, "tick with background flag", func() bool {
|
||||||
|
for _, e := range rec.events() {
|
||||||
|
if pt, ok := e.(ProgressTick); ok {
|
||||||
|
for _, s := range pt.Snapshots {
|
||||||
|
if s.ID == id && s.Background && s.State == Running {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
})
|
||||||
|
close(stop)
|
||||||
|
shutdown(t, m)
|
||||||
|
if snaps := m.Snapshot(); len(snaps) != 1 || !snaps[0].Background || snaps[0].State != Done {
|
||||||
|
t.Errorf("snapshot = %+v", snaps)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
151
internal/logx/logx.go
Normal file
151
internal/logx/logx.go
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
// Package logx sets up vcom's log (design §9.3): log/slog text records in
|
||||||
|
// $XDG_STATE_HOME/vcom/vcom.log (file 0600, directory 0700), level from
|
||||||
|
// --log-level / --debug / $VCOM_LOG (default warn), one rotation on start when
|
||||||
|
// the file exceeds 5 MiB. Secrets (password, passphrase, keyboard-interactive
|
||||||
|
// answers) are redacted by attribute name and never reach the file.
|
||||||
|
package logx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxSize is the size above which the log is rotated to vcom.log.1 on start.
|
||||||
|
const MaxSize = 5 << 20
|
||||||
|
|
||||||
|
// FileName is the log file name inside the state directory.
|
||||||
|
const FileName = "vcom.log"
|
||||||
|
|
||||||
|
// Options configure Open.
|
||||||
|
type Options struct {
|
||||||
|
Dir string // state directory; created 0700
|
||||||
|
Level slog.Level // minimum level written
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logger is an open log file with its slog logger.
|
||||||
|
type Logger struct {
|
||||||
|
*slog.Logger
|
||||||
|
Path string
|
||||||
|
file *os.File
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close flushes and closes the file. Safe on nil.
|
||||||
|
func (l *Logger) Close() error {
|
||||||
|
if l == nil || l.file == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return l.file.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLevel accepts debug | info | warn | warning | error (any case).
|
||||||
|
func ParseLevel(s string) (slog.Level, error) {
|
||||||
|
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||||
|
case "debug":
|
||||||
|
return slog.LevelDebug, nil
|
||||||
|
case "info":
|
||||||
|
return slog.LevelInfo, nil
|
||||||
|
case "", "warn", "warning":
|
||||||
|
return slog.LevelWarn, nil
|
||||||
|
case "error":
|
||||||
|
return slog.LevelError, nil
|
||||||
|
}
|
||||||
|
return slog.LevelWarn, fmt.Errorf("unknown log level %q (want debug, info, warn or error)", s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveLevel picks the level: --debug, then --log-level, then $VCOM_LOG,
|
||||||
|
// then warn.
|
||||||
|
func ResolveLevel(debug bool, flagLevel, env string) (slog.Level, error) {
|
||||||
|
switch {
|
||||||
|
case debug:
|
||||||
|
return slog.LevelDebug, nil
|
||||||
|
case flagLevel != "":
|
||||||
|
return ParseLevel(flagLevel)
|
||||||
|
default:
|
||||||
|
return ParseLevel(env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open rotates and opens the log file and returns a logger writing to it.
|
||||||
|
func Open(o Options) (*Logger, error) {
|
||||||
|
if err := os.MkdirAll(o.Dir, 0o700); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_ = os.Chmod(o.Dir, 0o700)
|
||||||
|
p := filepath.Join(o.Dir, FileName)
|
||||||
|
if err := rotate(p); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f, err := os.OpenFile(p, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := f.Chmod(0o600); err != nil { // an older file may have been 0644
|
||||||
|
f.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &Logger{Logger: slog.New(NewHandler(f, o.Level)), Path: p, file: f}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rotate moves p to p.1 (replacing an older .1) when p exceeds MaxSize.
|
||||||
|
func rotate(p string) error {
|
||||||
|
fi, err := os.Stat(p)
|
||||||
|
if err != nil || fi.Size() <= MaxSize {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return os.Rename(p, p+".1")
|
||||||
|
}
|
||||||
|
|
||||||
|
// secretKeys are attribute names whose values are never logged.
|
||||||
|
var secretKeys = map[string]bool{
|
||||||
|
"password": true,
|
||||||
|
"passphrase": true,
|
||||||
|
"answers": true,
|
||||||
|
"answer": true,
|
||||||
|
"secret": true,
|
||||||
|
"token": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redacted replaces secret values.
|
||||||
|
const Redacted = "[REDACTED]"
|
||||||
|
|
||||||
|
// NewHandler returns a text handler at level that redacts secrets.
|
||||||
|
func NewHandler(w io.Writer, level slog.Level) slog.Handler {
|
||||||
|
return slog.NewTextHandler(w, &slog.HandlerOptions{
|
||||||
|
Level: level,
|
||||||
|
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
|
||||||
|
if secretKeys[strings.ToLower(a.Key)] {
|
||||||
|
return slog.String(a.Key, Redacted)
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Discard is a logger that drops everything (when the log file cannot be
|
||||||
|
// opened).
|
||||||
|
func Discard() *Logger {
|
||||||
|
return &Logger{Logger: slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError + 100}))}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RedirectStdLog sends the standard "log" package (the old UI's 178
|
||||||
|
// log.Printf calls) to l at debug level.
|
||||||
|
func RedirectStdLog(l *slog.Logger) {
|
||||||
|
log.SetFlags(0)
|
||||||
|
log.SetPrefix("")
|
||||||
|
log.SetOutput(stdWriter{l})
|
||||||
|
}
|
||||||
|
|
||||||
|
type stdWriter struct{ l *slog.Logger }
|
||||||
|
|
||||||
|
func (w stdWriter) Write(b []byte) (int, error) {
|
||||||
|
if w.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
|
w.l.Debug(strings.TrimRight(string(b), "\n"), "src", "ui")
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
}
|
||||||
132
internal/logx/logx_test.go
Normal file
132
internal/logx/logx_test.go
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
package logx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"log"
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestRotateOver5MiB(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, FileName)
|
||||||
|
big := bytes.Repeat([]byte("x"), MaxSize+1)
|
||||||
|
if err := os.WriteFile(p, big, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p+".1", []byte("older"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l, err := Open(Options{Dir: dir, Level: slog.LevelInfo})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.Info("fresh")
|
||||||
|
l.Close()
|
||||||
|
if fi, err := os.Stat(p + ".1"); err != nil || fi.Size() != MaxSize+1 {
|
||||||
|
t.Fatalf("rotated file: %v %v", fi, err)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(p); !strings.Contains(string(b), "fresh") || len(b) > 1000 {
|
||||||
|
t.Fatalf("new log: %d bytes", len(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
// At or under the limit: appended, not rotated.
|
||||||
|
small := filepath.Join(t.TempDir(), FileName)
|
||||||
|
if err := os.WriteFile(small, []byte("keep\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l, err = Open(Options{Dir: filepath.Dir(small), Level: slog.LevelInfo})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.Info("more")
|
||||||
|
l.Close()
|
||||||
|
if b, _ := os.ReadFile(small); !strings.HasPrefix(string(b), "keep\n") {
|
||||||
|
t.Fatalf("small log not appended: %q", b)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(small + ".1"); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("small log rotated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogFilePerms(t *testing.T) {
|
||||||
|
dir := filepath.Join(t.TempDir(), "state", "vcom")
|
||||||
|
l, err := Open(Options{Dir: dir, Level: slog.LevelWarn})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.Close()
|
||||||
|
if fi, _ := os.Stat(dir); fi.Mode().Perm() != 0o700 {
|
||||||
|
t.Fatalf("dir mode %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(filepath.Join(dir, FileName)); fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("file mode %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
// An existing world-readable log is tightened.
|
||||||
|
p := filepath.Join(dir, FileName)
|
||||||
|
if err := os.Chmod(p, 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l, err = Open(Options{Dir: dir})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.Close()
|
||||||
|
if fi, _ := os.Stat(p); fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("existing file mode %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRedactSecrets(t *testing.T) {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
l := slog.New(NewHandler(&buf, slog.LevelDebug))
|
||||||
|
l.Info("auth", "user", "bob", "password", "hunter2", "Passphrase", "s3cret-pp",
|
||||||
|
slog.Group("ki", slog.Any("answers", []string{"123456"})))
|
||||||
|
l.With("password", "withpw").Debug("again")
|
||||||
|
out := buf.String()
|
||||||
|
for _, secret := range []string{"hunter2", "s3cret-pp", "123456", "withpw"} {
|
||||||
|
if strings.Contains(out, secret) {
|
||||||
|
t.Fatalf("secret %q leaked:\n%s", secret, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(out, "user=bob") || strings.Count(out, Redacted) != 4 {
|
||||||
|
t.Fatalf("output:\n%s", out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLevelsAndStdLog(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
debug bool
|
||||||
|
flag, env string
|
||||||
|
want slog.Level
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{false, "", "", slog.LevelWarn, false},
|
||||||
|
{true, "error", "info", slog.LevelDebug, false},
|
||||||
|
{false, "error", "debug", slog.LevelError, false},
|
||||||
|
{false, "", "INFO", slog.LevelInfo, false},
|
||||||
|
{false, "loud", "", slog.LevelWarn, true},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, err := ResolveLevel(c.debug, c.flag, c.env)
|
||||||
|
if got != c.want || (err != nil) != c.wantErr {
|
||||||
|
t.Errorf("%+v: got %v %v", c, got, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var buf bytes.Buffer
|
||||||
|
defer log.SetOutput(os.Stderr)
|
||||||
|
RedirectStdLog(slog.New(NewHandler(&buf, slog.LevelWarn)))
|
||||||
|
log.Printf("[KEY] j")
|
||||||
|
if buf.Len() != 0 {
|
||||||
|
t.Fatalf("old log.Printf must be debug-only: %q", buf.String())
|
||||||
|
}
|
||||||
|
RedirectStdLog(slog.New(NewHandler(&buf, slog.LevelDebug)))
|
||||||
|
log.Printf("[KEY] j")
|
||||||
|
if !strings.Contains(buf.String(), "level=DEBUG") || !strings.Contains(buf.String(), "[KEY] j") {
|
||||||
|
t.Fatalf("debug: %q", buf.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
317
internal/paths/paths.go
Normal file
317
internal/paths/paths.go
Normal file
|
|
@ -0,0 +1,317 @@
|
||||||
|
// Package paths decides where vcom reads and writes its files (design §9.1).
|
||||||
|
//
|
||||||
|
// - Config: -config PATH → $VCOM_CONFIG → $XDG_CONFIG_HOME/vcom/vcom.toml →
|
||||||
|
// ~/.config/vcom/vcom.toml. Never ./vcom.toml from the working directory.
|
||||||
|
// - State (session.toml, vcom.log): $XDG_STATE_HOME/vcom.
|
||||||
|
// - Cache and per-process temp files: $XDG_CACHE_HOME/vcom/run-<pid> (0700);
|
||||||
|
// run dirs of dead processes are swept on start (U-P1-15).
|
||||||
|
// - sudo: config and ~/.ssh are READ from the invoking user's home; state,
|
||||||
|
// cache, trash and known_hosts are WRITTEN only under the effective user's
|
||||||
|
// home, and inherited XDG_*_HOME variables are ignored for writing, so root
|
||||||
|
// never leaves files in ~user.
|
||||||
|
package paths
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"os/user"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// system is the process environment; tests replace it.
|
||||||
|
type system struct {
|
||||||
|
getenv func(string) string
|
||||||
|
geteuid func() int
|
||||||
|
getpid func() int
|
||||||
|
getwd func() (string, error)
|
||||||
|
homeOfUser func(name string) (string, error) // home of a user name
|
||||||
|
homeOfUID func(uid int) (string, error)
|
||||||
|
alive func(pid int) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var sys = osSystem()
|
||||||
|
|
||||||
|
func osSystem() system {
|
||||||
|
return system{
|
||||||
|
getenv: os.Getenv,
|
||||||
|
geteuid: os.Geteuid,
|
||||||
|
getpid: os.Getpid,
|
||||||
|
getwd: os.Getwd,
|
||||||
|
homeOfUser: func(name string) (string, error) {
|
||||||
|
u, err := user.Lookup(name)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return u.HomeDir, nil
|
||||||
|
},
|
||||||
|
homeOfUID: func(uid int) (string, error) {
|
||||||
|
u, err := user.LookupId(strconv.Itoa(uid))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return u.HomeDir, nil
|
||||||
|
},
|
||||||
|
alive: pidAlive,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pidAlive: signal 0 succeeds or fails with EPERM for a live process.
|
||||||
|
func pidAlive(pid int) bool {
|
||||||
|
err := syscall.Kill(pid, 0)
|
||||||
|
return err == nil || errors.Is(err, syscall.EPERM)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SudoUser returns the invoking user's name when running as root via sudo.
|
||||||
|
func SudoUser() (string, bool) {
|
||||||
|
if sys.geteuid() != 0 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
u := sys.getenv("SUDO_USER")
|
||||||
|
if u == "" || u == "root" {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return u, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func envHome() (string, error) {
|
||||||
|
if h := sys.getenv("HOME"); h != "" {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
if h, err := sys.homeOfUID(sys.geteuid()); err == nil && h != "" {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
return "", errors.New("cannot determine home directory")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadHome is the home to read user configuration from (vcom.toml, ~/.ssh):
|
||||||
|
// the invoking user's home under sudo, $HOME otherwise.
|
||||||
|
func ReadHome() (string, error) {
|
||||||
|
if name, ok := SudoUser(); ok {
|
||||||
|
if h, err := sys.homeOfUser(name); err == nil && h != "" {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return envHome()
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteHome is the home vcom may write under: the effective user's.
|
||||||
|
func WriteHome() (string, error) {
|
||||||
|
if _, ok := SudoUser(); ok {
|
||||||
|
h, err := sys.homeOfUID(sys.geteuid())
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("home of uid %d: %w", sys.geteuid(), err)
|
||||||
|
}
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
return envHome()
|
||||||
|
}
|
||||||
|
|
||||||
|
// xdgWrite returns $env (if absolute and not under sudo) or WriteHome/def.
|
||||||
|
func xdgWrite(env string, def ...string) (string, error) {
|
||||||
|
if _, sudo := SudoUser(); !sudo {
|
||||||
|
if d := sys.getenv(env); filepath.IsAbs(d) {
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h, err := WriteHome()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(append([]string{h}, def...)...), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// configHome is the directory holding vcom/ for reading.
|
||||||
|
func configHome() (string, error) {
|
||||||
|
if d := sys.getenv("XDG_CONFIG_HOME"); filepath.IsAbs(d) {
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
h, err := ReadHome()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(h, ".config"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigFile resolves the config path. explicit is the -config flag. found
|
||||||
|
// reports whether the file exists; when it does not, path is where SetKey
|
||||||
|
// would create it (DefaultConfigFile), or explicit/$VCOM_CONFIG if given.
|
||||||
|
// The working directory is never consulted (see StrayCwdConfig).
|
||||||
|
func ConfigFile(explicit string) (path string, found bool, err error) {
|
||||||
|
for _, p := range []string{explicit, sys.getenv("VCOM_CONFIG")} {
|
||||||
|
if p == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(p)
|
||||||
|
if err != nil {
|
||||||
|
return "", false, err
|
||||||
|
}
|
||||||
|
ok, err := exists(abs)
|
||||||
|
return abs, ok, err
|
||||||
|
}
|
||||||
|
var candidates []string
|
||||||
|
if d, err := configHome(); err == nil {
|
||||||
|
candidates = append(candidates, filepath.Join(d, "vcom", "vcom.toml"))
|
||||||
|
}
|
||||||
|
if h, err := ReadHome(); err == nil {
|
||||||
|
candidates = append(candidates, filepath.Join(h, ".config", "vcom", "vcom.toml"))
|
||||||
|
}
|
||||||
|
if _, sudo := SudoUser(); sudo {
|
||||||
|
if h, err := WriteHome(); err == nil {
|
||||||
|
candidates = append(candidates, filepath.Join(h, ".config", "vcom", "vcom.toml"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range candidates {
|
||||||
|
ok, err := exists(c)
|
||||||
|
if err != nil {
|
||||||
|
return "", false, err
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
return c, true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
def, err := DefaultConfigFile()
|
||||||
|
return def, false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultConfigFile is where a new config file is created: $VCOM_CONFIG if
|
||||||
|
// set (the file every start reads; QA-15), else the XDG file. Under sudo it
|
||||||
|
// is the effective user's, so root does not create files in ~user.
|
||||||
|
func DefaultConfigFile() (string, error) {
|
||||||
|
if p := sys.getenv("VCOM_CONFIG"); p != "" {
|
||||||
|
return filepath.Abs(p)
|
||||||
|
}
|
||||||
|
if _, sudo := SudoUser(); sudo {
|
||||||
|
d, err := xdgWrite("XDG_CONFIG_HOME", ".config")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(d, "vcom", "vcom.toml"), nil
|
||||||
|
}
|
||||||
|
d, err := configHome()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(d, "vcom", "vcom.toml"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StrayCwdConfig returns ./vcom.toml (or ./config/vcom.toml) when it exists:
|
||||||
|
// older versions loaded it; now it is only worth a hint in the log when no
|
||||||
|
// real config was found.
|
||||||
|
func StrayCwdConfig() (string, bool) {
|
||||||
|
wd, err := sys.getwd()
|
||||||
|
if err != nil {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
for _, c := range []string{filepath.Join(wd, "vcom.toml"), filepath.Join(wd, "config", "vcom.toml")} {
|
||||||
|
if ok, _ := exists(c); ok {
|
||||||
|
return c, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// OldSessionFile is the pre-0.3 session location (next to the config), read
|
||||||
|
// once for migration.
|
||||||
|
func OldSessionFile() (string, error) {
|
||||||
|
d, err := configHome()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(d, "vcom", "session.toml"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StateDir is $XDG_STATE_HOME/vcom (effective user). It is not created.
|
||||||
|
func StateDir() (string, error) {
|
||||||
|
d, err := xdgWrite("XDG_STATE_HOME", ".local", "state")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(d, "vcom"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CacheDir is $XDG_CACHE_HOME/vcom (effective user). It is not created.
|
||||||
|
func CacheDir() (string, error) {
|
||||||
|
d, err := xdgWrite("XDG_CACHE_HOME", ".cache")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(d, "vcom"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DataHome is $XDG_DATA_HOME (effective user), e.g. for the trash.
|
||||||
|
func DataHome() (string, error) { return xdgWrite("XDG_DATA_HOME", ".local", "share") }
|
||||||
|
|
||||||
|
// EnsureDir creates d and missing parents with mode 0700.
|
||||||
|
func EnsureDir(d string) error { return os.MkdirAll(d, 0o700) }
|
||||||
|
|
||||||
|
// CreateRunDir sweeps run dirs of dead processes from CacheDir and creates
|
||||||
|
// CacheDir/run-<pid> (0700) for this process. The caller removes it on exit
|
||||||
|
// (RemoveRunDir).
|
||||||
|
func CreateRunDir() (string, error) {
|
||||||
|
cache, err := CacheDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := EnsureDir(cache); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
SweepRunDirs(cache)
|
||||||
|
d := filepath.Join(cache, "run-"+strconv.Itoa(sys.getpid()))
|
||||||
|
if err := os.Mkdir(d, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.Chmod(d, 0o700); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return d, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SweepRunDirs removes cache/run-<pid> directories whose process is gone
|
||||||
|
// (left behind by kill -9 or a crash). It returns what it removed.
|
||||||
|
func SweepRunDirs(cache string) []string {
|
||||||
|
ents, err := os.ReadDir(cache)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var removed []string
|
||||||
|
self := sys.getpid()
|
||||||
|
for _, e := range ents {
|
||||||
|
rest, ok := strings.CutPrefix(e.Name(), "run-")
|
||||||
|
if !ok || !e.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pid, err := strconv.Atoi(rest)
|
||||||
|
if err != nil || pid <= 0 || pid == self || sys.alive(pid) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p := filepath.Join(cache, e.Name())
|
||||||
|
if os.RemoveAll(p) == nil {
|
||||||
|
removed = append(removed, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return removed
|
||||||
|
}
|
||||||
|
|
||||||
|
// RemoveRunDir deletes this process's run dir (teardown).
|
||||||
|
func RemoveRunDir(d string) error {
|
||||||
|
if d == "" || !strings.HasPrefix(filepath.Base(d), "run-") {
|
||||||
|
return fmt.Errorf("refusing to remove %q: not a run dir", d)
|
||||||
|
}
|
||||||
|
return os.RemoveAll(d)
|
||||||
|
}
|
||||||
|
|
||||||
|
func exists(p string) (bool, error) {
|
||||||
|
_, err := os.Stat(p)
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOTDIR) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
182
internal/paths/paths_test.go
Normal file
182
internal/paths/paths_test.go
Normal file
|
|
@ -0,0 +1,182 @@
|
||||||
|
package paths
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fake installs a fake system for one test.
|
||||||
|
func fake(t *testing.T, env map[string]string, euid int, homes map[string]string) {
|
||||||
|
t.Helper()
|
||||||
|
orig := sys
|
||||||
|
t.Cleanup(func() { sys = orig })
|
||||||
|
sys.getenv = func(k string) string { return env[k] }
|
||||||
|
sys.geteuid = func() int { return euid }
|
||||||
|
sys.homeOfUser = func(name string) (string, error) {
|
||||||
|
if h, ok := homes[name]; ok {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
return "", errors.New("no such user")
|
||||||
|
}
|
||||||
|
sys.homeOfUID = func(uid int) (string, error) {
|
||||||
|
if h, ok := homes["uid:"+strconv.Itoa(uid)]; ok {
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
return "", errors.New("no such uid")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func write(t *testing.T, p string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte("[ui]\n"), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigLookupIgnoresCwd(t *testing.T) {
|
||||||
|
home := t.TempDir()
|
||||||
|
cwd := t.TempDir()
|
||||||
|
write(t, filepath.Join(cwd, "vcom.toml"))
|
||||||
|
write(t, filepath.Join(cwd, "config", "vcom.toml"))
|
||||||
|
t.Chdir(cwd)
|
||||||
|
fake(t, map[string]string{"HOME": home}, 1000, nil)
|
||||||
|
|
||||||
|
p, found, err := ConfigFile("")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
t.Fatalf("found %s: the working directory must not be searched", p)
|
||||||
|
}
|
||||||
|
if want := filepath.Join(home, ".config", "vcom", "vcom.toml"); p != want {
|
||||||
|
t.Fatalf("default path %s, want %s", p, want)
|
||||||
|
}
|
||||||
|
if stray, ok := StrayCwdConfig(); !ok || stray != filepath.Join(cwd, "vcom.toml") {
|
||||||
|
t.Fatalf("stray = %q %v", stray, ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The real XDG file is found; explicit and $VCOM_CONFIG win in that order.
|
||||||
|
write(t, filepath.Join(home, ".config", "vcom", "vcom.toml"))
|
||||||
|
if p, found, _ := ConfigFile(""); !found || p != filepath.Join(home, ".config", "vcom", "vcom.toml") {
|
||||||
|
t.Fatalf("home config: %s %v", p, found)
|
||||||
|
}
|
||||||
|
xdg := filepath.Join(home, "xdg")
|
||||||
|
write(t, filepath.Join(xdg, "vcom", "vcom.toml"))
|
||||||
|
env := map[string]string{"HOME": home, "XDG_CONFIG_HOME": xdg}
|
||||||
|
fake(t, env, 1000, nil)
|
||||||
|
if p, _, _ := ConfigFile(""); p != filepath.Join(xdg, "vcom", "vcom.toml") {
|
||||||
|
t.Fatalf("XDG_CONFIG_HOME not preferred: %s", p)
|
||||||
|
}
|
||||||
|
env["VCOM_CONFIG"] = filepath.Join(home, "env.toml")
|
||||||
|
if p, found, _ := ConfigFile(""); found || p != env["VCOM_CONFIG"] {
|
||||||
|
t.Fatalf("VCOM_CONFIG: %s %v", p, found)
|
||||||
|
}
|
||||||
|
if p, _, _ := ConfigFile("rel.toml"); p != filepath.Join(cwd, "rel.toml") {
|
||||||
|
t.Fatalf("explicit relative path: %s", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSudoWritePathsEffectiveUser(t *testing.T) {
|
||||||
|
tmp := t.TempDir()
|
||||||
|
bob, root := filepath.Join(tmp, "bob"), filepath.Join(tmp, "root")
|
||||||
|
write(t, filepath.Join(bob, ".config", "vcom", "vcom.toml"))
|
||||||
|
// sudo -E keeps bob's HOME and XDG variables.
|
||||||
|
env := map[string]string{
|
||||||
|
"HOME": bob,
|
||||||
|
"SUDO_USER": "bob",
|
||||||
|
"XDG_STATE_HOME": filepath.Join(bob, ".local", "state"),
|
||||||
|
"XDG_CACHE_HOME": filepath.Join(bob, ".cache"),
|
||||||
|
"XDG_DATA_HOME": filepath.Join(bob, ".local", "share"),
|
||||||
|
"XDG_CONFIG_HOME": filepath.Join(bob, ".config"),
|
||||||
|
}
|
||||||
|
fake(t, env, 0, map[string]string{"bob": bob, "uid:0": root})
|
||||||
|
|
||||||
|
if p, found, _ := ConfigFile(""); !found || p != filepath.Join(bob, ".config", "vcom", "vcom.toml") {
|
||||||
|
t.Fatalf("config must be read from the invoking user: %s %v", p, found)
|
||||||
|
}
|
||||||
|
if h, _ := ReadHome(); h != bob {
|
||||||
|
t.Fatalf("ReadHome = %s", h)
|
||||||
|
}
|
||||||
|
checks := map[string]func() (string, error){
|
||||||
|
filepath.Join(root, ".local", "state", "vcom"): StateDir,
|
||||||
|
filepath.Join(root, ".cache", "vcom"): CacheDir,
|
||||||
|
filepath.Join(root, ".local", "share"): DataHome,
|
||||||
|
filepath.Join(root, ".config", "vcom", "vcom.toml"): DefaultConfigFile,
|
||||||
|
root: WriteHome,
|
||||||
|
}
|
||||||
|
for want, f := range checks {
|
||||||
|
if got, err := f(); err != nil || got != want {
|
||||||
|
t.Errorf("got %s (%v), want %s", got, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without sudo the XDG variables are honoured.
|
||||||
|
delete(env, "SUDO_USER")
|
||||||
|
fake(t, env, 1000, nil)
|
||||||
|
if d, _ := StateDir(); d != filepath.Join(bob, ".local", "state", "vcom") {
|
||||||
|
t.Fatalf("StateDir = %s", d)
|
||||||
|
}
|
||||||
|
// sudo with SUDO_USER=root (sudo -s from root) is not "sudo".
|
||||||
|
env["SUDO_USER"] = "root"
|
||||||
|
fake(t, env, 0, nil)
|
||||||
|
if _, ok := SudoUser(); ok {
|
||||||
|
t.Fatal("SUDO_USER=root must not count")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRunDirSweepDeadPID(t *testing.T) {
|
||||||
|
cacheHome := t.TempDir()
|
||||||
|
fake(t, map[string]string{"HOME": t.TempDir(), "XDG_CACHE_HOME": cacheHome}, 1000, nil)
|
||||||
|
sys.getpid = func() int { return 4242 }
|
||||||
|
sys.alive = func(pid int) bool { return pid == 222 }
|
||||||
|
cache := filepath.Join(cacheHome, "vcom")
|
||||||
|
for _, d := range []string{"run-111", "run-222", "run-abc", "keep"} {
|
||||||
|
write(t, filepath.Join(cache, d, "junk"))
|
||||||
|
}
|
||||||
|
|
||||||
|
d, err := CreateRunDir()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if d != filepath.Join(cache, "run-4242") {
|
||||||
|
t.Fatalf("run dir %s", d)
|
||||||
|
}
|
||||||
|
if fi, err := os.Stat(d); err != nil || fi.Mode().Perm() != 0o700 {
|
||||||
|
t.Fatalf("run dir mode: %v %v", fi, err)
|
||||||
|
}
|
||||||
|
for name, want := range map[string]bool{"run-111": false, "run-222": true, "run-abc": true, "keep": true} {
|
||||||
|
_, err := os.Stat(filepath.Join(cache, name))
|
||||||
|
if (err == nil) != want {
|
||||||
|
t.Errorf("%s exists=%v, want %v", name, err == nil, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := RemoveRunDir(d); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(d); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("run dir not removed")
|
||||||
|
}
|
||||||
|
if err := RemoveRunDir(cache); err == nil {
|
||||||
|
t.Fatal("RemoveRunDir must refuse a non-run dir")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPidAlive(t *testing.T) {
|
||||||
|
if !pidAlive(os.Getpid()) {
|
||||||
|
t.Fatal("self not alive")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDefaultConfigFileHonoursVCOMConfig(t *testing.T) {
|
||||||
|
home := t.TempDir()
|
||||||
|
fake(t, map[string]string{"HOME": home, "VCOM_CONFIG": filepath.Join(home, "custom", "v.toml")}, 1000, nil)
|
||||||
|
if p, _ := DefaultConfigFile(); p != filepath.Join(home, "custom", "v.toml") {
|
||||||
|
t.Fatalf("DefaultConfigFile = %s (QA-15)", p)
|
||||||
|
}
|
||||||
|
}
|
||||||
284
internal/preview/build.go
Normal file
284
internal/preview/build.go
Normal file
|
|
@ -0,0 +1,284 @@
|
||||||
|
// Package preview builds the content shown for a selected entry (design
|
||||||
|
// §5.4): a pure Build(ctx, req) over vfs — no global state, no Bubble Tea.
|
||||||
|
// Non-regular files are never opened (U-P1-10); external tools run with a
|
||||||
|
// timeout and are killed with their children; text is highlighted by a
|
||||||
|
// chroma formatter that emits foreground SGR only, capped at MaxLines.
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
_ "image/gif" // DecodeConfig formats
|
||||||
|
_ "image/jpeg"
|
||||||
|
_ "image/png"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Kind of a preview.
|
||||||
|
type Kind uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Empty Kind = iota
|
||||||
|
Directory
|
||||||
|
Text
|
||||||
|
Image
|
||||||
|
PDF
|
||||||
|
Audio
|
||||||
|
Video
|
||||||
|
Binary
|
||||||
|
Special
|
||||||
|
Error
|
||||||
|
)
|
||||||
|
|
||||||
|
func (k Kind) String() string {
|
||||||
|
return [...]string{"empty", "directory", "text", "image", "pdf", "audio", "video", "binary", "special", "error"}[k]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Metadata shown next to the preview.
|
||||||
|
type Metadata struct {
|
||||||
|
Path string
|
||||||
|
Label string // KindLabel: "directory", "go", "fifo", ...
|
||||||
|
Size int64
|
||||||
|
Mode fs.FileMode
|
||||||
|
ModTime time.Time
|
||||||
|
LinkTarget string
|
||||||
|
|
||||||
|
ImageFormat string
|
||||||
|
Width, Height int
|
||||||
|
|
||||||
|
Duration, Bitrate, AudioCodec, VideoCodec, SampleRate, Channels, Dimensions string
|
||||||
|
PageCount string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageRef is what imgview needs to draw an image; it decodes the file
|
||||||
|
// itself, off the UI goroutine.
|
||||||
|
type ImageRef struct {
|
||||||
|
Loc vfs.Location
|
||||||
|
Size int64
|
||||||
|
ModTime time.Time
|
||||||
|
Format string
|
||||||
|
Width, Height int
|
||||||
|
// Local is a local file with the image: the file itself for a local FS,
|
||||||
|
// a cached download for a remote one; "" when not available.
|
||||||
|
Local string
|
||||||
|
// TooLarge: a remote image above MaxRemoteImageBytes is not downloaded.
|
||||||
|
TooLarge bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request describes what to preview.
|
||||||
|
type Request struct {
|
||||||
|
Loc vfs.Location
|
||||||
|
Info vfs.FileInfo // Lstat of Loc; zero → Build does the Lstat
|
||||||
|
|
||||||
|
MaxBytes int64 // bytes read for text (default 64 KiB)
|
||||||
|
MaxLines int // text lines kept (default 3000)
|
||||||
|
// HighlightLines: how many of the first lines are highlighted (default
|
||||||
|
// 400 — the chroma lexer costs ~2 ms per 1 KiB); the rest is plain. The
|
||||||
|
// viewer asks for more (up to MaxLines) when the user scrolls.
|
||||||
|
HighlightLines int
|
||||||
|
DirLimit int // directory entries kept (default 80)
|
||||||
|
ShowHidden bool // directory preview
|
||||||
|
Theme string
|
||||||
|
|
||||||
|
Tools *Tools // external utilities; nil → none
|
||||||
|
Images *ImageCache // remote image downloads; nil → no downloads
|
||||||
|
MaxRemoteImageBytes int64 // default 20 MiB
|
||||||
|
}
|
||||||
|
|
||||||
|
// Result of Build.
|
||||||
|
type Result struct {
|
||||||
|
Kind Kind
|
||||||
|
Meta Metadata
|
||||||
|
Lines []string // highlighted (foreground SGR only), one per screen line, no wrapping
|
||||||
|
Plain []string // the same lines without SGR (caret, yank)
|
||||||
|
Dir []vfs.FileInfo
|
||||||
|
Image *ImageRef
|
||||||
|
Truncated bool
|
||||||
|
// Highlighted is the number of leading Lines that carry highlighting.
|
||||||
|
Highlighted int
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
defaultMaxBytes = 64 << 10
|
||||||
|
defaultMaxLines = 3000
|
||||||
|
defaultDirLimit = 80
|
||||||
|
defaultMaxRemote = 20 << 20
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r *Request) defaults() {
|
||||||
|
if r.MaxBytes <= 0 {
|
||||||
|
r.MaxBytes = defaultMaxBytes
|
||||||
|
}
|
||||||
|
if r.MaxLines <= 0 {
|
||||||
|
r.MaxLines = defaultMaxLines
|
||||||
|
}
|
||||||
|
if r.HighlightLines <= 0 {
|
||||||
|
r.HighlightLines = 400
|
||||||
|
}
|
||||||
|
if r.HighlightLines > r.MaxLines {
|
||||||
|
r.HighlightLines = r.MaxLines
|
||||||
|
}
|
||||||
|
if r.DirLimit <= 0 {
|
||||||
|
r.DirLimit = defaultDirLimit
|
||||||
|
}
|
||||||
|
if r.MaxRemoteImageBytes <= 0 {
|
||||||
|
r.MaxRemoteImageBytes = defaultMaxRemote
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build makes the preview. It honours ctx everywhere it waits (reads,
|
||||||
|
// tools, highlighting) and returns Kind=Error with Err on failure.
|
||||||
|
func Build(ctx context.Context, req Request) Result {
|
||||||
|
req.defaults()
|
||||||
|
fsys, p := req.Loc.FS, req.Loc.Path
|
||||||
|
res := Result{Meta: Metadata{Path: p}}
|
||||||
|
fail := func(err error) Result {
|
||||||
|
res.Kind, res.Err = Error, err
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
fi := req.Info
|
||||||
|
if fi.Name == "" {
|
||||||
|
var err error
|
||||||
|
if fi, err = fsys.Lstat(ctx, p); err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Meta.Label = KindLabel(fi)
|
||||||
|
res.Meta.Size, res.Meta.Mode, res.Meta.ModTime = fi.Size, fi.Mode, fi.ModTime
|
||||||
|
eff := fi
|
||||||
|
if fi.IsSymlink() {
|
||||||
|
res.Meta.LinkTarget, _ = fsys.ReadLink(ctx, p)
|
||||||
|
if fi.Target == nil {
|
||||||
|
res.Kind = Special
|
||||||
|
if fi.LinkErr != nil {
|
||||||
|
res.Err = fmt.Errorf("broken symlink: %w", fi.LinkErr)
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
eff = *fi.Target
|
||||||
|
}
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case eff.IsDir():
|
||||||
|
return buildDir(ctx, req, res)
|
||||||
|
case !eff.Mode.IsRegular():
|
||||||
|
res.Kind = Special // FIFO, socket, device: never opened (U-P1-10)
|
||||||
|
return res
|
||||||
|
case eff.Size == 0:
|
||||||
|
res.Kind = Empty
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
head, truncated, err := readHead(ctx, fsys, p, req.MaxBytes)
|
||||||
|
if err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
if cfg, format, err := image.DecodeConfig(bytes.NewReader(head)); err == nil {
|
||||||
|
return buildImage(ctx, req, res, eff, format, cfg)
|
||||||
|
}
|
||||||
|
ext := strings.ToLower(path.Ext(p))
|
||||||
|
switch {
|
||||||
|
case ext == ".pdf":
|
||||||
|
return buildPDF(ctx, req, res)
|
||||||
|
case audioExts[ext]:
|
||||||
|
return buildMedia(ctx, req, res, Audio)
|
||||||
|
case videoExts[ext]:
|
||||||
|
return buildMedia(ctx, req, res, Video)
|
||||||
|
}
|
||||||
|
if isBinary(head) {
|
||||||
|
res.Kind = Binary
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
res.Kind, res.Truncated = Text, truncated
|
||||||
|
return highlightInto(ctx, req, res, path.Base(p), string(head))
|
||||||
|
}
|
||||||
|
|
||||||
|
// readHead reads at most max bytes (and reports whether there was more).
|
||||||
|
func readHead(ctx context.Context, fsys vfs.FS, p string, max int64) ([]byte, bool, error) {
|
||||||
|
f, err := fsys.Open(ctx, p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
stop := context.AfterFunc(ctx, func() { f.Close() })
|
||||||
|
defer stop()
|
||||||
|
buf := make([]byte, max+1)
|
||||||
|
n, err := io.ReadFull(f, buf)
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, false, ctx.Err()
|
||||||
|
}
|
||||||
|
if err != nil && err != io.EOF && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
if int64(n) > max {
|
||||||
|
return buf[:max], true, nil
|
||||||
|
}
|
||||||
|
return buf[:n], false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// isBinary: a NUL byte or mostly invalid UTF-8 in the sample.
|
||||||
|
func isBinary(b []byte) bool {
|
||||||
|
if bytes.IndexByte(b, 0) >= 0 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if len(b) > 4 {
|
||||||
|
b = b[:len(b)-4] // a rune may be cut at the end of the sample
|
||||||
|
}
|
||||||
|
bad := 0
|
||||||
|
for len(b) > 0 {
|
||||||
|
r, n := utf8.DecodeRune(b)
|
||||||
|
if r == utf8.RuneError && n == 1 {
|
||||||
|
bad++
|
||||||
|
}
|
||||||
|
b = b[n:]
|
||||||
|
}
|
||||||
|
return bad > 8
|
||||||
|
}
|
||||||
|
|
||||||
|
// KindLabel names an entry for the metadata line: "directory", "symlink",
|
||||||
|
// "fifo", "socket", "device", the lower-case extension ("go", "tar.gz"), or
|
||||||
|
// "file" (U-P2: the old label was inverted).
|
||||||
|
func KindLabel(fi vfs.FileInfo) string {
|
||||||
|
m := fi.Mode
|
||||||
|
switch {
|
||||||
|
case m.IsDir():
|
||||||
|
return "directory"
|
||||||
|
case m&fs.ModeSymlink != 0:
|
||||||
|
return "symlink"
|
||||||
|
case m&fs.ModeNamedPipe != 0:
|
||||||
|
return "fifo"
|
||||||
|
case m&fs.ModeSocket != 0:
|
||||||
|
return "socket"
|
||||||
|
case m&fs.ModeDevice != 0:
|
||||||
|
return "device"
|
||||||
|
}
|
||||||
|
name := strings.ToLower(fi.Name)
|
||||||
|
if strings.HasSuffix(name, ".tar.gz") && len(name) > 7 {
|
||||||
|
return "tar.gz"
|
||||||
|
}
|
||||||
|
ext := path.Ext(name)
|
||||||
|
if ext == "" || ext == name {
|
||||||
|
return "file"
|
||||||
|
}
|
||||||
|
return ext[1:]
|
||||||
|
}
|
||||||
|
|
||||||
|
var audioExts = map[string]bool{".mp3": true, ".flac": true, ".wav": true, ".ogg": true, ".m4a": true,
|
||||||
|
".aac": true, ".opus": true, ".wma": true}
|
||||||
|
|
||||||
|
var videoExts = map[string]bool{".mp4": true, ".mkv": true, ".webm": true, ".avi": true, ".mov": true,
|
||||||
|
".wmv": true, ".flv": true, ".m4v": true}
|
||||||
229
internal/preview/cache.go
Normal file
229
internal/preview/cache.go
Normal file
|
|
@ -0,0 +1,229 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"container/list"
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ImageCache keeps downloaded remote images in a local directory, keyed by
|
||||||
|
// (volume, path, size, mtime), evicting least recently used files above a
|
||||||
|
// total size budget (default 200 MiB).
|
||||||
|
type ImageCache struct {
|
||||||
|
dir string
|
||||||
|
max int64
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
lru *list.List // of *cached, front = most recent
|
||||||
|
byKey map[string]*list.Element
|
||||||
|
total int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type cached struct {
|
||||||
|
key string
|
||||||
|
path string
|
||||||
|
size int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImageCache uses dir (created 0700). Files already there are kept up to
|
||||||
|
// the budget (oldest removed first), so the cache survives restarts.
|
||||||
|
func NewImageCache(dir string, maxBytes int64) (*ImageCache, error) {
|
||||||
|
if maxBytes <= 0 {
|
||||||
|
maxBytes = 200 << 20
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c := &ImageCache{dir: dir, max: maxBytes, lru: list.New(), byKey: map[string]*list.Element{}}
|
||||||
|
ents, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
type old struct {
|
||||||
|
name string
|
||||||
|
size int64
|
||||||
|
mt time.Time
|
||||||
|
}
|
||||||
|
var files []old
|
||||||
|
for _, e := range ents {
|
||||||
|
fi, err := e.Info()
|
||||||
|
if err != nil || !fi.Mode().IsRegular() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(e.Name(), ".tmp-") { // an interrupted download
|
||||||
|
_ = os.Remove(filepath.Join(dir, e.Name()))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
files = append(files, old{e.Name(), fi.Size(), fi.ModTime()})
|
||||||
|
}
|
||||||
|
sort.Slice(files, func(i, j int) bool { return files[i].mt.After(files[j].mt) })
|
||||||
|
for _, f := range files {
|
||||||
|
c.add(strings.TrimSuffix(f.name, path.Ext(f.name)), filepath.Join(dir, f.name), f.size)
|
||||||
|
}
|
||||||
|
c.evict()
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func cacheKey(vol vfs.VolumeID, p string, size int64, mt time.Time) string {
|
||||||
|
h := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%s\x00%d\x00%d", vol, p, size, mt.UnixNano())))
|
||||||
|
return hex.EncodeToString(h[:16])
|
||||||
|
}
|
||||||
|
|
||||||
|
// add appends at the back (least recent): used while loading.
|
||||||
|
func (c *ImageCache) add(key, p string, size int64) {
|
||||||
|
c.byKey[key] = c.lru.PushBack(&cached{key: key, path: p, size: size})
|
||||||
|
c.total += size
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ImageCache) evict() {
|
||||||
|
for c.total > c.max && c.lru.Len() > 1 {
|
||||||
|
e := c.lru.Back()
|
||||||
|
it := e.Value.(*cached)
|
||||||
|
c.lru.Remove(e)
|
||||||
|
delete(c.byKey, it.key)
|
||||||
|
c.total -= it.size
|
||||||
|
_ = os.Remove(it.path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch returns a local copy of p on fsys, downloading it if needed.
|
||||||
|
func (c *ImageCache) Fetch(ctx context.Context, fsys vfs.FS, p string, size int64, mt time.Time) (string, error) {
|
||||||
|
key := cacheKey(fsys.Volume(), p, size, mt)
|
||||||
|
c.mu.Lock()
|
||||||
|
if e, ok := c.byKey[key]; ok {
|
||||||
|
c.lru.MoveToFront(e)
|
||||||
|
lp := e.Value.(*cached).path
|
||||||
|
c.mu.Unlock()
|
||||||
|
return lp, nil
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
|
||||||
|
src, err := fsys.Open(ctx, p)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer src.Close()
|
||||||
|
tmp, err := os.CreateTemp(c.dir, ".tmp-*")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
n, err := io.Copy(tmp, &ctxRead{ctx: ctx, r: io.LimitReader(src, size+1)})
|
||||||
|
if cerr := tmp.Close(); err == nil {
|
||||||
|
err = cerr
|
||||||
|
}
|
||||||
|
if err == nil && n != size {
|
||||||
|
err = fmt.Errorf("%s changed while downloading (%d of %d bytes)", p, n, size)
|
||||||
|
}
|
||||||
|
final := filepath.Join(c.dir, key+strings.ToLower(path.Ext(p)))
|
||||||
|
if err == nil {
|
||||||
|
err = os.Rename(tmp.Name(), final)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
_ = os.Remove(tmp.Name())
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if _, ok := c.byKey[key]; !ok {
|
||||||
|
c.byKey[key] = c.lru.PushFront(&cached{key: key, path: final, size: n})
|
||||||
|
c.total += n
|
||||||
|
c.evict()
|
||||||
|
}
|
||||||
|
return final, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type ctxRead struct {
|
||||||
|
ctx context.Context
|
||||||
|
r io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ctxRead) Read(p []byte) (int, error) {
|
||||||
|
if err := c.ctx.Err(); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return c.r.Read(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache keeps the last results (default 32) by (volume, path, size, mtime,
|
||||||
|
// theme, limits), so moving the cursor back and forth does not rebuild.
|
||||||
|
type Cache struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
max int
|
||||||
|
lru *list.List
|
||||||
|
byKey map[resultKey]*list.Element
|
||||||
|
}
|
||||||
|
|
||||||
|
type resultKey struct {
|
||||||
|
vol vfs.VolumeID
|
||||||
|
path string
|
||||||
|
size int64
|
||||||
|
mtime int64
|
||||||
|
theme string
|
||||||
|
maxBytes int64
|
||||||
|
maxLines, dirLimit int
|
||||||
|
highlight int
|
||||||
|
hidden bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type resultEntry struct {
|
||||||
|
key resultKey
|
||||||
|
res Result
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewCache returns a result cache with room for max results (≤ 0 → 32).
|
||||||
|
func NewCache(max int) *Cache {
|
||||||
|
if max <= 0 {
|
||||||
|
max = 32
|
||||||
|
}
|
||||||
|
return &Cache{max: max, lru: list.New(), byKey: map[resultKey]*list.Element{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build returns a cached result or builds and caches it. Errors and
|
||||||
|
// cancelled builds are not cached.
|
||||||
|
func (c *Cache) Build(ctx context.Context, req Request) Result {
|
||||||
|
req.defaults()
|
||||||
|
if req.Info.Name == "" {
|
||||||
|
fi, err := req.Loc.FS.Lstat(ctx, req.Loc.Path)
|
||||||
|
if err != nil {
|
||||||
|
return Result{Kind: Error, Err: err, Meta: Metadata{Path: req.Loc.Path}}
|
||||||
|
}
|
||||||
|
req.Info = fi
|
||||||
|
}
|
||||||
|
k := resultKey{req.Loc.FS.Volume(), req.Loc.Path, req.Info.Size, req.Info.ModTime.UnixNano(), req.Theme,
|
||||||
|
req.MaxBytes, req.MaxLines, req.DirLimit, req.HighlightLines, req.ShowHidden}
|
||||||
|
c.mu.Lock()
|
||||||
|
if e, ok := c.byKey[k]; ok {
|
||||||
|
c.lru.MoveToFront(e)
|
||||||
|
r := e.Value.(*resultEntry).res
|
||||||
|
c.mu.Unlock()
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
c.mu.Unlock()
|
||||||
|
r := Build(ctx, req)
|
||||||
|
if r.Err != nil || r.Kind == Error {
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if _, ok := c.byKey[k]; !ok {
|
||||||
|
c.byKey[k] = c.lru.PushFront(&resultEntry{key: k, res: r})
|
||||||
|
for c.lru.Len() > c.max {
|
||||||
|
e := c.lru.Back()
|
||||||
|
c.lru.Remove(e)
|
||||||
|
delete(c.byKey, e.Value.(*resultEntry).key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
39
internal/preview/dir.go
Normal file
39
internal/preview/dir.go
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// buildDir lists a directory, keeping at most DirLimit entries (dirs first,
|
||||||
|
// then by name). Hidden entries are dropped unless ShowHidden.
|
||||||
|
func buildDir(ctx context.Context, req Request, res Result) Result {
|
||||||
|
ents, err := req.Loc.FS.ReadDir(ctx, req.Loc.Path)
|
||||||
|
if err != nil {
|
||||||
|
res.Kind, res.Err = Error, err
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
kept := ents[:0]
|
||||||
|
for _, e := range ents {
|
||||||
|
if req.ShowHidden || !strings.HasPrefix(e.Name, ".") {
|
||||||
|
kept = append(kept, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Slice(kept, func(i, j int) bool {
|
||||||
|
di, dj := kept[i].NavigableDir(), kept[j].NavigableDir()
|
||||||
|
if di != dj {
|
||||||
|
return di
|
||||||
|
}
|
||||||
|
return strings.ToLower(kept[i].Name) < strings.ToLower(kept[j].Name)
|
||||||
|
})
|
||||||
|
res.Kind = Directory
|
||||||
|
if len(kept) > req.DirLimit {
|
||||||
|
kept, res.Truncated = kept[:req.DirLimit], true
|
||||||
|
}
|
||||||
|
res.Dir = make([]vfs.FileInfo, len(kept)) // do not pin the full listing
|
||||||
|
copy(res.Dir, kept)
|
||||||
|
return res
|
||||||
|
}
|
||||||
109
internal/preview/highlight.go
Normal file
109
internal/preview/highlight.go
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/alecthomas/chroma/v2"
|
||||||
|
"github.com/alecthomas/chroma/v2/lexers"
|
||||||
|
"github.com/alecthomas/chroma/v2/styles"
|
||||||
|
|
||||||
|
"vcom/internal/theme"
|
||||||
|
)
|
||||||
|
|
||||||
|
// highlightInto fills Lines/Plain for text. The formatter writes SGR for
|
||||||
|
// foreground colour, bold, italic and underline only — never a background
|
||||||
|
// (no post-processing regexps). ctx is checked every 256 tokens.
|
||||||
|
func highlightInto(ctx context.Context, req Request, res Result, name, src string) Result {
|
||||||
|
plain, cut := textLines(src, req.MaxLines)
|
||||||
|
res.Plain = plain
|
||||||
|
res.Truncated = res.Truncated || cut
|
||||||
|
n := min(req.HighlightLines, len(plain))
|
||||||
|
lines, err := Highlight(ctx, name, strings.Join(plain[:n], "\n"), req.Theme)
|
||||||
|
if err != nil {
|
||||||
|
res.Kind, res.Err = Error, err
|
||||||
|
res.Lines, res.Plain = nil, nil
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
if len(lines) != n {
|
||||||
|
lines, n = plain[:n], 0 // a lexer that changed the text: show it plain
|
||||||
|
}
|
||||||
|
res.Lines = make([]string, 0, len(plain))
|
||||||
|
res.Lines = append(append(res.Lines, lines...), plain[n:]...)
|
||||||
|
res.Highlighted = n
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// Highlight returns src (already normalised: LF, no tabs) as highlighted
|
||||||
|
// lines for the given vcom theme.
|
||||||
|
func Highlight(ctx context.Context, name, src, themeName string) ([]string, error) {
|
||||||
|
lexer := lexers.Match(name)
|
||||||
|
if lexer == nil {
|
||||||
|
lexer = lexers.Analyse(src)
|
||||||
|
}
|
||||||
|
if lexer == nil {
|
||||||
|
return strings.Split(src, "\n"), nil
|
||||||
|
}
|
||||||
|
lexer = chroma.Coalesce(lexer)
|
||||||
|
style := styles.Get(theme.ChromaStyle(themeName))
|
||||||
|
it, err := lexer.Tokenise(nil, src)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sgr := map[chroma.TokenType]string{}
|
||||||
|
var lines []string
|
||||||
|
var cur strings.Builder
|
||||||
|
n := 0
|
||||||
|
for tok := it(); tok != chroma.EOF; tok = it() {
|
||||||
|
if n++; n&255 == 0 {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
code, ok := sgr[tok.Type]
|
||||||
|
if !ok {
|
||||||
|
code = sgrFor(style.Get(tok.Type))
|
||||||
|
sgr[tok.Type] = code
|
||||||
|
}
|
||||||
|
for i, seg := range strings.Split(tok.Value, "\n") {
|
||||||
|
if i > 0 {
|
||||||
|
lines = append(lines, cur.String())
|
||||||
|
cur.Reset()
|
||||||
|
}
|
||||||
|
if seg == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if code != "" {
|
||||||
|
cur.WriteString(code)
|
||||||
|
cur.WriteString(seg)
|
||||||
|
cur.WriteString("\x1b[0m")
|
||||||
|
} else {
|
||||||
|
cur.WriteString(seg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines = append(lines, cur.String())
|
||||||
|
return lines, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sgrFor renders a style entry as a foreground-only SGR sequence.
|
||||||
|
func sgrFor(e chroma.StyleEntry) string {
|
||||||
|
var parts []string
|
||||||
|
if e.Bold == chroma.Yes {
|
||||||
|
parts = append(parts, "1")
|
||||||
|
}
|
||||||
|
if e.Italic == chroma.Yes {
|
||||||
|
parts = append(parts, "3")
|
||||||
|
}
|
||||||
|
if e.Underline == chroma.Yes {
|
||||||
|
parts = append(parts, "4")
|
||||||
|
}
|
||||||
|
if e.Colour.IsSet() {
|
||||||
|
parts = append(parts, fmt.Sprintf("38;2;%d;%d;%d", e.Colour.Red(), e.Colour.Green(), e.Colour.Blue()))
|
||||||
|
}
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return "\x1b[" + strings.Join(parts, ";") + "m"
|
||||||
|
}
|
||||||
30
internal/preview/image.go
Normal file
30
internal/preview/image.go
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"image"
|
||||||
|
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// buildImage reports format and size; imgview decodes later. A remote image
|
||||||
|
// is downloaded to the cache only up to MaxRemoteImageBytes (N-P1-16).
|
||||||
|
func buildImage(ctx context.Context, req Request, res Result, fi vfs.FileInfo, format string, cfg image.Config) Result {
|
||||||
|
res.Kind = Image
|
||||||
|
res.Meta.ImageFormat, res.Meta.Width, res.Meta.Height = format, cfg.Width, cfg.Height
|
||||||
|
ref := &ImageRef{Loc: req.Loc, Size: fi.Size, ModTime: fi.ModTime, Format: format, Width: cfg.Width, Height: cfg.Height}
|
||||||
|
res.Image = ref
|
||||||
|
switch {
|
||||||
|
case req.Loc.FS.Kind() == vfs.KindLocal:
|
||||||
|
ref.Local = req.Loc.Path
|
||||||
|
case fi.Size > req.MaxRemoteImageBytes:
|
||||||
|
ref.TooLarge = true
|
||||||
|
case req.Images != nil:
|
||||||
|
p, err := req.Images.Fetch(ctx, req.Loc.FS, req.Loc.Path, fi.Size, fi.ModTime)
|
||||||
|
if err != nil {
|
||||||
|
res.Err = err
|
||||||
|
}
|
||||||
|
ref.Local = p
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
150
internal/preview/media.go
Normal file
150
internal/preview/media.go
Normal file
|
|
@ -0,0 +1,150 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
)
|
||||||
|
|
||||||
|
// localPath returns the path tools can read, or "" for a non-local FS.
|
||||||
|
func localPath(req Request) string {
|
||||||
|
if req.Loc.FS.Kind() == vfs.KindLocal {
|
||||||
|
return req.Loc.Path
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func message(res Result, k Kind, lines ...string) Result {
|
||||||
|
res.Kind, res.Lines, res.Plain = k, lines, lines
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildPDF: the text of the first 3 pages via pdftotext, page count via
|
||||||
|
// pdfinfo.
|
||||||
|
func buildPDF(ctx context.Context, req Request, res Result) Result {
|
||||||
|
lp := localPath(req)
|
||||||
|
switch {
|
||||||
|
case lp == "":
|
||||||
|
return message(res, PDF, "PDF on a remote file system: text preview is not available.")
|
||||||
|
case req.Tools == nil || req.Tools.PdfToText == "":
|
||||||
|
return message(res, PDF, "PDF file. Install poppler-utils (pdftotext) for a text preview.")
|
||||||
|
}
|
||||||
|
out, err := req.Tools.run(ctx, req.MaxBytes, req.Tools.PdfToText, "-l", "3", "-layout", "-nopgbrk", lp, "-")
|
||||||
|
if err != nil {
|
||||||
|
res.Kind, res.Err = Error, err
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
if req.Tools.PdfInfo != "" {
|
||||||
|
if info, err := req.Tools.run(ctx, 64<<10, req.Tools.PdfInfo, lp); err == nil {
|
||||||
|
for _, line := range strings.Split(string(info), "\n") {
|
||||||
|
if v, ok := strings.CutPrefix(line, "Pages:"); ok {
|
||||||
|
res.Meta.PageCount = strings.TrimSpace(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Kind = PDF
|
||||||
|
res.Plain, res.Truncated = textLines(string(out), req.MaxLines)
|
||||||
|
res.Lines = res.Plain
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildMedia: duration, bitrate, codecs via ffprobe.
|
||||||
|
func buildMedia(ctx context.Context, req Request, res Result, k Kind) Result {
|
||||||
|
lp := localPath(req)
|
||||||
|
switch {
|
||||||
|
case lp == "":
|
||||||
|
return message(res, k, "Media file on a remote file system: metadata is not available.")
|
||||||
|
case req.Tools == nil || req.Tools.FFProbe == "":
|
||||||
|
return message(res, k, "Media file. Install ffmpeg (ffprobe) for metadata.")
|
||||||
|
}
|
||||||
|
out, err := req.Tools.run(ctx, 1<<20, req.Tools.FFProbe, "-v", "quiet", "-print_format", "json",
|
||||||
|
"-show_format", "-show_streams", lp)
|
||||||
|
if err != nil {
|
||||||
|
res.Kind, res.Err = Error, err
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
var info struct {
|
||||||
|
Format struct {
|
||||||
|
Duration string `json:"duration"`
|
||||||
|
Bitrate string `json:"bit_rate"`
|
||||||
|
} `json:"format"`
|
||||||
|
Streams []struct {
|
||||||
|
CodecType string `json:"codec_type"`
|
||||||
|
CodecName string `json:"codec_name"`
|
||||||
|
SampleRate string `json:"sample_rate"`
|
||||||
|
Channels int `json:"channels"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
} `json:"streams"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(out, &info); err != nil {
|
||||||
|
res.Kind, res.Err = Error, fmt.Errorf("ffprobe output: %w", err)
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
m := &res.Meta
|
||||||
|
if secs, err := strconv.ParseFloat(info.Format.Duration, 64); err == nil {
|
||||||
|
s := int(secs)
|
||||||
|
if s >= 3600 {
|
||||||
|
m.Duration = fmt.Sprintf("%d:%02d:%02d", s/3600, s%3600/60, s%60)
|
||||||
|
} else {
|
||||||
|
m.Duration = fmt.Sprintf("%d:%02d", s/60, s%60)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bps, err := strconv.ParseInt(info.Format.Bitrate, 10, 64); err == nil {
|
||||||
|
m.Bitrate = fmt.Sprintf("%d kbps", bps/1000)
|
||||||
|
}
|
||||||
|
for _, st := range info.Streams {
|
||||||
|
switch st.CodecType {
|
||||||
|
case "video":
|
||||||
|
if m.VideoCodec == "" {
|
||||||
|
m.VideoCodec = st.CodecName
|
||||||
|
if st.Width > 0 {
|
||||||
|
m.Dimensions = fmt.Sprintf("%dx%d", st.Width, st.Height)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case "audio":
|
||||||
|
if m.AudioCodec == "" {
|
||||||
|
m.AudioCodec = st.CodecName
|
||||||
|
if st.SampleRate != "" {
|
||||||
|
m.SampleRate = st.SampleRate + " Hz"
|
||||||
|
}
|
||||||
|
m.Channels = channels(st.Channels)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var lines []string
|
||||||
|
add := func(label, v string) {
|
||||||
|
if v != "" {
|
||||||
|
lines = append(lines, fmt.Sprintf("%-11s %s", label+":", v))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
add("Duration", m.Duration)
|
||||||
|
add("Bitrate", m.Bitrate)
|
||||||
|
add("Video", m.VideoCodec)
|
||||||
|
add("Resolution", m.Dimensions)
|
||||||
|
add("Audio", m.AudioCodec)
|
||||||
|
add("Rate", m.SampleRate)
|
||||||
|
add("Channels", m.Channels)
|
||||||
|
return message(res, k, lines...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func channels(n int) string {
|
||||||
|
switch n {
|
||||||
|
case 0:
|
||||||
|
return ""
|
||||||
|
case 1:
|
||||||
|
return "mono"
|
||||||
|
case 2:
|
||||||
|
return "stereo"
|
||||||
|
case 6:
|
||||||
|
return "5.1"
|
||||||
|
case 8:
|
||||||
|
return "7.1"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d ch", n)
|
||||||
|
}
|
||||||
BIN
internal/preview/preview.test
Executable file
BIN
internal/preview/preview.test
Executable file
Binary file not shown.
387
internal/preview/preview_test.go
Normal file
387
internal/preview/preview_test.go
Normal file
|
|
@ -0,0 +1,387 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/color"
|
||||||
|
"image/png"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/fstree"
|
||||||
|
"vcom/internal/theme"
|
||||||
|
"vcom/internal/vfs"
|
||||||
|
"vcom/internal/vfs/localfs"
|
||||||
|
"vcom/internal/vfs/vfstest"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bg = context.Background()
|
||||||
|
local = localfs.New()
|
||||||
|
)
|
||||||
|
|
||||||
|
func at(p string) vfs.Location { return vfs.Location{FS: local, Path: p} }
|
||||||
|
|
||||||
|
func pngBytes(t testing.TB, w, h int) []byte {
|
||||||
|
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||||
|
img.Set(0, 0, color.RGBA{255, 0, 0, 255})
|
||||||
|
var b bytes.Buffer
|
||||||
|
if err := png.Encode(&b, img); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return b.Bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFifoNotRead(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
fstree.Build(t, dir, fstree.Spec{fstree.FIFO("pipe"), fstree.Symlink("ln", "pipe")})
|
||||||
|
for _, name := range []string{"pipe", "ln"} {
|
||||||
|
t0 := time.Now()
|
||||||
|
res := Build(bg, Request{Loc: at(filepath.Join(dir, name))})
|
||||||
|
if el := time.Since(t0); el > 50*time.Millisecond {
|
||||||
|
t.Fatalf("%s: took %v (U-P1-10: a FIFO must not be opened)", name, el)
|
||||||
|
}
|
||||||
|
if res.Kind != Special || res.Err != nil {
|
||||||
|
t.Fatalf("%s: %+v", name, res)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if res := Build(bg, Request{Loc: at("/dev/zero")}); res.Kind != Special {
|
||||||
|
t.Fatalf("/dev/zero: %v", res.Kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeTool writes an executable shell script.
|
||||||
|
func fakeTool(t *testing.T, body string) string {
|
||||||
|
p := filepath.Join(t.TempDir(), "tool")
|
||||||
|
if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestToolTimeout(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
pdf := filepath.Join(dir, "doc.pdf")
|
||||||
|
_ = os.WriteFile(pdf, []byte("%PDF-1.4 not really"), 0o644)
|
||||||
|
// The script's child (sleep) keeps stdout open: only a group kill ends it.
|
||||||
|
tools := &Tools{PdfToText: fakeTool(t, "sleep 10 & wait"), Timeout: 3 * time.Second}
|
||||||
|
t0 := time.Now()
|
||||||
|
res := Build(bg, Request{Loc: at(pdf), Tools: tools})
|
||||||
|
el := time.Since(t0)
|
||||||
|
if el > 3500*time.Millisecond {
|
||||||
|
t.Fatalf("returned after %v", el)
|
||||||
|
}
|
||||||
|
if res.Kind != Error || !errors.Is(res.Err, ErrToolTimeout) {
|
||||||
|
t.Fatalf("%+v", res)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A working tool: output is used and capped.
|
||||||
|
tools = &Tools{PdfToText: fakeTool(t, `yes "page text" | head -c 100000`), Timeout: 3 * time.Second}
|
||||||
|
res = Build(bg, Request{Loc: at(pdf), Tools: tools, MaxBytes: 1000})
|
||||||
|
if res.Kind != PDF || len(strings.Join(res.Plain, "\n")) > 1000 || res.Plain[0] != "page text" {
|
||||||
|
t.Fatalf("pdf %v %d lines err=%v", res.Kind, len(res.Plain), res.Err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildCancelled(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
fstree.Build(t, dir, fstree.Spec{fstree.File("a.go", "package a\n")})
|
||||||
|
ctx, cancel := context.WithCancel(bg)
|
||||||
|
cancel()
|
||||||
|
res := Build(ctx, Request{Loc: at(filepath.Join(dir, "a.go"))})
|
||||||
|
if res.Kind != Error || !errors.Is(res.Err, context.Canceled) {
|
||||||
|
t.Fatalf("%+v", res)
|
||||||
|
}
|
||||||
|
// Cancel during a slow read.
|
||||||
|
ctx, cancel = context.WithCancel(bg)
|
||||||
|
slow := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
|
||||||
|
if op == vfstest.OpRead {
|
||||||
|
cancel()
|
||||||
|
time.Sleep(10 * time.Millisecond)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}}
|
||||||
|
res = Build(ctx, Request{Loc: vfs.Location{FS: slow, Path: filepath.Join(dir, "a.go")}})
|
||||||
|
if !errors.Is(res.Err, context.Canceled) {
|
||||||
|
t.Fatalf("mid-read: %+v", res)
|
||||||
|
}
|
||||||
|
// Cancel during highlighting of a big file.
|
||||||
|
src := strings.Repeat("func f() { x := 1; _ = x }\n", 3000)
|
||||||
|
ctx, cancel = context.WithCancel(bg)
|
||||||
|
time.AfterFunc(time.Millisecond, cancel)
|
||||||
|
if _, err := Highlight(ctx, "big.go", src, "nord"); err != nil && !errors.Is(err, context.Canceled) {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHighlightNoBackgroundSGR(t *testing.T) {
|
||||||
|
src := "package main\n\n// comment\nfunc main() {\n\tprintln(\"hi\", 42)\n}\n"
|
||||||
|
plain, _ := textLines(src, 100)
|
||||||
|
for _, th := range theme.Names() {
|
||||||
|
lines, err := Highlight(bg, "main.go", strings.Join(plain, "\n"), th)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
joined := strings.Join(lines, "\n")
|
||||||
|
if !strings.Contains(joined, "\x1b[") {
|
||||||
|
t.Fatalf("%s: nothing highlighted", th)
|
||||||
|
}
|
||||||
|
for _, seq := range strings.Split(joined, "\x1b[")[1:] {
|
||||||
|
params := strings.Split(seq[:strings.IndexByte(seq, 'm')], ";")
|
||||||
|
for i := 0; i < len(params); i++ {
|
||||||
|
switch p := params[i]; {
|
||||||
|
case p == "38" && i+1 < len(params) && params[i+1] == "2":
|
||||||
|
i += 4 // 38;2;r;g;b
|
||||||
|
case p == "38":
|
||||||
|
i += 2 // 38;5;n
|
||||||
|
case p == "48" || p == "49" || (len(p) == 2 && p[0] == '4') || (len(p) == 3 && p[:2] == "10"):
|
||||||
|
t.Fatalf("%s: background SGR %q", th, params)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(lines) != len(plain) {
|
||||||
|
t.Fatalf("%s: %d lines for %d", th, len(lines), len(plain))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Lines and Plain match line by line.
|
||||||
|
dir := t.TempDir()
|
||||||
|
fstree.Build(t, dir, fstree.Spec{fstree.File("m.go", src)})
|
||||||
|
res := Build(bg, Request{Loc: at(filepath.Join(dir, "m.go")), Theme: "dracula"})
|
||||||
|
if res.Kind != Text || len(res.Lines) != len(res.Plain) || res.Plain[4] != " println(\"hi\", 42)" {
|
||||||
|
t.Fatalf("%+v", res.Plain)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func goSource(tb testing.TB) string {
|
||||||
|
b, err := os.ReadFile("highlight.go")
|
||||||
|
if err != nil {
|
||||||
|
tb.Fatal(err)
|
||||||
|
}
|
||||||
|
var s strings.Builder
|
||||||
|
for s.Len() < 64<<10 {
|
||||||
|
s.Write(b)
|
||||||
|
}
|
||||||
|
return s.String()[:64<<10]
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkPreviewGo64K(b *testing.B) {
|
||||||
|
dir := b.TempDir()
|
||||||
|
p := filepath.Join(dir, "big.go")
|
||||||
|
_ = os.WriteFile(p, []byte(goSource(b)), 0o644)
|
||||||
|
b.ResetTimer()
|
||||||
|
for range b.N {
|
||||||
|
if res := Build(bg, Request{Loc: at(p), Theme: "github-dark"}); res.Kind != Text {
|
||||||
|
b.Fatal(res.Kind)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A loose gate for the benchmark (target ≤ 40 ms, measured ~20 ms; was
|
||||||
|
// 190 ms). The margin covers -race (≈ ×8).
|
||||||
|
func TestPreviewGo64KFast(t *testing.T) {
|
||||||
|
if testing.Short() {
|
||||||
|
t.Skip()
|
||||||
|
}
|
||||||
|
r := testing.Benchmark(BenchmarkPreviewGo64K)
|
||||||
|
if per := time.Duration(r.NsPerOp()); per > 400*time.Millisecond {
|
||||||
|
t.Fatalf("Build on 64 KiB of Go: %v per op", per)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// remote makes a local FS look remote (no tools, no direct image path).
|
||||||
|
type remote struct{ vfs.FS }
|
||||||
|
|
||||||
|
func (remote) Kind() vfs.Kind { return vfs.KindSFTP }
|
||||||
|
func (remote) Volume() vfs.VolumeID { return "ssh:test" }
|
||||||
|
|
||||||
|
func TestRemoteImageSizeLimit(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
small := filepath.Join(dir, "small.png")
|
||||||
|
_ = os.WriteFile(small, pngBytes(t, 40, 30), 0o644)
|
||||||
|
big := filepath.Join(dir, "big.png")
|
||||||
|
data := pngBytes(t, 40, 30)
|
||||||
|
_ = os.WriteFile(big, append(data, make([]byte, 50000)...), 0o644) // decodable header, large file
|
||||||
|
cacheDir := filepath.Join(t.TempDir(), "img")
|
||||||
|
cache, err := NewImageCache(cacheDir, 0)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
opens := 0
|
||||||
|
rfs := remote{&vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
|
||||||
|
if op == vfstest.OpOpen {
|
||||||
|
opens++
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}}}
|
||||||
|
res := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: big}, Images: cache, MaxRemoteImageBytes: 10000})
|
||||||
|
if res.Kind != Image || res.Image == nil || !res.Image.TooLarge || res.Image.Local != "" {
|
||||||
|
t.Fatalf("big: %+v", res.Image)
|
||||||
|
}
|
||||||
|
if ents, _ := os.ReadDir(cacheDir); len(ents) != 0 {
|
||||||
|
t.Fatal("a too large remote image was downloaded (N-P1-16)")
|
||||||
|
}
|
||||||
|
res = Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000})
|
||||||
|
if res.Image == nil || res.Image.Local == "" || res.Meta.Width != 40 || res.Meta.Height != 30 {
|
||||||
|
t.Fatalf("small: %+v %v", res.Image, res.Err)
|
||||||
|
}
|
||||||
|
if b, _ := os.ReadFile(res.Image.Local); !bytes.Equal(b, pngBytes(t, 40, 30)) {
|
||||||
|
t.Fatal("cached copy differs")
|
||||||
|
}
|
||||||
|
before := opens
|
||||||
|
again := Build(bg, Request{Loc: vfs.Location{FS: rfs, Path: small}, Images: cache, MaxRemoteImageBytes: 10000})
|
||||||
|
if again.Image.Local != res.Image.Local || opens-before != 1 { // head read only, no second download
|
||||||
|
t.Fatalf("cache miss: opens %d", opens-before)
|
||||||
|
}
|
||||||
|
// Local images are referenced in place.
|
||||||
|
if r := Build(bg, Request{Loc: at(small)}); r.Image == nil || r.Image.Local != small {
|
||||||
|
t.Fatalf("local: %+v", r.Image)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestImageCacheEvicts(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
src := t.TempDir()
|
||||||
|
c, err := NewImageCache(filepath.Join(dir, "c"), 2500)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var paths []string
|
||||||
|
for i := range 3 {
|
||||||
|
p := filepath.Join(src, fmt.Sprintf("%d.png", i))
|
||||||
|
_ = os.WriteFile(p, make([]byte, 1000), 0o644)
|
||||||
|
lp, err := c.Fetch(bg, remote{local}, p, 1000, time.Unix(int64(i), 0))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
paths = append(paths, lp)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(paths[0]); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("oldest entry not evicted")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(paths[2]); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// Reopened: kept within the budget.
|
||||||
|
c2, err := NewImageCache(filepath.Join(dir, "c"), 1500)
|
||||||
|
if err != nil || c2.total > 1500 {
|
||||||
|
t.Fatalf("%v total=%d", err, c2.total)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDirPreviewLimited(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
var spec fstree.Spec
|
||||||
|
for i := range 100 {
|
||||||
|
spec = append(spec, fstree.File(fmt.Sprintf("f%03d", i), ""))
|
||||||
|
}
|
||||||
|
spec = append(spec, fstree.Dir("zdir"), fstree.File(".hidden", ""), fstree.Symlink("alink", "zdir"))
|
||||||
|
fstree.Build(t, dir, spec)
|
||||||
|
res := Build(bg, Request{Loc: at(dir), DirLimit: 10})
|
||||||
|
if res.Kind != Directory || len(res.Dir) != 10 || !res.Truncated {
|
||||||
|
t.Fatalf("%v %d %v", res.Kind, len(res.Dir), res.Truncated)
|
||||||
|
}
|
||||||
|
if res.Dir[0].Name != "alink" || res.Dir[1].Name != "zdir" || res.Dir[2].Name != "f000" {
|
||||||
|
t.Fatalf("order %s %s %s", res.Dir[0].Name, res.Dir[1].Name, res.Dir[2].Name)
|
||||||
|
}
|
||||||
|
for _, e := range res.Dir {
|
||||||
|
if e.Name == ".hidden" {
|
||||||
|
t.Fatal("hidden shown")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cap(res.Dir) > 10 {
|
||||||
|
t.Fatalf("result pins the full listing: cap %d", cap(res.Dir))
|
||||||
|
}
|
||||||
|
if res := Build(bg, Request{Loc: at(dir), DirLimit: 1000, ShowHidden: true}); len(res.Dir) != 103 || res.Truncated {
|
||||||
|
t.Fatalf("all: %d", len(res.Dir))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKindLabel(t *testing.T) {
|
||||||
|
cases := map[string]vfs.FileInfo{
|
||||||
|
"directory": {Name: "src", Mode: os.ModeDir},
|
||||||
|
"symlink": {Name: "l.go", Mode: os.ModeSymlink},
|
||||||
|
"fifo": {Name: "p", Mode: os.ModeNamedPipe},
|
||||||
|
"socket": {Name: "s", Mode: os.ModeSocket},
|
||||||
|
"device": {Name: "zero", Mode: os.ModeDevice | os.ModeCharDevice},
|
||||||
|
"go": {Name: "main.go"},
|
||||||
|
"tar.gz": {Name: "a.TAR.GZ"},
|
||||||
|
"file": {Name: "Makefile"},
|
||||||
|
}
|
||||||
|
for want, fi := range cases {
|
||||||
|
if got := KindLabel(fi); got != want {
|
||||||
|
t.Errorf("KindLabel(%q) = %q, want %q", fi.Name, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if KindLabel(vfs.FileInfo{Name: ".bashrc"}) != "file" {
|
||||||
|
t.Error("dot-file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildKinds(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
fstree.Build(t, dir, fstree.Spec{
|
||||||
|
fstree.File("empty", ""),
|
||||||
|
fstree.File("bin", "a\x00b\x00c"),
|
||||||
|
fstree.File("long.txt", strings.Repeat("line\n", 5000)),
|
||||||
|
fstree.Symlink("broken", "nowhere"),
|
||||||
|
fstree.File("song.mp3", "ID3 not really"),
|
||||||
|
})
|
||||||
|
_ = os.WriteFile(filepath.Join(dir, "pic.png"), pngBytes(t, 7, 5), 0o644)
|
||||||
|
kinds := map[string]Kind{"empty": Empty, "bin": Binary, "long.txt": Text, "broken": Special, "pic.png": Image, "song.mp3": Audio}
|
||||||
|
for name, want := range kinds {
|
||||||
|
res := Build(bg, Request{Loc: at(filepath.Join(dir, name)), MaxLines: 100})
|
||||||
|
if res.Kind != want {
|
||||||
|
t.Errorf("%s: kind %v (%v), want %v", name, res.Kind, res.Err, want)
|
||||||
|
}
|
||||||
|
if name == "long.txt" && (len(res.Lines) != 100 || !res.Truncated) {
|
||||||
|
t.Errorf("long: %d lines truncated=%v", len(res.Lines), res.Truncated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if res := Build(bg, Request{Loc: at(filepath.Join(dir, "broken"))}); res.Meta.LinkTarget != "nowhere" {
|
||||||
|
t.Error("link target")
|
||||||
|
}
|
||||||
|
// The result cache returns the same result without rebuilding.
|
||||||
|
c := NewCache(2)
|
||||||
|
opens := 0
|
||||||
|
cfs := &vfstest.FaultFS{FS: local, Hook: func(op vfstest.Op, _ string) error {
|
||||||
|
if op == vfstest.OpOpen {
|
||||||
|
opens++
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}}
|
||||||
|
loc := vfs.Location{FS: cfs, Path: filepath.Join(dir, "long.txt")}
|
||||||
|
r1 := c.Build(bg, Request{Loc: loc})
|
||||||
|
r2 := c.Build(bg, Request{Loc: loc})
|
||||||
|
if opens != 1 || len(r1.Lines) != len(r2.Lines) {
|
||||||
|
t.Fatalf("cache: opens=%d", opens)
|
||||||
|
}
|
||||||
|
if res := c.Build(bg, Request{Loc: vfs.Location{FS: local, Path: "/nonexistent"}}); !errors.Is(res.Err, syscall.ENOENT) {
|
||||||
|
t.Fatalf("missing: %v", res.Err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHighlightWindow(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "big.go")
|
||||||
|
_ = os.WriteFile(p, []byte(goSource(t)), 0o644)
|
||||||
|
res := Build(bg, Request{Loc: at(p), HighlightLines: 50})
|
||||||
|
if res.Highlighted != 50 || !strings.Contains(res.Lines[10]+res.Lines[0], "\x1b[") {
|
||||||
|
t.Fatalf("highlighted %d", res.Highlighted)
|
||||||
|
}
|
||||||
|
for i := 50; i < len(res.Lines); i++ {
|
||||||
|
if res.Lines[i] != res.Plain[i] {
|
||||||
|
t.Fatalf("line %d highlighted beyond the window", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
full := Build(bg, Request{Loc: at(p), HighlightLines: 3000})
|
||||||
|
if full.Highlighted != len(full.Plain) {
|
||||||
|
t.Fatalf("full: %d of %d", full.Highlighted, len(full.Plain))
|
||||||
|
}
|
||||||
|
}
|
||||||
16
internal/preview/text.go
Normal file
16
internal/preview/text.go
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// textLines normalises text for display (CRLF → LF, tab → 4 spaces) and
|
||||||
|
// splits it into at most max lines.
|
||||||
|
func textLines(src string, max int) (lines []string, truncated bool) {
|
||||||
|
src = strings.ReplaceAll(src, "\r\n", "\n")
|
||||||
|
src = strings.ReplaceAll(src, "\t", " ")
|
||||||
|
src = strings.TrimSuffix(src, "\n")
|
||||||
|
lines = strings.Split(src, "\n")
|
||||||
|
if len(lines) > max {
|
||||||
|
lines, truncated = lines[:max], true
|
||||||
|
}
|
||||||
|
return lines, truncated
|
||||||
|
}
|
||||||
78
internal/preview/tools.go
Normal file
78
internal/preview/tools.go
Normal file
|
|
@ -0,0 +1,78 @@
|
||||||
|
package preview
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tools are the external utilities, looked up once at start.
|
||||||
|
type Tools struct {
|
||||||
|
PdfToText string
|
||||||
|
PdfInfo string
|
||||||
|
FFProbe string
|
||||||
|
Timeout time.Duration // per run; default 3 s
|
||||||
|
}
|
||||||
|
|
||||||
|
// FindTools looks the utilities up in $PATH.
|
||||||
|
func FindTools() *Tools {
|
||||||
|
look := func(name string) string {
|
||||||
|
p, _ := exec.LookPath(name)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
return &Tools{PdfToText: look("pdftotext"), PdfInfo: look("pdfinfo"), FFProbe: look("ffprobe"), Timeout: 3 * time.Second}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrToolTimeout: the tool was killed after Tools.Timeout.
|
||||||
|
var ErrToolTimeout = errors.New("timed out")
|
||||||
|
|
||||||
|
// run executes prog with a timeout. The tool gets its own process group and
|
||||||
|
// the whole group is killed on timeout or cancel, so a child holding stdout
|
||||||
|
// open cannot make Wait hang. Output beyond max bytes is discarded.
|
||||||
|
func (t *Tools) run(ctx context.Context, max int64, prog string, args ...string) ([]byte, error) {
|
||||||
|
timeout := t.Timeout
|
||||||
|
if timeout <= 0 {
|
||||||
|
timeout = 3 * time.Second
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
cmd := exec.CommandContext(ctx, prog, args...)
|
||||||
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||||
|
cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) }
|
||||||
|
cmd.WaitDelay = 200 * time.Millisecond
|
||||||
|
out := &capped{max: max}
|
||||||
|
cmd.Stdout = out
|
||||||
|
err := cmd.Run()
|
||||||
|
if ctx.Err() == context.DeadlineExceeded {
|
||||||
|
return nil, fmt.Errorf("%s: %w after %v", prog, ErrToolTimeout, timeout)
|
||||||
|
}
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("%s: %w", prog, err)
|
||||||
|
}
|
||||||
|
return out.b.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// capped keeps the first max bytes and swallows the rest (the tool is not
|
||||||
|
// killed by a broken pipe halfway through).
|
||||||
|
type capped struct {
|
||||||
|
b bytes.Buffer
|
||||||
|
max int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *capped) Write(p []byte) (int, error) {
|
||||||
|
if room := c.max - int64(c.b.Len()); room > 0 {
|
||||||
|
if int64(len(p)) > room {
|
||||||
|
c.b.Write(p[:room])
|
||||||
|
} else {
|
||||||
|
c.b.Write(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return len(p), nil
|
||||||
|
}
|
||||||
263
internal/ssh/conn/auth.go
Normal file
263
internal/ssh/conn/auth.go
Normal file
|
|
@ -0,0 +1,263 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
"golang.org/x/crypto/ssh/agent"
|
||||||
|
)
|
||||||
|
|
||||||
|
// agentConn is the process-wide connection to ssh-agent (N-P2-1: the old
|
||||||
|
// code opened a new socket per connect and never closed it). It is opened on
|
||||||
|
// first use, reopened after an error, and closed by dialer.close.
|
||||||
|
type agentConn struct {
|
||||||
|
sock string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
c net.Conn
|
||||||
|
ag agent.ExtendedAgent
|
||||||
|
dials atomic.Int32 // sockets opened, for tests
|
||||||
|
}
|
||||||
|
|
||||||
|
// signers returns the agent's keys; no agent (or an agent error) yields nil.
|
||||||
|
func (a *agentConn) signers() []ssh.Signer {
|
||||||
|
if a == nil || a.sock == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
if a.ag == nil {
|
||||||
|
c, err := net.DialTimeout("unix", a.sock, 2*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
a.dials.Add(1)
|
||||||
|
a.c, a.ag = c, agent.NewClient(c)
|
||||||
|
}
|
||||||
|
ss, err := a.ag.Signers()
|
||||||
|
if err != nil {
|
||||||
|
a.c.Close()
|
||||||
|
a.c, a.ag = nil, nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ss
|
||||||
|
}
|
||||||
|
|
||||||
|
func (a *agentConn) close() {
|
||||||
|
if a == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.mu.Lock()
|
||||||
|
defer a.mu.Unlock()
|
||||||
|
if a.c != nil {
|
||||||
|
a.c.Close()
|
||||||
|
a.c, a.ag = nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// authMethods builds the auth chain (N-P2-2): public keys (explicit
|
||||||
|
// IdentityFiles, then agent keys, then default key files), password (stored
|
||||||
|
// or asked), keyboard-interactive (questions shown as they are, so 2FA
|
||||||
|
// works). x/crypto tries each method name once, so all keys go into one
|
||||||
|
// publickey method.
|
||||||
|
func (d *dialer) authMethods(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.AuthMethod {
|
||||||
|
methods := []ssh.AuthMethod{ssh.PublicKeysCallback(func() ([]ssh.Signer, error) {
|
||||||
|
return d.signers(ctx, ep, prompt), nil
|
||||||
|
})}
|
||||||
|
p := d.opts.Prompter
|
||||||
|
storedUsed := false // the handshake runs auth sequentially
|
||||||
|
if ep.Password != "" || p != nil {
|
||||||
|
methods = append(methods, ssh.PasswordCallback(func() (string, error) {
|
||||||
|
if ep.Password != "" && !storedUsed {
|
||||||
|
storedUsed = true
|
||||||
|
return ep.Password, nil
|
||||||
|
}
|
||||||
|
if p == nil {
|
||||||
|
return "", errors.New("password rejected")
|
||||||
|
}
|
||||||
|
var pw string
|
||||||
|
err := prompt(func() error {
|
||||||
|
var err error
|
||||||
|
pw, err = p.Password(ctx, ep)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
return pw, err
|
||||||
|
}))
|
||||||
|
methods = append(methods, ssh.KeyboardInteractive(func(name, instruction string, qs []string, echo []bool) ([]string, error) {
|
||||||
|
if len(qs) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
// A lone hidden question is the server's password prompt.
|
||||||
|
if ep.Password != "" && !storedUsed && len(qs) == 1 && !echo[0] {
|
||||||
|
storedUsed = true
|
||||||
|
return []string{ep.Password}, nil
|
||||||
|
}
|
||||||
|
if p == nil {
|
||||||
|
return nil, errors.New("keyboard-interactive: no way to ask the user")
|
||||||
|
}
|
||||||
|
instr := strings.TrimSpace(strings.TrimSpace(name) + "\n" + strings.TrimSpace(instruction))
|
||||||
|
var answers []string
|
||||||
|
err := prompt(func() error {
|
||||||
|
var err error
|
||||||
|
answers, err = p.KeyboardInteractive(ctx, ep, instr, qs, echo)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err == nil && len(answers) != len(qs) {
|
||||||
|
err = fmt.Errorf("keyboard-interactive: %d answers for %d questions", len(answers), len(qs))
|
||||||
|
}
|
||||||
|
return answers, err
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
return methods
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dialer) signers(ctx context.Context, ep Endpoint, prompt func(func() error) error) []ssh.Signer {
|
||||||
|
var out []ssh.Signer
|
||||||
|
seen := map[string]bool{}
|
||||||
|
add := func(s ssh.Signer) {
|
||||||
|
if s == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
k := string(s.PublicKey().Marshal())
|
||||||
|
if !seen[k] {
|
||||||
|
seen[k] = true
|
||||||
|
out = append(out, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
agentKeys := d.agent.signers()
|
||||||
|
inAgent := make(map[string]ssh.Signer, len(agentKeys))
|
||||||
|
for _, s := range agentKeys {
|
||||||
|
inAgent[string(s.PublicKey().Marshal())] = s
|
||||||
|
}
|
||||||
|
for _, p := range ep.IdentityFiles {
|
||||||
|
add(d.loadKey(ctx, p, inAgent, prompt))
|
||||||
|
}
|
||||||
|
if !ep.IdentitiesOnly {
|
||||||
|
for _, s := range agentKeys {
|
||||||
|
add(s)
|
||||||
|
}
|
||||||
|
for _, p := range d.opts.DefaultIdentityFiles {
|
||||||
|
add(d.loadKey(ctx, p, inAgent, prompt))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadKey reads a private key. An encrypted key whose public half is known
|
||||||
|
// (embedded in the OpenSSH format or in path.pub) becomes a lazySigner: the
|
||||||
|
// passphrase is asked only if the server accepts the key. A key already
|
||||||
|
// unlocked in the agent is used from there.
|
||||||
|
func (d *dialer) loadKey(ctx context.Context, path string, inAgent map[string]ssh.Signer, prompt func(func() error) error) ssh.Signer {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
s, err := ssh.ParsePrivateKey(data)
|
||||||
|
if err == nil {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var pm *ssh.PassphraseMissingError
|
||||||
|
if !errors.As(err, &pm) {
|
||||||
|
d.warnf("identity %s: %v", path, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
pub := pm.PublicKey
|
||||||
|
if pub == nil {
|
||||||
|
if b, err := os.ReadFile(path + ".pub"); err == nil {
|
||||||
|
pub, _, _, _, _ = ssh.ParseAuthorizedKey(b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pub != nil {
|
||||||
|
if as := inAgent[string(pub.Marshal())]; as != nil {
|
||||||
|
return as
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d.opts.Prompter == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ls := &lazySigner{pub: pub, path: path, pem: data, ask: func() ([]byte, error) {
|
||||||
|
var pass []byte
|
||||||
|
err := prompt(func() error {
|
||||||
|
var err error
|
||||||
|
pass, err = d.opts.Prompter.Passphrase(ctx, path)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
return pass, err
|
||||||
|
}}
|
||||||
|
if pub == nil {
|
||||||
|
// Without the public half the key cannot be offered lazily.
|
||||||
|
if _, err := ls.load(); err != nil {
|
||||||
|
d.warnf("identity %s: %v", path, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ls.pub = ls.s.PublicKey()
|
||||||
|
}
|
||||||
|
return ls
|
||||||
|
}
|
||||||
|
|
||||||
|
// lazySigner decrypts a passphrase-protected key on first Sign.
|
||||||
|
type lazySigner struct {
|
||||||
|
pub ssh.PublicKey
|
||||||
|
path string
|
||||||
|
pem []byte
|
||||||
|
ask func() ([]byte, error)
|
||||||
|
|
||||||
|
once sync.Once
|
||||||
|
s ssh.AlgorithmSigner
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
const passphraseAttempts = 3
|
||||||
|
|
||||||
|
func (l *lazySigner) load() (ssh.AlgorithmSigner, error) {
|
||||||
|
l.once.Do(func() {
|
||||||
|
for i := 0; i < passphraseAttempts; i++ {
|
||||||
|
pass, err := l.ask()
|
||||||
|
if err != nil {
|
||||||
|
l.err = err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s, err := ssh.ParsePrivateKeyWithPassphrase(l.pem, pass)
|
||||||
|
clear(pass)
|
||||||
|
if err != nil {
|
||||||
|
l.err = fmt.Errorf("identity %s: %w", l.path, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
as, ok := s.(ssh.AlgorithmSigner)
|
||||||
|
if !ok {
|
||||||
|
l.err = fmt.Errorf("identity %s: unsupported key type", l.path)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
l.s, l.err = as, nil
|
||||||
|
return
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return l.s, l.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *lazySigner) PublicKey() ssh.PublicKey { return l.pub }
|
||||||
|
|
||||||
|
func (l *lazySigner) Sign(r io.Reader, data []byte) (*ssh.Signature, error) {
|
||||||
|
s, err := l.load()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return s.Sign(r, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *lazySigner) SignWithAlgorithm(r io.Reader, data []byte, algo string) (*ssh.Signature, error) {
|
||||||
|
s, err := l.load()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return s.SignWithAlgorithm(r, data, algo)
|
||||||
|
}
|
||||||
360
internal/ssh/conn/conn.go
Normal file
360
internal/ssh/conn/conn.go
Normal file
|
|
@ -0,0 +1,360 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrConnLost: the connection died (keepalive timeout, network cut,
|
||||||
|
// server gone). The operation may be retried after Reconnect. sftpfs maps
|
||||||
|
// it to vfs.ErrConnLost.
|
||||||
|
ErrConnLost = errors.New("connection lost")
|
||||||
|
// ErrClosed: the connection was closed by the pool.
|
||||||
|
ErrClosed = errors.New("connection closed")
|
||||||
|
)
|
||||||
|
|
||||||
|
// State of a Conn.
|
||||||
|
type State uint32
|
||||||
|
|
||||||
|
const (
|
||||||
|
Connecting State = iota
|
||||||
|
Ready
|
||||||
|
Lost
|
||||||
|
Closed
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s State) String() string {
|
||||||
|
switch s {
|
||||||
|
case Connecting:
|
||||||
|
return "connecting"
|
||||||
|
case Ready:
|
||||||
|
return "ready"
|
||||||
|
case Lost:
|
||||||
|
return "lost"
|
||||||
|
case Closed:
|
||||||
|
return "closed"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("State(%d)", uint32(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Event reports a state change (ConnStateChanged). main forwards it to the
|
||||||
|
// UI with program.Send; it is called from connection goroutines and must not
|
||||||
|
// block.
|
||||||
|
type Event struct {
|
||||||
|
Key string // Endpoint.Key()
|
||||||
|
State State
|
||||||
|
Gen uint64 // generation the state refers to
|
||||||
|
Err error // why the connection was lost (Lost), nil otherwise
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defaults for keepalive (§3.4).
|
||||||
|
const (
|
||||||
|
DefaultKeepaliveInterval = 15 * time.Second
|
||||||
|
DefaultKeepaliveTimeout = 10 * time.Second
|
||||||
|
DefaultKeepaliveMaxMiss = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConnOptions tune liveness detection of one connection.
|
||||||
|
type ConnOptions struct {
|
||||||
|
KeepaliveInterval time.Duration // default 15s, or Endpoint.ServerAliveInterval
|
||||||
|
KeepaliveTimeout time.Duration // per keepalive reply; default 10s
|
||||||
|
KeepaliveMaxMiss int // default 2, or Endpoint.ServerAliveCountMax
|
||||||
|
OnEvent func(Event)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o ConnOptions) withDefaults(ep Endpoint) ConnOptions {
|
||||||
|
if o.KeepaliveInterval <= 0 {
|
||||||
|
o.KeepaliveInterval = ep.ServerAliveInterval
|
||||||
|
}
|
||||||
|
if o.KeepaliveInterval <= 0 {
|
||||||
|
o.KeepaliveInterval = DefaultKeepaliveInterval
|
||||||
|
}
|
||||||
|
if o.KeepaliveTimeout <= 0 {
|
||||||
|
o.KeepaliveTimeout = DefaultKeepaliveTimeout
|
||||||
|
}
|
||||||
|
if o.KeepaliveMaxMiss <= 0 {
|
||||||
|
o.KeepaliveMaxMiss = ep.ServerAliveCountMax
|
||||||
|
}
|
||||||
|
if o.KeepaliveMaxMiss <= 0 {
|
||||||
|
o.KeepaliveMaxMiss = DefaultKeepaliveMaxMiss
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConnCaps are server capabilities detected at connect time.
|
||||||
|
type ConnCaps struct {
|
||||||
|
PosixRename bool // posix-rename@openssh.com: atomic Rename(Replace)
|
||||||
|
Fsync bool // fsync@openssh.com
|
||||||
|
StatVFS bool // statvfs@openssh.com
|
||||||
|
Hardlink bool // hardlink@openssh.com
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn is one logical connection to an endpoint. Its fields are never reset:
|
||||||
|
// the current *sftp.Client sits in an atomic pointer and, once the
|
||||||
|
// connection dies, keeps returning errors instead of disappearing (N-P0-8).
|
||||||
|
// Reconnect installs a new generation in the same Conn, so leases stay
|
||||||
|
// valid. Only the Pool closes a Conn.
|
||||||
|
type Conn struct {
|
||||||
|
d *dialer
|
||||||
|
ep Endpoint
|
||||||
|
key string
|
||||||
|
opts ConnOptions
|
||||||
|
|
||||||
|
state atomic.Uint32
|
||||||
|
gen atomic.Uint64
|
||||||
|
sftp atomic.Pointer[sftp.Client]
|
||||||
|
cur atomic.Pointer[generation]
|
||||||
|
|
||||||
|
mu sync.Mutex // serializes state transitions
|
||||||
|
lostBy error
|
||||||
|
|
||||||
|
reconnectMu sync.Mutex // one reconnect at a time
|
||||||
|
|
||||||
|
execMu sync.Mutex
|
||||||
|
execKnown bool
|
||||||
|
execOK bool
|
||||||
|
|
||||||
|
wg sync.WaitGroup // per-generation goroutines
|
||||||
|
}
|
||||||
|
|
||||||
|
// generation is one live link plus its lifetime signal.
|
||||||
|
type generation struct {
|
||||||
|
*link
|
||||||
|
gen uint64
|
||||||
|
caps ConnCaps
|
||||||
|
done chan struct{} // closed when the link has ended
|
||||||
|
}
|
||||||
|
|
||||||
|
func newGeneration(l *link, gen uint64) *generation {
|
||||||
|
g := &generation{link: l, gen: gen, done: make(chan struct{})}
|
||||||
|
_, g.caps.PosixRename = l.sftp.HasExtension("posix-rename@openssh.com")
|
||||||
|
_, g.caps.Fsync = l.sftp.HasExtension("fsync@openssh.com")
|
||||||
|
_, g.caps.StatVFS = l.sftp.HasExtension("statvfs@openssh.com")
|
||||||
|
_, g.caps.Hardlink = l.sftp.HasExtension("hardlink@openssh.com")
|
||||||
|
return g
|
||||||
|
}
|
||||||
|
|
||||||
|
// connect dials ep and returns a Ready Conn with keepalive running.
|
||||||
|
func (d *dialer) connect(ctx context.Context, ep Endpoint, o ConnOptions) (*Conn, error) {
|
||||||
|
c := &Conn{d: d, ep: ep, key: ep.Key(), opts: o.withDefaults(ep)}
|
||||||
|
c.state.Store(uint32(Connecting))
|
||||||
|
l, err := d.dial(ctx, ep)
|
||||||
|
if err != nil {
|
||||||
|
c.state.Store(uint32(Closed))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c.mu.Lock()
|
||||||
|
c.install(l)
|
||||||
|
c.mu.Unlock()
|
||||||
|
c.emit(Event{Key: c.key, State: Ready, Gen: c.gen.Load()})
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// install makes l the current generation; c.mu is held.
|
||||||
|
func (c *Conn) install(l *link) {
|
||||||
|
gen := c.gen.Add(1)
|
||||||
|
g := newGeneration(l, gen)
|
||||||
|
c.cur.Store(g)
|
||||||
|
c.sftp.Store(l.sftp)
|
||||||
|
c.lostBy = nil
|
||||||
|
c.state.Store(uint32(Ready))
|
||||||
|
c.wg.Add(2)
|
||||||
|
go func() {
|
||||||
|
defer c.wg.Done()
|
||||||
|
err := l.ssh.Wait()
|
||||||
|
close(g.done)
|
||||||
|
if err == nil {
|
||||||
|
err = io.EOF
|
||||||
|
}
|
||||||
|
c.lose(g, err)
|
||||||
|
}()
|
||||||
|
go func() {
|
||||||
|
defer c.wg.Done()
|
||||||
|
c.keepalive(g)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// lose marks generation g as Lost (if it is still current and Ready) and
|
||||||
|
// closes its SSH client, failing every pending request at once.
|
||||||
|
func (c *Conn) lose(g *generation, why error) {
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.cur.Load() != g || c.State() != Ready {
|
||||||
|
c.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, why)
|
||||||
|
c.state.Store(uint32(Lost))
|
||||||
|
err := c.lostBy
|
||||||
|
c.mu.Unlock()
|
||||||
|
g.ssh.Close()
|
||||||
|
g.sftp.Close()
|
||||||
|
c.emit(Event{Key: c.key, State: Lost, Gen: g.gen, Err: err})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Conn) emit(e Event) {
|
||||||
|
if c.opts.OnEvent != nil {
|
||||||
|
c.opts.OnEvent(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// State returns the current state.
|
||||||
|
func (c *Conn) State() State { return State(c.state.Load()) }
|
||||||
|
|
||||||
|
// Gen is the generation number; it grows with every successful Reconnect.
|
||||||
|
func (c *Conn) Gen() uint64 { return c.gen.Load() }
|
||||||
|
|
||||||
|
// Key is the pool key (Endpoint.Key()).
|
||||||
|
func (c *Conn) Key() string { return c.key }
|
||||||
|
|
||||||
|
// Endpoint returns the endpoint this connection was dialed with.
|
||||||
|
func (c *Conn) Endpoint() Endpoint { return c.ep }
|
||||||
|
|
||||||
|
// Err explains the current state: why it was lost, ErrClosed, or nil.
|
||||||
|
func (c *Conn) Err() error {
|
||||||
|
switch c.State() {
|
||||||
|
case Closed:
|
||||||
|
return ErrClosed
|
||||||
|
case Lost, Connecting:
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
if c.lostBy != nil {
|
||||||
|
return c.lostBy
|
||||||
|
}
|
||||||
|
return ErrConnLost
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Client returns the SFTP client of the current generation, or an error
|
||||||
|
// wrapping ErrConnLost / ErrClosed when the connection is not Ready. The
|
||||||
|
// client is safe for concurrent use; after the connection dies its calls
|
||||||
|
// fail (map them with MapErr).
|
||||||
|
func (c *Conn) Client() (*sftp.Client, error) {
|
||||||
|
if err := c.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c.sftp.Load(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SSH returns the SSH client of the current generation (for exec and port
|
||||||
|
// forwarding), with the same rules as Client.
|
||||||
|
func (c *Conn) SSH() (*ssh.Client, error) {
|
||||||
|
if err := c.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return c.cur.Load().ssh, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Identity is the host key of the server; it does not change across
|
||||||
|
// reconnects (a different key fails the reconnect).
|
||||||
|
func (c *Conn) Identity() HostIdentity { return c.cur.Load().id }
|
||||||
|
|
||||||
|
// ServerVersion is the server's SSH version banner, e.g.
|
||||||
|
// "SSH-2.0-OpenSSH_9.6" (sftpfs uses it for the symlink argument order).
|
||||||
|
func (c *Conn) ServerVersion() string { return c.cur.Load().serverVersion }
|
||||||
|
|
||||||
|
// Caps returns the SFTP extensions of the current generation. Exec support
|
||||||
|
// is probed separately (ExecSupported) because it needs a round trip.
|
||||||
|
func (c *Conn) Caps() ConnCaps { return c.cur.Load().caps }
|
||||||
|
|
||||||
|
// MapErr turns errors caused by a dead connection into ErrConnLost (wrapped,
|
||||||
|
// so the original stays visible); other errors are returned unchanged.
|
||||||
|
func (c *Conn) MapErr(err error) error {
|
||||||
|
if err == nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if errors.Is(err, sftp.ErrSSHFxConnectionLost) || errors.Is(err, net.ErrClosed) {
|
||||||
|
return fmt.Errorf("%w: %v", ErrConnLost, err)
|
||||||
|
}
|
||||||
|
if st := c.State(); st != Ready && (errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF)) {
|
||||||
|
if st == Closed {
|
||||||
|
return fmt.Errorf("%w: %v", ErrClosed, err)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%w: %v", ErrConnLost, err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrIdentityChanged: on reconnect the server presented a different host key
|
||||||
|
// than the original connection (the Volume would no longer be the same).
|
||||||
|
var ErrIdentityChanged = errors.New("server host key differs from the original connection")
|
||||||
|
|
||||||
|
// Reconnect dials a new generation if the connection is Lost. It is a
|
||||||
|
// single attempt (Pool.Reconnect adds backoff); concurrent calls are
|
||||||
|
// serialized and a call on a Ready connection is a no-op. Operations started
|
||||||
|
// on the old generation keep failing with ErrConnLost.
|
||||||
|
func (c *Conn) Reconnect(ctx context.Context) error {
|
||||||
|
c.reconnectMu.Lock()
|
||||||
|
defer c.reconnectMu.Unlock()
|
||||||
|
c.mu.Lock()
|
||||||
|
switch c.State() {
|
||||||
|
case Closed:
|
||||||
|
c.mu.Unlock()
|
||||||
|
return ErrClosed
|
||||||
|
case Ready:
|
||||||
|
c.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c.state.Store(uint32(Connecting))
|
||||||
|
gen := c.gen.Load()
|
||||||
|
c.mu.Unlock()
|
||||||
|
c.emit(Event{Key: c.key, State: Connecting, Gen: gen})
|
||||||
|
|
||||||
|
l, err := c.d.dial(ctx, c.ep)
|
||||||
|
if err == nil && l.id != c.Identity() {
|
||||||
|
l.close()
|
||||||
|
err = fmt.Errorf("reconnect %s: %w (was %s, now %s)", c.ep.Label(), ErrIdentityChanged,
|
||||||
|
c.Identity().FingerprintSHA256, l.id.FingerprintSHA256)
|
||||||
|
}
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.State() == Closed {
|
||||||
|
c.mu.Unlock()
|
||||||
|
if err == nil {
|
||||||
|
l.close()
|
||||||
|
}
|
||||||
|
return ErrClosed
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
c.lostBy = fmt.Errorf("%w: %v", ErrConnLost, err)
|
||||||
|
c.state.Store(uint32(Lost))
|
||||||
|
lostBy := c.lostBy
|
||||||
|
c.mu.Unlock()
|
||||||
|
c.emit(Event{Key: c.key, State: Lost, Gen: gen, Err: lostBy})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
c.install(l)
|
||||||
|
gen = c.gen.Load()
|
||||||
|
c.mu.Unlock()
|
||||||
|
c.emit(Event{Key: c.key, State: Ready, Gen: gen})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// close shuts the connection down for good and waits for its goroutines.
|
||||||
|
// Only the Pool calls it.
|
||||||
|
func (c *Conn) close() {
|
||||||
|
c.mu.Lock()
|
||||||
|
if c.State() == Closed {
|
||||||
|
c.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.state.Store(uint32(Closed))
|
||||||
|
g := c.cur.Load()
|
||||||
|
c.mu.Unlock()
|
||||||
|
if g != nil {
|
||||||
|
g.close()
|
||||||
|
}
|
||||||
|
c.wg.Wait()
|
||||||
|
if g != nil {
|
||||||
|
c.emit(Event{Key: c.key, State: Closed, Gen: g.gen})
|
||||||
|
}
|
||||||
|
}
|
||||||
297
internal/ssh/conn/conn_test.go
Normal file
297
internal/ssh/conn/conn_test.go
Normal file
|
|
@ -0,0 +1,297 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// events collects Conn events.
|
||||||
|
type events struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
ev []Event
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *events) add(ev Event) {
|
||||||
|
e.mu.Lock()
|
||||||
|
e.ev = append(e.ev, ev)
|
||||||
|
e.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *events) has(s State) bool {
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
for _, ev := range e.ev {
|
||||||
|
if ev.State == s {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *events) snapshot() []Event {
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
return append([]Event(nil), e.ev...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *events) last() Event {
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
if len(e.ev) == 0 {
|
||||||
|
return Event{}
|
||||||
|
}
|
||||||
|
return e.ev[len(e.ev)-1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// fastKeepalive makes liveness tests take well under a second.
|
||||||
|
var fastKeepalive = ConnOptions{
|
||||||
|
KeepaliveInterval: 100 * time.Millisecond,
|
||||||
|
KeepaliveTimeout: 100 * time.Millisecond,
|
||||||
|
KeepaliveMaxMiss: 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *env) connect(addr, password string, o ConnOptions) *Conn {
|
||||||
|
e.t.Helper()
|
||||||
|
c, err := e.dialer(DialOptions{}).connect(context.Background(), endpointFor(addr, password), o)
|
||||||
|
if err != nil {
|
||||||
|
e.t.Fatalf("connect: %v", err)
|
||||||
|
}
|
||||||
|
e.t.Cleanup(c.close)
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ported from the testbed (B6, TestFreezeHangs), N-P1-2: a frozen link was
|
||||||
|
// never noticed and calls hung forever. Now keepalive marks it Lost within
|
||||||
|
// interval*(miss+1)+timeout and the hung ReadDir returns ErrConnLost.
|
||||||
|
func TestFreezeDetectedAsLost(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
var ev events
|
||||||
|
o := fastKeepalive
|
||||||
|
o.OnEvent = ev.add
|
||||||
|
c := e.connect(px.Addr, srv.Password, o)
|
||||||
|
sc, err := c.Client()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
if _, err := sc.ReadDir(dir); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
px.Freeze(true)
|
||||||
|
defer px.Freeze(false)
|
||||||
|
start := time.Now()
|
||||||
|
res := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := sc.ReadDir(dir)
|
||||||
|
res <- c.MapErr(err)
|
||||||
|
}()
|
||||||
|
bound := o.KeepaliveInterval*time.Duration(o.KeepaliveMaxMiss+1) + o.KeepaliveTimeout
|
||||||
|
waitFor(t, bound+500*time.Millisecond, "state Lost", func() bool { return c.State() == Lost })
|
||||||
|
t.Logf("lost after %v (bound %v)", time.Since(start), bound)
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
if !errors.Is(err, ErrConnLost) {
|
||||||
|
t.Errorf("hung ReadDir: err = %v, want ErrConnLost", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("hung ReadDir did not return after Lost")
|
||||||
|
}
|
||||||
|
waitFor(t, time.Second, "Lost event", func() bool { return ev.has(Lost) })
|
||||||
|
if ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) {
|
||||||
|
t.Errorf("events = %+v", ev.snapshot())
|
||||||
|
}
|
||||||
|
if _, err := c.Client(); !errors.Is(err, ErrConnLost) {
|
||||||
|
t.Errorf("Client() after Lost: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReconnectAfterCut(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
var ev events
|
||||||
|
o := ConnOptions{KeepaliveInterval: time.Hour, OnEvent: ev.add}
|
||||||
|
c := e.connect(px.Addr, srv.Password, o)
|
||||||
|
dir := t.TempDir()
|
||||||
|
gen := c.Gen()
|
||||||
|
id := c.Identity()
|
||||||
|
|
||||||
|
px.CutAfter(1)
|
||||||
|
sc, _ := c.Client()
|
||||||
|
_, err := sc.ReadDir(dir)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("ReadDir across a cut succeeded")
|
||||||
|
}
|
||||||
|
if !errors.Is(c.MapErr(err), ErrConnLost) {
|
||||||
|
t.Errorf("err = %v, want ErrConnLost", c.MapErr(err))
|
||||||
|
}
|
||||||
|
waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost })
|
||||||
|
|
||||||
|
if err := c.Reconnect(context.Background()); err != nil {
|
||||||
|
t.Fatalf("Reconnect: %v", err)
|
||||||
|
}
|
||||||
|
if c.State() != Ready || c.Gen() != gen+1 || c.Identity() != id {
|
||||||
|
t.Errorf("after reconnect: state %v gen %d (was %d) id %+v", c.State(), c.Gen(), gen, c.Identity())
|
||||||
|
}
|
||||||
|
sc2, err := c.Client()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := sc2.ReadDir(dir); err != nil {
|
||||||
|
t.Fatalf("ReadDir after reconnect: %v", err)
|
||||||
|
}
|
||||||
|
// The old generation's client stays dead.
|
||||||
|
if _, err := sc.ReadDir(dir); !errors.Is(c.MapErr(err), ErrConnLost) {
|
||||||
|
t.Errorf("old-generation client: %v", err)
|
||||||
|
}
|
||||||
|
if err := c.Reconnect(context.Background()); err != nil {
|
||||||
|
t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err)
|
||||||
|
}
|
||||||
|
if !ev.has(Connecting) || ev.last().State != Ready {
|
||||||
|
t.Errorf("events = %+v", ev.snapshot())
|
||||||
|
}
|
||||||
|
c.close()
|
||||||
|
if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) {
|
||||||
|
t.Errorf("Reconnect after close: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := c.Client(); !errors.Is(err, ErrClosed) {
|
||||||
|
t.Errorf("Client after close: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestReconnectFailsWhileServerDown(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour})
|
||||||
|
px.Freeze(true)
|
||||||
|
defer px.Freeze(false)
|
||||||
|
px.KillAll()
|
||||||
|
waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost })
|
||||||
|
c.d.opts.HandshakeTimeout = 200 * time.Millisecond
|
||||||
|
if err := c.Reconnect(context.Background()); err == nil {
|
||||||
|
t.Fatal("reconnect through a frozen link succeeded")
|
||||||
|
}
|
||||||
|
if c.State() != Lost {
|
||||||
|
t.Errorf("state = %v, want Lost", c.State())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProbeMarksLost(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour})
|
||||||
|
if err := c.Probe(context.Background(), time.Second); err != nil {
|
||||||
|
t.Fatalf("probe on a live link: %v", err)
|
||||||
|
}
|
||||||
|
px.Freeze(true)
|
||||||
|
defer px.Freeze(false)
|
||||||
|
if err := c.Probe(context.Background(), 100*time.Millisecond); !errors.Is(err, ErrConnLost) {
|
||||||
|
t.Fatalf("probe on a frozen link: %v", err)
|
||||||
|
}
|
||||||
|
if c.State() != Lost {
|
||||||
|
t.Errorf("state = %v", c.State())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-15 / N-P1-7: Exec had no ctx and no timeout.
|
||||||
|
func TestExecCancelKills(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
time.AfterFunc(100*time.Millisecond, cancel)
|
||||||
|
start := time.Now()
|
||||||
|
_, _, err := c.Exec(ctx, []string{"sleep", "60"}, 0)
|
||||||
|
if el := time.Since(start); el > time.Second {
|
||||||
|
t.Errorf("cancel took %v", el)
|
||||||
|
}
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("err = %v", err)
|
||||||
|
}
|
||||||
|
// The connection is still usable.
|
||||||
|
out, code, err := c.Exec(context.Background(), []string{"echo", "it's ok"}, 0)
|
||||||
|
if err != nil || code != 0 || string(out) != "it's ok\n" {
|
||||||
|
t.Errorf("exec after cancel: %q %d %v", out, code, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecOutputLimit(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
|
||||||
|
start := time.Now()
|
||||||
|
out, _, err := c.Exec(context.Background(), []string{"yes"}, 1000)
|
||||||
|
if !errors.Is(err, ErrOutputLimit) {
|
||||||
|
t.Fatalf("err = %v, want ErrOutputLimit", err)
|
||||||
|
}
|
||||||
|
if len(out) != 1000 || !strings.HasPrefix(string(out), "y\ny\n") {
|
||||||
|
t.Errorf("output: %d bytes", len(out))
|
||||||
|
}
|
||||||
|
if el := time.Since(start); el > 2*time.Second {
|
||||||
|
t.Errorf("limited exec took %v", el)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecExitStatus(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
|
||||||
|
out, code, err := c.Exec(context.Background(), []string{"sh", "-c", "echo out; echo bad >&2; exit 3"}, 0)
|
||||||
|
var ee *ExitError
|
||||||
|
if !errors.As(err, &ee) || code != 3 || ee.Code != 3 || strings.TrimSpace(ee.Stderr) != "bad" || string(out) != "out\n" {
|
||||||
|
t.Errorf("out=%q code=%d err=%v", out, code, err)
|
||||||
|
}
|
||||||
|
if !c.ExecSupported(context.Background()) {
|
||||||
|
t.Error("ExecSupported = false on a server with exec")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecSupportedNoExec(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{NoExec: true})
|
||||||
|
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
|
||||||
|
if c.ExecSupported(context.Background()) {
|
||||||
|
t.Error("ExecSupported = true with ForceCommand internal-sftp")
|
||||||
|
}
|
||||||
|
if _, err := c.Client(); err != nil {
|
||||||
|
t.Errorf("a refused exec must not break the connection: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQuote(t *testing.T) {
|
||||||
|
got := Quote([]string{"cp", "-r", "a b", "it's", "", "x;rm -rf /", "/ok/path_1.txt"})
|
||||||
|
want := `cp -r 'a b' 'it'\''s' '' 'x;rm -rf /' /ok/path_1.txt`
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("Quote = %s\nwant %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConnInfo(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
|
||||||
|
if c.Identity().FingerprintSHA256 == "" || !strings.HasPrefix(c.ServerVersion(), "SSH-2.0-") {
|
||||||
|
t.Errorf("identity %+v version %q", c.Identity(), c.ServerVersion())
|
||||||
|
}
|
||||||
|
if !c.Caps().PosixRename {
|
||||||
|
t.Logf("caps: %+v", c.Caps())
|
||||||
|
}
|
||||||
|
if c.Key() != "u@"+srv.Addr {
|
||||||
|
t.Errorf("Key = %q", c.Key())
|
||||||
|
}
|
||||||
|
}
|
||||||
235
internal/ssh/conn/dial.go
Normal file
235
internal/ssh/conn/dial.go
Normal file
|
|
@ -0,0 +1,235 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultHandshakeTimeout bounds TCP connect + kex + auth + SFTP init.
|
||||||
|
const DefaultHandshakeTimeout = 20 * time.Second
|
||||||
|
|
||||||
|
// ErrHandshakeTimeout: the server accepted TCP but did not finish the
|
||||||
|
// handshake in time (N-P1-3).
|
||||||
|
var ErrHandshakeTimeout = errors.New("ssh handshake timed out")
|
||||||
|
|
||||||
|
// DialOptions configures how connections are established.
|
||||||
|
type DialOptions struct {
|
||||||
|
Prompter Prompter
|
||||||
|
// HandshakeTimeout covers the whole path TCP + kex + auth + SFTP init,
|
||||||
|
// excluding time spent waiting for the Prompter. Default 20s.
|
||||||
|
HandshakeTimeout time.Duration
|
||||||
|
// Home is the home directory for the default known_hosts and identity
|
||||||
|
// files ("" = os.UserHomeDir()).
|
||||||
|
Home string
|
||||||
|
// KnownHostsFiles are read in order. nil means Home/.ssh/known_hosts and
|
||||||
|
// /etc/ssh/ssh_known_hosts.
|
||||||
|
KnownHostsFiles []string
|
||||||
|
// KnownHostsWrite receives AcceptAndSave lines. "" means the first of
|
||||||
|
// KnownHostsFiles (the default user file). Set to "-" for memory only.
|
||||||
|
KnownHostsWrite string
|
||||||
|
// AgentSocket is the ssh-agent socket. "" means $SSH_AUTH_SOCK; "-"
|
||||||
|
// disables the agent.
|
||||||
|
AgentSocket string
|
||||||
|
// DefaultIdentityFiles are tried when the endpoint does not set
|
||||||
|
// IdentitiesOnly. nil means Home/.ssh/id_{ed25519,ecdsa,rsa}.
|
||||||
|
DefaultIdentityFiles []string
|
||||||
|
// Warn receives non-fatal problems (host key kept in memory only,
|
||||||
|
// unreadable identity file). May be nil.
|
||||||
|
Warn func(msg string)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (o DialOptions) withDefaults() DialOptions {
|
||||||
|
if o.HandshakeTimeout <= 0 {
|
||||||
|
o.HandshakeTimeout = DefaultHandshakeTimeout
|
||||||
|
}
|
||||||
|
if o.Home == "" {
|
||||||
|
o.Home, _ = os.UserHomeDir()
|
||||||
|
}
|
||||||
|
ssh := filepath.Join(o.Home, ".ssh")
|
||||||
|
if o.KnownHostsFiles == nil {
|
||||||
|
o.KnownHostsFiles = []string{filepath.Join(ssh, "known_hosts"), "/etc/ssh/ssh_known_hosts"}
|
||||||
|
}
|
||||||
|
switch o.KnownHostsWrite {
|
||||||
|
case "":
|
||||||
|
if len(o.KnownHostsFiles) > 0 {
|
||||||
|
o.KnownHostsWrite = o.KnownHostsFiles[0]
|
||||||
|
}
|
||||||
|
case "-":
|
||||||
|
o.KnownHostsWrite = ""
|
||||||
|
}
|
||||||
|
switch o.AgentSocket {
|
||||||
|
case "":
|
||||||
|
o.AgentSocket = os.Getenv("SSH_AUTH_SOCK")
|
||||||
|
case "-":
|
||||||
|
o.AgentSocket = ""
|
||||||
|
}
|
||||||
|
if o.DefaultIdentityFiles == nil {
|
||||||
|
for _, n := range []string{"id_ed25519", "id_ecdsa", "id_rsa"} {
|
||||||
|
o.DefaultIdentityFiles = append(o.DefaultIdentityFiles, filepath.Join(ssh, n))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// dialer establishes connections. One per Pool (i.e. per process): it owns
|
||||||
|
// the shared agent connection and the session-trusted host keys.
|
||||||
|
type dialer struct {
|
||||||
|
opts DialOptions
|
||||||
|
hosts *knownHosts
|
||||||
|
agent *agentConn
|
||||||
|
dials atomic.Int64 // successful TCP connects, for tests
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDialer(o DialOptions) *dialer {
|
||||||
|
o = o.withDefaults()
|
||||||
|
return &dialer{
|
||||||
|
opts: o,
|
||||||
|
hosts: newKnownHosts(o.KnownHostsFiles, o.KnownHostsWrite, o.Warn),
|
||||||
|
agent: &agentConn{sock: o.AgentSocket},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *dialer) close() { d.agent.close() }
|
||||||
|
|
||||||
|
func (d *dialer) warnf(format string, args ...any) {
|
||||||
|
if d.opts.Warn != nil {
|
||||||
|
d.opts.Warn(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// link is one established generation of a connection.
|
||||||
|
type link struct {
|
||||||
|
ssh *ssh.Client
|
||||||
|
sftp *sftp.Client
|
||||||
|
id HostIdentity
|
||||||
|
serverVersion string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *link) close() {
|
||||||
|
l.sftp.Close()
|
||||||
|
l.ssh.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// deadlineGate applies the handshake deadline to the raw connection and
|
||||||
|
// pauses it while the Prompter waits for the user.
|
||||||
|
type deadlineGate struct {
|
||||||
|
nc net.Conn
|
||||||
|
timeout time.Duration
|
||||||
|
mu sync.Mutex
|
||||||
|
done bool // handshake finished: never touch deadlines again
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *deadlineGate) arm() {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
if !g.done {
|
||||||
|
g.nc.SetDeadline(time.Now().Add(g.timeout))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *deadlineGate) finish() {
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
g.done = true
|
||||||
|
g.nc.SetDeadline(time.Time{})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *deadlineGate) prompt(fn func() error) error {
|
||||||
|
g.mu.Lock()
|
||||||
|
if !g.done {
|
||||||
|
g.nc.SetDeadline(time.Time{})
|
||||||
|
}
|
||||||
|
g.mu.Unlock()
|
||||||
|
defer g.arm()
|
||||||
|
return fn()
|
||||||
|
}
|
||||||
|
|
||||||
|
// sftpOptions: concurrent reads/writes so a transfer is not one packet per
|
||||||
|
// RTT (N-P1-6).
|
||||||
|
var sftpOptions = []sftp.ClientOption{
|
||||||
|
sftp.UseConcurrentWrites(true),
|
||||||
|
sftp.UseConcurrentReads(true),
|
||||||
|
sftp.MaxConcurrentRequestsPerFile(64),
|
||||||
|
}
|
||||||
|
|
||||||
|
// dial connects, verifies the host key, authenticates and starts SFTP.
|
||||||
|
// Cancelling ctx closes the socket at once; if the handshake still
|
||||||
|
// completes, the late client is closed here, never leaked (N-P1-3).
|
||||||
|
func (d *dialer) dial(ctx context.Context, ep Endpoint) (*link, error) {
|
||||||
|
timeout := d.opts.HandshakeTimeout
|
||||||
|
tcpTimeout := timeout
|
||||||
|
if ep.ConnectTimeout > 0 && ep.ConnectTimeout < tcpTimeout {
|
||||||
|
tcpTimeout = ep.ConnectTimeout
|
||||||
|
}
|
||||||
|
addr := ep.Addr()
|
||||||
|
nd := net.Dialer{Timeout: tcpTimeout}
|
||||||
|
nc, err := nd.DialContext(ctx, "tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err())
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("connect %s: %w", ep.Label(), err)
|
||||||
|
}
|
||||||
|
d.dials.Add(1)
|
||||||
|
gate := &deadlineGate{nc: nc, timeout: timeout}
|
||||||
|
gate.arm()
|
||||||
|
stop := context.AfterFunc(ctx, func() { nc.Close() })
|
||||||
|
|
||||||
|
var idMu sync.Mutex
|
||||||
|
var id HostIdentity
|
||||||
|
onKey := func(h HostIdentity) {
|
||||||
|
idMu.Lock()
|
||||||
|
defer idMu.Unlock()
|
||||||
|
if id.KeyType == "" {
|
||||||
|
id = h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg := &ssh.ClientConfig{
|
||||||
|
User: ep.User,
|
||||||
|
Auth: d.authMethods(ctx, ep, gate.prompt),
|
||||||
|
HostKeyCallback: d.hosts.callback(ctx, ep, d.opts.Prompter, gate.prompt, onKey),
|
||||||
|
HostKeyAlgorithms: d.hosts.algorithms(addr),
|
||||||
|
}
|
||||||
|
fail := func(err error) (*link, error) {
|
||||||
|
stop()
|
||||||
|
nc.Close()
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err())
|
||||||
|
}
|
||||||
|
if errors.Is(err, os.ErrDeadlineExceeded) {
|
||||||
|
return nil, fmt.Errorf("connect %s: %w after %v", ep.Label(), ErrHandshakeTimeout, timeout)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("connect %s: %w", ep.Label(), err)
|
||||||
|
}
|
||||||
|
sc, chans, reqs, err := ssh.NewClientConn(nc, addr, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fail(err)
|
||||||
|
}
|
||||||
|
client := ssh.NewClient(sc, chans, reqs)
|
||||||
|
sc2, err := sftp.NewClient(client, sftpOptions...)
|
||||||
|
if err != nil {
|
||||||
|
client.Close()
|
||||||
|
return fail(fmt.Errorf("sftp: %w", err))
|
||||||
|
}
|
||||||
|
l := &link{ssh: client, sftp: sc2, serverVersion: string(client.ServerVersion())}
|
||||||
|
if !stop() {
|
||||||
|
// ctx fired while we were finishing: the caller is gone.
|
||||||
|
l.close()
|
||||||
|
return nil, fmt.Errorf("connect %s: %w", ep.Label(), ctx.Err())
|
||||||
|
}
|
||||||
|
gate.finish()
|
||||||
|
idMu.Lock()
|
||||||
|
l.id = id
|
||||||
|
idMu.Unlock()
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
452
internal/ssh/conn/dial_test.go
Normal file
452
internal/ssh/conn/dial_test.go
Normal file
|
|
@ -0,0 +1,452 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/rsa"
|
||||||
|
"errors"
|
||||||
|
"math/big"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// N-P1-3: the server accepts TCP and then goes silent; the dial must fail
|
||||||
|
// within HandshakeTimeout (+1s slack), not hang.
|
||||||
|
func TestHandshakeTimeout(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := sshtest.NewProxy(t, srv.Addr)
|
||||||
|
px.Freeze(true)
|
||||||
|
const timeout = 300 * time.Millisecond
|
||||||
|
d := e.dialer(DialOptions{HandshakeTimeout: timeout})
|
||||||
|
start := time.Now()
|
||||||
|
l, err := d.dial(context.Background(), endpointFor(px.Addr, srv.Password))
|
||||||
|
el := time.Since(start)
|
||||||
|
if err == nil {
|
||||||
|
l.close()
|
||||||
|
t.Fatal("dial through a frozen proxy succeeded")
|
||||||
|
}
|
||||||
|
if !errors.Is(err, ErrHandshakeTimeout) {
|
||||||
|
t.Errorf("err = %v, want ErrHandshakeTimeout", err)
|
||||||
|
}
|
||||||
|
if el > timeout+time.Second {
|
||||||
|
t.Errorf("dial took %v, want <= %v", el, timeout+time.Second)
|
||||||
|
}
|
||||||
|
px.Freeze(false)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P1-3: cancelling ctx mid-handshake returns at once; once the link
|
||||||
|
// unfreezes nothing is left behind (no client, no goroutines).
|
||||||
|
func TestDialCancelClosesLateClient(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := sshtest.NewProxy(t, srv.Addr)
|
||||||
|
px.Freeze(true)
|
||||||
|
d := e.dialer(DialOptions{HandshakeTimeout: 10 * time.Second})
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
time.AfterFunc(100*time.Millisecond, cancel)
|
||||||
|
start := time.Now()
|
||||||
|
l, err := d.dial(ctx, endpointFor(px.Addr, srv.Password))
|
||||||
|
if err == nil {
|
||||||
|
l.close()
|
||||||
|
t.Fatal("cancelled dial succeeded")
|
||||||
|
}
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("err = %v, want context.Canceled", err)
|
||||||
|
}
|
||||||
|
if el := time.Since(start); el > time.Second {
|
||||||
|
t.Errorf("cancel took %v", el)
|
||||||
|
}
|
||||||
|
px.Freeze(false)
|
||||||
|
// The proxy forwards the buffered handshake now; the server must see
|
||||||
|
// the client gone and drop the connection.
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// A prompt answered after the caller gave up must not produce a live client.
|
||||||
|
func TestDialCancelDuringPrompt(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) {
|
||||||
|
cancel()
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
return AcceptOnce, nil // ignores ctx on purpose
|
||||||
|
}}
|
||||||
|
d := e.dialer(DialOptions{Prompter: p})
|
||||||
|
l, err := d.dial(ctx, endpointFor(srv.Addr, srv.Password))
|
||||||
|
if err == nil {
|
||||||
|
l.close()
|
||||||
|
t.Fatal("dial succeeded after cancel")
|
||||||
|
}
|
||||||
|
if !errors.Is(err, context.Canceled) {
|
||||||
|
t.Errorf("err = %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// The deadline is paused while the Prompter waits for the user.
|
||||||
|
func TestHandshakeDeadlinePausedDuringPrompt(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) {
|
||||||
|
time.Sleep(400 * time.Millisecond)
|
||||||
|
return AcceptOnce, nil
|
||||||
|
}}
|
||||||
|
d := e.dialer(DialOptions{Prompter: p, HandshakeTimeout: 200 * time.Millisecond})
|
||||||
|
l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("slow user answer must not time out the handshake: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ported from the testbed (B9), N-P1-4: known_hosts has only the ed25519
|
||||||
|
// key, the server offers ed25519+ECDSA; Go would pick ECDSA and raise a
|
||||||
|
// false "host key changed".
|
||||||
|
func TestHostKeyAlgoMismatch(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
ed, ec := sshtest.GenKeys(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ec, ed}})
|
||||||
|
e.trust(srv.Addr, ed.PublicKey())
|
||||||
|
d := e.dialer(DialOptions{})
|
||||||
|
l, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("connect with a valid known ed25519 key: %v", err)
|
||||||
|
}
|
||||||
|
defer l.close()
|
||||||
|
if want := IdentityOf(ed.PublicKey()); l.id != want {
|
||||||
|
t.Errorf("identity = %+v, want %+v", l.id, want)
|
||||||
|
}
|
||||||
|
if got := d.hosts.algorithms(srv.Addr); len(got) != 1 || got[0] != ssh.KeyAlgoED25519 {
|
||||||
|
t.Errorf("algorithms = %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHostKeyAlgorithmsRSA(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
_, ec := sshtest.GenKeys(t)
|
||||||
|
rsaPub, err := ssh.ParsePublicKey(testRSAPublicKeyWire(t))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e.trust("[h]:2222", rsaPub, ec.PublicKey())
|
||||||
|
d := e.dialer(DialOptions{})
|
||||||
|
got := d.hosts.algorithms("h:2222")
|
||||||
|
want := []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256, ssh.KeyAlgoRSA, ssh.KeyAlgoECDSA256}
|
||||||
|
if strings.Join(got, ",") != strings.Join(want, ",") {
|
||||||
|
t.Errorf("algorithms = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
if got := d.hosts.algorithms("other:22"); got != nil {
|
||||||
|
t.Errorf("unknown host algorithms = %v, want nil", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestHostKeyChangedRejected(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
ed, _ := sshtest.GenKeys(t)
|
||||||
|
stale, _ := sshtest.GenKeys(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{HostKeys: []ssh.Signer{ed}})
|
||||||
|
e.trust(srv.Addr, stale.PublicKey())
|
||||||
|
before, _ := os.ReadFile(e.kh)
|
||||||
|
|
||||||
|
// No prompter: refused.
|
||||||
|
d := e.dialer(DialOptions{})
|
||||||
|
_, err := d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
|
||||||
|
if !errors.Is(err, ErrHostKeyChanged) {
|
||||||
|
t.Fatalf("err = %v, want ErrHostKeyChanged", err)
|
||||||
|
}
|
||||||
|
var hke *HostKeyError
|
||||||
|
if !errors.As(err, &hke) || !hke.Changed || len(hke.Known) != 1 || hke.Known[0] != IdentityOf(stale.PublicKey()) {
|
||||||
|
t.Errorf("HostKeyError = %+v", hke)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prompter told about the change, rejects.
|
||||||
|
p := &fakePrompter{}
|
||||||
|
d = e.dialer(DialOptions{Prompter: p})
|
||||||
|
_, err = d.dial(context.Background(), endpointFor(srv.Addr, srv.Password))
|
||||||
|
if !errors.Is(err, ErrHostKeyChanged) {
|
||||||
|
t.Fatalf("err = %v, want ErrHostKeyChanged", err)
|
||||||
|
}
|
||||||
|
if len(p.hostKeys) != 1 || !p.hostKeys[0].changed {
|
||||||
|
t.Errorf("prompter calls = %+v, want one with changed=true", p.hostKeys)
|
||||||
|
}
|
||||||
|
after, _ := os.ReadFile(e.kh)
|
||||||
|
if !bytes.Equal(before, after) {
|
||||||
|
t.Error("known_hosts modified on a rejected changed key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-14: an unknown host goes to the Prompter instead of silent TOFU.
|
||||||
|
func TestUnknownHostAsksPrompter(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := sshtest.Start(t, sshtest.Options{})
|
||||||
|
ep := endpointFor(srv.Addr, srv.Password)
|
||||||
|
|
||||||
|
t.Run("Reject", func(t *testing.T) {
|
||||||
|
p := &fakePrompter{}
|
||||||
|
_, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
|
||||||
|
if !errors.Is(err, ErrHostKeyRejected) {
|
||||||
|
t.Fatalf("err = %v, want ErrHostKeyRejected", err)
|
||||||
|
}
|
||||||
|
if n, _, _, _ := p.counts(); n != 1 || p.hostKeys[0].changed || len(p.hostKeys[0].known) != 0 {
|
||||||
|
t.Errorf("prompter calls = %+v", p.hostKeys)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(e.kh); !os.IsNotExist(err) {
|
||||||
|
t.Error("known_hosts written on Reject")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("NoPrompter", func(t *testing.T) {
|
||||||
|
_, err := e.dialer(DialOptions{}).dial(context.Background(), ep)
|
||||||
|
if !errors.Is(err, ErrHostKeyRejected) {
|
||||||
|
t.Fatalf("err = %v, want ErrHostKeyRejected", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("AcceptOnce", func(t *testing.T) {
|
||||||
|
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptOnce, nil }}
|
||||||
|
d := e.dialer(DialOptions{Prompter: p})
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
l, err := d.dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
}
|
||||||
|
if n, _, _, _ := p.counts(); n != 1 {
|
||||||
|
t.Errorf("asked %d times, want once per process", n)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(e.kh); !os.IsNotExist(err) {
|
||||||
|
t.Error("known_hosts written on AcceptOnce")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("AcceptAndSave", func(t *testing.T) {
|
||||||
|
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }}
|
||||||
|
l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
data, err := os.ReadFile(e.kh)
|
||||||
|
if err != nil || !strings.Contains(string(data), "127.0.0.1") {
|
||||||
|
t.Fatalf("known_hosts = %q, %v", data, err)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(e.kh); fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Errorf("known_hosts mode %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
// A fresh process (dialer) trusts it without asking.
|
||||||
|
l, err = e.dialer(DialOptions{}).dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("saved key not trusted: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("MemoryOnlyWarns", func(t *testing.T) {
|
||||||
|
os.Remove(e.kh)
|
||||||
|
var warns []string
|
||||||
|
var mu sync.Mutex
|
||||||
|
p := &fakePrompter{hostKey: func(context.Context, bool) (HostKeyDecision, error) { return AcceptAndSave, nil }}
|
||||||
|
d := e.dialer(DialOptions{Prompter: p, KnownHostsWrite: "-", Warn: func(s string) {
|
||||||
|
mu.Lock()
|
||||||
|
warns = append(warns, s)
|
||||||
|
mu.Unlock()
|
||||||
|
}})
|
||||||
|
l, err := d.dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
if len(warns) != 1 || !strings.Contains(warns[0], "session only") {
|
||||||
|
t.Errorf("warnings = %q", warns)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(e.kh); !os.IsNotExist(err) {
|
||||||
|
t.Error("known_hosts written in memory-only mode")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-2: a rejected IdentityFile used to end authentication; the agent
|
||||||
|
// must still be tried.
|
||||||
|
func TestAuthFallbackToAgentAfterIdentityRejected(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
agentPriv, agentSigner := newKey(t)
|
||||||
|
otherPriv, _ := newKey(t)
|
||||||
|
idPath := filepath.Join(e.home, ".ssh", "id_other")
|
||||||
|
writeKey(t, idPath, otherPriv, "")
|
||||||
|
ag := startAgent(t, agentPriv)
|
||||||
|
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{agentSigner.PublicKey()}})
|
||||||
|
d := e.dialer(DialOptions{AgentSocket: ag.sock})
|
||||||
|
ep := endpointFor(srv.Addr, "")
|
||||||
|
ep.IdentityFiles = []string{idPath, filepath.Join(e.home, ".ssh", "missing")}
|
||||||
|
l, err := d.dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("agent key not tried after the identity file was rejected: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
|
||||||
|
// IdentitiesOnly: the agent key is not offered.
|
||||||
|
ep.IdentitiesOnly = true
|
||||||
|
if _, err := d.dial(context.Background(), ep); err == nil {
|
||||||
|
t.Fatal("IdentitiesOnly must not offer unrelated agent keys")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAuthDefaultIdentityAndPasswordFallback(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
priv, signer := newKey(t)
|
||||||
|
writeKey(t, filepath.Join(e.home, ".ssh", "id_ed25519"), priv, "")
|
||||||
|
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}})
|
||||||
|
l, err := e.dialer(DialOptions{}).dial(context.Background(), endpointFor(srv.Addr, ""))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("default identity: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
|
||||||
|
// Password server: keys are offered and rejected, the prompter's password works.
|
||||||
|
srv2 := e.startTrusted(sshtest.Options{Password: "s3cret"})
|
||||||
|
p := &fakePrompter{password: func(context.Context) (string, error) { return "s3cret", nil }}
|
||||||
|
l, err = e.dialer(DialOptions{Prompter: p}).dial(context.Background(), endpointFor(srv2.Addr, ""))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("prompted password: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
if _, pw, _, _ := p.counts(); pw != 1 {
|
||||||
|
t.Errorf("password asked %d times", pw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-2: keyboard-interactive questions reach the Prompter as they are
|
||||||
|
// (the old code answered every question, 2FA included, with the password).
|
||||||
|
func TestKeyboardInteractiveUsesPrompter(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
qs := []string{"Password: ", "Verification code: "}
|
||||||
|
echo := []bool{false, true}
|
||||||
|
addr, hostKey := kiServer(t, qs, echo, []string{"pw", "123456"})
|
||||||
|
e.trust(addr, hostKey)
|
||||||
|
p := &fakePrompter{ki: func([]string) ([]string, error) { return []string{"pw", "123456"}, nil }}
|
||||||
|
ep := endpointFor(addr, "pw") // the stored password must not answer the 2FA question
|
||||||
|
l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("keyboard-interactive: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
if len(p.kiCalls) != 1 || strings.Join(p.kiCalls[0], "|") != strings.Join(qs, "|") ||
|
||||||
|
p.kiEcho[0][0] || !p.kiEcho[0][1] {
|
||||||
|
t.Errorf("prompter saw %q echo %v", p.kiCalls, p.kiEcho)
|
||||||
|
}
|
||||||
|
if !strings.Contains(p.kiInstr[0], "Two factors please") {
|
||||||
|
t.Errorf("instruction = %q", p.kiInstr[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// A lone hidden question is answered with the stored password.
|
||||||
|
addr2, hostKey2 := kiServer(t, []string{"Password: "}, []bool{false}, []string{"pw"})
|
||||||
|
e.trust(addr2, hostKey2)
|
||||||
|
p2 := &fakePrompter{}
|
||||||
|
l, err = e.dialer(DialOptions{Prompter: p2}).dial(context.Background(), endpointFor(addr2, "pw"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("stored password via keyboard-interactive: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
if _, _, ki, _ := p2.counts(); ki != 0 {
|
||||||
|
t.Errorf("prompter asked %d times", ki)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-1: one agent connection per process, not one per connect.
|
||||||
|
func TestAgentConnectionShared(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
priv, signer := newKey(t)
|
||||||
|
ag := startAgent(t, priv)
|
||||||
|
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{signer.PublicKey()}})
|
||||||
|
d := newDialer(DialOptions{Home: e.home, AgentSocket: ag.sock, KnownHostsFiles: []string{e.kh}})
|
||||||
|
ep := endpointFor(srv.Addr, "")
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make(chan error, 6)
|
||||||
|
for i := 0; i < 6; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
l, err := d.dial(context.Background(), ep)
|
||||||
|
if err == nil {
|
||||||
|
l.close()
|
||||||
|
}
|
||||||
|
errs <- err
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
close(errs)
|
||||||
|
for err := range errs {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if n := ag.accepts.Load(); n != 1 {
|
||||||
|
t.Errorf("agent connections = %d, want 1", n)
|
||||||
|
}
|
||||||
|
d.close()
|
||||||
|
waitFor(t, 2*time.Second, "agent connection closed", func() bool { return ag.active.Load() == 0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
// An encrypted key is decrypted only when the server accepts it.
|
||||||
|
func TestPassphraseAskedLazily(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
accPriv, accSigner := newKey(t)
|
||||||
|
rejPriv, _ := newKey(t)
|
||||||
|
rej := filepath.Join(e.home, ".ssh", "id_rejected")
|
||||||
|
acc := filepath.Join(e.home, ".ssh", "id_accepted")
|
||||||
|
writeKey(t, rej, rejPriv, "one")
|
||||||
|
writeKey(t, acc, accPriv, "two")
|
||||||
|
srv := e.startTrusted(sshtest.Options{AuthorizedKeys: []ssh.PublicKey{accSigner.PublicKey()}})
|
||||||
|
tries := 0
|
||||||
|
p := &fakePrompter{passphrase: func(path string) ([]byte, error) {
|
||||||
|
tries++
|
||||||
|
if tries == 1 {
|
||||||
|
return []byte("wrong"), nil
|
||||||
|
}
|
||||||
|
return []byte("two"), nil
|
||||||
|
}}
|
||||||
|
ep := endpointFor(srv.Addr, "")
|
||||||
|
ep.IdentityFiles = []string{rej, acc}
|
||||||
|
l, err := e.dialer(DialOptions{Prompter: p}).dial(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("encrypted key: %v", err)
|
||||||
|
}
|
||||||
|
l.close()
|
||||||
|
for _, ph := range p.phrases {
|
||||||
|
if ph != acc {
|
||||||
|
t.Errorf("passphrase asked for %s (server never accepted it)", ph)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(p.phrases) != 2 {
|
||||||
|
t.Errorf("passphrase asked %d times, want 2 (one wrong attempt)", len(p.phrases))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// testRSAPublicKeyWire returns an RSA public key in wire format. Only the
|
||||||
|
// type matters here, so the modulus is arbitrary (no slow key generation).
|
||||||
|
func testRSAPublicKeyWire(t *testing.T) []byte {
|
||||||
|
t.Helper()
|
||||||
|
n := new(big.Int).Lsh(big.NewInt(1), 2047)
|
||||||
|
n.Add(n, big.NewInt(12345))
|
||||||
|
pub, err := ssh.NewPublicKey(&rsa.PublicKey{N: n, E: 65537})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return pub.Marshal()
|
||||||
|
}
|
||||||
195
internal/ssh/conn/exec.go
Normal file
195
internal/ssh/conn/exec.go
Normal file
|
|
@ -0,0 +1,195 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultExecLimit caps the captured stdout of Exec (§3.4).
|
||||||
|
const DefaultExecLimit = 1 << 20
|
||||||
|
|
||||||
|
// stderrLimit caps the stderr kept for ExitError.
|
||||||
|
const stderrLimit = 4 << 10
|
||||||
|
|
||||||
|
// ErrOutputLimit: the command printed more than the limit; it was killed
|
||||||
|
// and the output truncated (N-P2-15).
|
||||||
|
var ErrOutputLimit = errors.New("command output exceeds limit")
|
||||||
|
|
||||||
|
// ExitError is a non-zero exit status.
|
||||||
|
type ExitError struct {
|
||||||
|
Code int
|
||||||
|
Stderr string // first 4 KiB
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ExitError) Error() string {
|
||||||
|
msg := strings.TrimSpace(e.Stderr)
|
||||||
|
if msg == "" {
|
||||||
|
return fmt.Sprintf("remote command exited with status %d", e.Code)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("remote command exited with status %d: %s", e.Code, msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quote joins argv into a POSIX shell command line, quoting every argument
|
||||||
|
// that is not made of safe characters only.
|
||||||
|
func Quote(argv []string) string {
|
||||||
|
parts := make([]string, len(argv))
|
||||||
|
for i, a := range argv {
|
||||||
|
parts[i] = quoteArg(a)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func quoteArg(a string) string {
|
||||||
|
if a == "" {
|
||||||
|
return "''"
|
||||||
|
}
|
||||||
|
safe := true
|
||||||
|
for _, r := range a {
|
||||||
|
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_./=:,+@%", r)) {
|
||||||
|
safe = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if safe {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return "'" + strings.ReplaceAll(a, "'", `'\''`) + "'"
|
||||||
|
}
|
||||||
|
|
||||||
|
// limitWriter keeps at most limit bytes and calls overflow once when more
|
||||||
|
// arrive.
|
||||||
|
type limitWriter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
buf bytes.Buffer
|
||||||
|
limit int64
|
||||||
|
over bool
|
||||||
|
overflow func()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *limitWriter) Write(p []byte) (int, error) {
|
||||||
|
w.mu.Lock()
|
||||||
|
defer w.mu.Unlock()
|
||||||
|
if w.over {
|
||||||
|
return 0, ErrOutputLimit
|
||||||
|
}
|
||||||
|
room := w.limit - int64(w.buf.Len())
|
||||||
|
if int64(len(p)) <= room {
|
||||||
|
return w.buf.Write(p)
|
||||||
|
}
|
||||||
|
w.buf.Write(p[:room])
|
||||||
|
w.over = true
|
||||||
|
if w.overflow != nil {
|
||||||
|
go w.overflow()
|
||||||
|
}
|
||||||
|
return int(room), ErrOutputLimit
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *limitWriter) bytes() ([]byte, bool) {
|
||||||
|
w.mu.Lock()
|
||||||
|
defer w.mu.Unlock()
|
||||||
|
return append([]byte(nil), w.buf.Bytes()...), w.over
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exec runs argv on the server (arguments are shell-quoted) and returns its
|
||||||
|
// stdout (at most limit bytes; <= 0 means DefaultExecLimit) and exit code.
|
||||||
|
// A non-zero exit returns *ExitError along with the code. Cancelling ctx
|
||||||
|
// sends SIGKILL and closes the session immediately (N-P1-7); output over
|
||||||
|
// the limit kills the command and returns ErrOutputLimit with the
|
||||||
|
// truncated output. Code is -1 when there is no exit status.
|
||||||
|
func (c *Conn) Exec(ctx context.Context, argv []string, limit int64) ([]byte, int, error) {
|
||||||
|
if len(argv) == 0 {
|
||||||
|
return nil, -1, errors.New("exec: empty command")
|
||||||
|
}
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = DefaultExecLimit
|
||||||
|
}
|
||||||
|
client, err := c.SSH()
|
||||||
|
if err != nil {
|
||||||
|
return nil, -1, err
|
||||||
|
}
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return nil, -1, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
mu sync.Mutex
|
||||||
|
sess *ssh.Session
|
||||||
|
killed bool
|
||||||
|
)
|
||||||
|
kill := func() {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
killed = true
|
||||||
|
if sess != nil {
|
||||||
|
sess.Signal(ssh.SIGKILL)
|
||||||
|
sess.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stdout := &limitWriter{limit: limit, overflow: kill}
|
||||||
|
stderr := &limitWriter{limit: stderrLimit}
|
||||||
|
type result struct{ err error }
|
||||||
|
done := make(chan result, 1)
|
||||||
|
go func() {
|
||||||
|
s, err := client.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
done <- result{c.MapErr(err)}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
if killed {
|
||||||
|
mu.Unlock()
|
||||||
|
s.Close()
|
||||||
|
done <- result{context.Canceled}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sess = s
|
||||||
|
mu.Unlock()
|
||||||
|
defer s.Close()
|
||||||
|
s.Stdout, s.Stderr = stdout, stderr
|
||||||
|
done <- result{s.Run(Quote(argv))}
|
||||||
|
}()
|
||||||
|
|
||||||
|
var r result
|
||||||
|
select {
|
||||||
|
case r = <-done:
|
||||||
|
case <-ctx.Done():
|
||||||
|
kill()
|
||||||
|
return nil, -1, ctx.Err()
|
||||||
|
}
|
||||||
|
out, over := stdout.bytes()
|
||||||
|
if over {
|
||||||
|
return out, -1, fmt.Errorf("%w (%d bytes)", ErrOutputLimit, limit)
|
||||||
|
}
|
||||||
|
if r.err == nil {
|
||||||
|
return out, 0, nil
|
||||||
|
}
|
||||||
|
var ee *ssh.ExitError
|
||||||
|
if errors.As(r.err, &ee) {
|
||||||
|
se, _ := stderr.bytes()
|
||||||
|
return out, ee.ExitStatus(), &ExitError{Code: ee.ExitStatus(), Stderr: string(se)}
|
||||||
|
}
|
||||||
|
return out, -1, c.MapErr(r.err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecSupported reports whether the server runs commands (false for
|
||||||
|
// `ForceCommand internal-sftp`). Probed with `true`; only a definite answer
|
||||||
|
// is cached (a cancelled or lost probe is retried next time).
|
||||||
|
func (c *Conn) ExecSupported(ctx context.Context) bool {
|
||||||
|
c.execMu.Lock()
|
||||||
|
defer c.execMu.Unlock()
|
||||||
|
if c.execKnown {
|
||||||
|
return c.execOK
|
||||||
|
}
|
||||||
|
_, code, err := c.Exec(ctx, []string{"true"}, 64)
|
||||||
|
if ctx.Err() != nil || errors.Is(err, ErrConnLost) || errors.Is(err, ErrClosed) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
c.execKnown, c.execOK = true, err == nil && code == 0
|
||||||
|
return c.execOK
|
||||||
|
}
|
||||||
401
internal/ssh/conn/helpers_test.go
Normal file
401
internal/ssh/conn/helpers_test.go
Normal file
|
|
@ -0,0 +1,401 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
"golang.org/x/crypto/ssh/agent"
|
||||||
|
"golang.org/x/crypto/ssh/knownhosts"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the
|
||||||
|
// goroutine count returns to the baseline within ±2.
|
||||||
|
func noLeak(t *testing.T, fn func(t *testing.T)) {
|
||||||
|
t.Helper()
|
||||||
|
runtime.GC()
|
||||||
|
base := runtime.NumGoroutine()
|
||||||
|
t.Run("body", fn)
|
||||||
|
deadline := time.Now().Add(5 * time.Second)
|
||||||
|
var n int
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
n = runtime.NumGoroutine()
|
||||||
|
if n <= base+2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
buf := make([]byte, 1<<20)
|
||||||
|
buf = buf[:runtime.Stack(buf, true)]
|
||||||
|
t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitFor polls cond until it holds or d elapses.
|
||||||
|
func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(d)
|
||||||
|
for !cond() {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("timed out after %v waiting for %s", d, what)
|
||||||
|
}
|
||||||
|
time.Sleep(5 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// env is an isolated HOME with helpers to dial the in-process server.
|
||||||
|
type env struct {
|
||||||
|
t *testing.T
|
||||||
|
home string
|
||||||
|
kh string // ~/.ssh/known_hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
func newEnv(t *testing.T) *env {
|
||||||
|
t.Helper()
|
||||||
|
home := sshtest.IsolatedHome(t)
|
||||||
|
return &env{t: t, home: home, kh: filepath.Join(home, ".ssh", "known_hosts")}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dialer returns a dialer rooted at the env HOME; the agent is disabled
|
||||||
|
// unless o.AgentSocket is set.
|
||||||
|
func (e *env) dialer(o DialOptions) *dialer {
|
||||||
|
if o.Home == "" {
|
||||||
|
o.Home = e.home
|
||||||
|
}
|
||||||
|
if o.AgentSocket == "" {
|
||||||
|
o.AgentSocket = "-"
|
||||||
|
}
|
||||||
|
if o.KnownHostsFiles == nil {
|
||||||
|
o.KnownHostsFiles = []string{e.kh}
|
||||||
|
}
|
||||||
|
d := newDialer(o)
|
||||||
|
e.t.Cleanup(d.close)
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
// trust writes known_hosts lines for addr.
|
||||||
|
func (e *env) trust(addr string, keys ...ssh.PublicKey) {
|
||||||
|
e.t.Helper()
|
||||||
|
var data []byte
|
||||||
|
for _, k := range keys {
|
||||||
|
data = append(data, knownhosts.Line([]string{knownhosts.Normalize(addr)}, k)+"\n"...)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(e.kh, data, 0o600); err != nil {
|
||||||
|
e.t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func endpointFor(addr, password string) Endpoint {
|
||||||
|
host, port, _ := net.SplitHostPort(addr)
|
||||||
|
p, _ := strconv.Atoi(port)
|
||||||
|
return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password}
|
||||||
|
}
|
||||||
|
|
||||||
|
// proxy starts a proxy in front of srv and trusts srv's keys at the proxy
|
||||||
|
// address too.
|
||||||
|
func (e *env) proxy(srv *sshtest.Server) *sshtest.Proxy {
|
||||||
|
px := sshtest.NewProxy(e.t, srv.Addr)
|
||||||
|
old, _ := os.ReadFile(e.kh)
|
||||||
|
var pubs []ssh.PublicKey
|
||||||
|
for _, k := range srv.HostKeys {
|
||||||
|
pubs = append(pubs, k.PublicKey())
|
||||||
|
}
|
||||||
|
e.trust(px.Addr, pubs...)
|
||||||
|
added, _ := os.ReadFile(e.kh)
|
||||||
|
if err := os.WriteFile(e.kh, append(old, added...), 0o600); err != nil {
|
||||||
|
e.t.Fatal(err)
|
||||||
|
}
|
||||||
|
return px
|
||||||
|
}
|
||||||
|
|
||||||
|
// startTrusted starts a server whose host keys are in known_hosts.
|
||||||
|
func (e *env) startTrusted(o sshtest.Options) *sshtest.Server {
|
||||||
|
srv := sshtest.Start(e.t, o)
|
||||||
|
var pubs []ssh.PublicKey
|
||||||
|
for _, k := range srv.HostKeys {
|
||||||
|
pubs = append(pubs, k.PublicKey())
|
||||||
|
}
|
||||||
|
e.trust(srv.Addr, pubs...)
|
||||||
|
return srv
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *link) closeOnCleanup(t *testing.T) *link {
|
||||||
|
t.Cleanup(l.close)
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakePrompter records calls and answers with the configured functions.
|
||||||
|
type fakePrompter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
hostKeys []hostKeyCall
|
||||||
|
passwords int
|
||||||
|
kiCalls [][]string
|
||||||
|
kiEcho [][]bool
|
||||||
|
kiInstr []string
|
||||||
|
phrases []string
|
||||||
|
|
||||||
|
hostKey func(ctx context.Context, changed bool) (HostKeyDecision, error)
|
||||||
|
password func(ctx context.Context) (string, error)
|
||||||
|
ki func(qs []string) ([]string, error)
|
||||||
|
passphrase func(path string) ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type hostKeyCall struct {
|
||||||
|
id HostIdentity
|
||||||
|
known []HostIdentity
|
||||||
|
changed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *fakePrompter) HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
p.hostKeys = append(p.hostKeys, hostKeyCall{id, known, changed})
|
||||||
|
p.mu.Unlock()
|
||||||
|
if p.hostKey == nil {
|
||||||
|
return Reject, nil
|
||||||
|
}
|
||||||
|
return p.hostKey(ctx, changed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *fakePrompter) Password(ctx context.Context, ep Endpoint) (string, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
p.passwords++
|
||||||
|
p.mu.Unlock()
|
||||||
|
if p.password == nil {
|
||||||
|
return "", errors.New("no password")
|
||||||
|
}
|
||||||
|
return p.password(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *fakePrompter) KeyboardInteractive(ctx context.Context, ep Endpoint, instr string, qs []string, echo []bool) ([]string, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
p.kiCalls = append(p.kiCalls, append([]string(nil), qs...))
|
||||||
|
p.kiEcho = append(p.kiEcho, append([]bool(nil), echo...))
|
||||||
|
p.kiInstr = append(p.kiInstr, instr)
|
||||||
|
p.mu.Unlock()
|
||||||
|
if p.ki == nil {
|
||||||
|
return nil, errors.New("no answers")
|
||||||
|
}
|
||||||
|
return p.ki(qs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *fakePrompter) Passphrase(ctx context.Context, path string) ([]byte, error) {
|
||||||
|
p.mu.Lock()
|
||||||
|
p.phrases = append(p.phrases, path)
|
||||||
|
p.mu.Unlock()
|
||||||
|
if p.passphrase == nil {
|
||||||
|
return nil, errors.New("no passphrase")
|
||||||
|
}
|
||||||
|
return p.passphrase(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *fakePrompter) counts() (hostKeys, passwords, ki, phrases int) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return len(p.hostKeys), p.passwords, len(p.kiCalls), len(p.phrases)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newKey returns a fresh ed25519 private key and its signer.
|
||||||
|
func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) {
|
||||||
|
t.Helper()
|
||||||
|
_, priv, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s, err := ssh.NewSignerFromKey(priv)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return priv, s
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeKey stores priv in OpenSSH format (encrypted when passphrase != "").
|
||||||
|
func writeKey(t *testing.T, path string, priv ed25519.PrivateKey, passphrase string) {
|
||||||
|
t.Helper()
|
||||||
|
var blk *pem.Block
|
||||||
|
var err error
|
||||||
|
if passphrase == "" {
|
||||||
|
blk, err = ssh.MarshalPrivateKey(priv, "test")
|
||||||
|
} else {
|
||||||
|
blk, err = ssh.MarshalPrivateKeyWithPassphrase(priv, "test", []byte(passphrase))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, pem.EncodeToMemory(blk), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeAgent serves an in-memory keyring on a unix socket.
|
||||||
|
type fakeAgent struct {
|
||||||
|
sock string
|
||||||
|
accepts atomic.Int32
|
||||||
|
active atomic.Int32
|
||||||
|
}
|
||||||
|
|
||||||
|
func startAgent(t *testing.T, keys ...ed25519.PrivateKey) *fakeAgent {
|
||||||
|
t.Helper()
|
||||||
|
kr := agent.NewKeyring()
|
||||||
|
for _, k := range keys {
|
||||||
|
if err := kr.Add(agent.AddedKey{PrivateKey: k}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dir, err := os.MkdirTemp("", "agent")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||||
|
a := &fakeAgent{sock: filepath.Join(dir, "s")}
|
||||||
|
ln, err := net.Listen("unix", a.sock)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var mu sync.Mutex
|
||||||
|
var conns []net.Conn
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
c, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
a.accepts.Add(1)
|
||||||
|
a.active.Add(1)
|
||||||
|
mu.Lock()
|
||||||
|
conns = append(conns, c)
|
||||||
|
mu.Unlock()
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
defer a.active.Add(-1)
|
||||||
|
agent.ServeAgent(kr, c)
|
||||||
|
c.Close()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ln.Close()
|
||||||
|
mu.Lock()
|
||||||
|
for _, c := range conns {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
wg.Wait()
|
||||||
|
})
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
// kiServer is a minimal SSH server that only allows keyboard-interactive
|
||||||
|
// auth with the given questions; answers must equal want. It serves SFTP so
|
||||||
|
// the full dial path succeeds.
|
||||||
|
func kiServer(t *testing.T, questions []string, echo []bool, want []string) (string, ssh.PublicKey) {
|
||||||
|
t.Helper()
|
||||||
|
ed, _ := sshtest.GenKeys(t)
|
||||||
|
cfg := &ssh.ServerConfig{
|
||||||
|
KeyboardInteractiveCallback: func(_ ssh.ConnMetadata, ch ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
|
||||||
|
ans, err := ch("vcom-test", "Two factors please", questions, echo)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(ans) != len(want) {
|
||||||
|
return nil, errors.New("wrong answer count")
|
||||||
|
}
|
||||||
|
for i := range want {
|
||||||
|
if ans[i] != want[i] {
|
||||||
|
return nil, errors.New("wrong answer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cfg.AddHostKey(ed)
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
var mu sync.Mutex
|
||||||
|
var conns []net.Conn
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
for {
|
||||||
|
nc, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
conns = append(conns, nc)
|
||||||
|
mu.Unlock()
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
defer nc.Close()
|
||||||
|
sc, chans, reqs, err := ssh.NewServerConn(nc, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer sc.Close()
|
||||||
|
go ssh.DiscardRequests(reqs)
|
||||||
|
for nch := range chans {
|
||||||
|
ch, creqs, err := nch.Accept()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
defer ch.Close()
|
||||||
|
for req := range creqs {
|
||||||
|
if req.Type == "subsystem" {
|
||||||
|
req.Reply(true, nil)
|
||||||
|
srv, err := sftp.NewServer(ch)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
for range creqs {
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
srv.Serve()
|
||||||
|
srv.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Reply(false, nil)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
ln.Close()
|
||||||
|
mu.Lock()
|
||||||
|
for _, c := range conns {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
wg.Wait()
|
||||||
|
})
|
||||||
|
return ln.Addr().String(), ed.PublicKey()
|
||||||
|
}
|
||||||
272
internal/ssh/conn/hostkey.go
Normal file
272
internal/ssh/conn/hostkey.go
Normal file
|
|
@ -0,0 +1,272 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/rand"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
"golang.org/x/crypto/ssh/knownhosts"
|
||||||
|
|
||||||
|
"vcom/internal/atomicfile"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrHostKeyRejected: the key is unknown and the user (or the absence of
|
||||||
|
// a Prompter) refused it.
|
||||||
|
ErrHostKeyRejected = errors.New("host key rejected")
|
||||||
|
// ErrHostKeyChanged: known_hosts has a different key of the same type.
|
||||||
|
ErrHostKeyChanged = errors.New("REMOTE HOST IDENTIFICATION HAS CHANGED")
|
||||||
|
)
|
||||||
|
|
||||||
|
// HostKeyError describes a refused host key. It unwraps to
|
||||||
|
// ErrHostKeyChanged or ErrHostKeyRejected.
|
||||||
|
type HostKeyError struct {
|
||||||
|
Host string // host:port as checked against known_hosts
|
||||||
|
Identity HostIdentity
|
||||||
|
Known []HostIdentity
|
||||||
|
Changed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *HostKeyError) Error() string {
|
||||||
|
if e.Changed {
|
||||||
|
return fmt.Sprintf("%v for %s: server offers %s %s; remove the stale entry with `ssh-keygen -R %s` once the new key is verified",
|
||||||
|
ErrHostKeyChanged, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256, e.Host)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%v: %s %s %s", ErrHostKeyRejected, e.Host, e.Identity.KeyType, e.Identity.FingerprintSHA256)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *HostKeyError) Unwrap() error {
|
||||||
|
if e.Changed {
|
||||||
|
return ErrHostKeyChanged
|
||||||
|
}
|
||||||
|
return ErrHostKeyRejected
|
||||||
|
}
|
||||||
|
|
||||||
|
// probeKey is a throwaway key that is never in known_hosts: checking it
|
||||||
|
// makes knownhosts report every key it has for a host (KeyError.Want).
|
||||||
|
var probeKey = sync.OnceValue(func() ssh.PublicKey {
|
||||||
|
pub, _, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
k, err := ssh.NewPublicKey(pub)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
return k
|
||||||
|
})
|
||||||
|
|
||||||
|
// knownHosts verifies host keys against known_hosts files plus keys
|
||||||
|
// accepted during this process.
|
||||||
|
type knownHosts struct {
|
||||||
|
files []string // read in order
|
||||||
|
write string // AcceptAndSave appends here ("" = memory only)
|
||||||
|
warn func(string)
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
session map[string][]ssh.PublicKey // knownhosts.Normalize(host:port) -> keys
|
||||||
|
}
|
||||||
|
|
||||||
|
func newKnownHosts(files []string, write string, warn func(string)) *knownHosts {
|
||||||
|
return &knownHosts{files: files, write: write, warn: warn, session: map[string][]ssh.PublicKey{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// db parses the existing known_hosts files; nil when there are none.
|
||||||
|
func (h *knownHosts) db() (ssh.HostKeyCallback, error) {
|
||||||
|
var files []string
|
||||||
|
for _, f := range h.files {
|
||||||
|
if _, err := os.Stat(f); err == nil {
|
||||||
|
files = append(files, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(files) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return knownhosts.New(files...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// known returns every key on record for hostport (files, then session).
|
||||||
|
func (h *knownHosts) known(hostport string) []ssh.PublicKey {
|
||||||
|
var out []ssh.PublicKey
|
||||||
|
if cb, err := h.db(); err == nil && cb != nil {
|
||||||
|
var ke *knownhosts.KeyError
|
||||||
|
if err := cb(hostport, &net.TCPAddr{IP: net.IPv4zero}, probeKey()); errors.As(err, &ke) {
|
||||||
|
for _, k := range ke.Want {
|
||||||
|
out = append(out, k.Key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.mu.Lock()
|
||||||
|
out = append(out, h.session[knownhosts.Normalize(hostport)]...)
|
||||||
|
h.mu.Unlock()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// algorithms lists host key algorithms for the key types on record, so the
|
||||||
|
// server is asked for a key we can actually verify (N-P1-4: Go prefers ECDSA,
|
||||||
|
// OpenSSH usually records ed25519). nil means "library defaults".
|
||||||
|
func (h *knownHosts) algorithms(hostport string) []string {
|
||||||
|
var algos []string
|
||||||
|
seen := map[string]bool{}
|
||||||
|
add := func(a string) {
|
||||||
|
if !seen[a] {
|
||||||
|
seen[a] = true
|
||||||
|
algos = append(algos, a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, k := range h.known(hostport) {
|
||||||
|
switch t := k.Type(); t {
|
||||||
|
case ssh.KeyAlgoRSA:
|
||||||
|
add(ssh.KeyAlgoRSASHA512)
|
||||||
|
add(ssh.KeyAlgoRSASHA256)
|
||||||
|
add(ssh.KeyAlgoRSA)
|
||||||
|
default:
|
||||||
|
add(t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return algos
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *knownHosts) sessionHas(hostport string, key ssh.PublicKey) bool {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
for _, k := range h.session[knownhosts.Normalize(hostport)] {
|
||||||
|
if string(k.Marshal()) == string(key.Marshal()) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *knownHosts) remember(hostport string, key ssh.PublicKey) {
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
n := knownhosts.Normalize(hostport)
|
||||||
|
h.session[n] = append(h.session[n], key)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *knownHosts) warnf(format string, args ...any) {
|
||||||
|
if h.warn != nil {
|
||||||
|
h.warn(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// save appends a known_hosts line atomically (rewrite via temp copy). When
|
||||||
|
// the file belongs to another user (vcom under sudo) or cannot be written,
|
||||||
|
// the key is trusted for this process only and a warning is emitted
|
||||||
|
// (N-P2-14).
|
||||||
|
func (h *knownHosts) save(hostport string, key ssh.PublicKey) {
|
||||||
|
h.remember(hostport, key)
|
||||||
|
if h.write == "" {
|
||||||
|
h.warnf("host key for %s accepted for this session only (no known_hosts file configured)", hostport)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if foreignOwner(h.write) {
|
||||||
|
h.warnf("host key for %s accepted for this session only: %s belongs to another user", hostport, h.write)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
h.mu.Lock()
|
||||||
|
defer h.mu.Unlock()
|
||||||
|
if err := appendKnownHost(h.write, knownhosts.Line([]string{knownhosts.Normalize(hostport)}, key)); err != nil {
|
||||||
|
h.warnf("host key for %s accepted for this session only: %v", hostport, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func appendKnownHost(path, line string) error {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
perm := os.FileMode(0o600)
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fi, err := os.Stat(path); err == nil {
|
||||||
|
perm = fi.Mode().Perm()
|
||||||
|
}
|
||||||
|
if len(data) > 0 && data[len(data)-1] != '\n' {
|
||||||
|
data = append(data, '\n')
|
||||||
|
}
|
||||||
|
data = append(data, line+"\n"...)
|
||||||
|
return atomicfile.WriteFile(path, data, perm)
|
||||||
|
}
|
||||||
|
|
||||||
|
// callback builds the HostKeyCallback for one dial. prompt wraps Prompter
|
||||||
|
// calls so the handshake deadline is paused while the user decides; onKey
|
||||||
|
// sees every key the server presents (also on later re-keys).
|
||||||
|
func (h *knownHosts) callback(ctx context.Context, ep Endpoint, p Prompter, prompt func(func() error) error, onKey func(HostIdentity)) ssh.HostKeyCallback {
|
||||||
|
return func(hostname string, remote net.Addr, key ssh.PublicKey) error {
|
||||||
|
id := IdentityOf(key)
|
||||||
|
onKey(id)
|
||||||
|
if h.sessionHas(hostname, key) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var wants []ssh.PublicKey
|
||||||
|
cb, err := h.db()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("known_hosts: %w", err)
|
||||||
|
}
|
||||||
|
if cb != nil {
|
||||||
|
err := cb(hostname, remote, key)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var ke *knownhosts.KeyError
|
||||||
|
if !errors.As(err, &ke) {
|
||||||
|
return err // revoked key, unreadable file, ...
|
||||||
|
}
|
||||||
|
for _, k := range ke.Want {
|
||||||
|
wants = append(wants, k.Key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h.mu.Lock()
|
||||||
|
wants = append(wants, h.session[knownhosts.Normalize(hostname)]...)
|
||||||
|
h.mu.Unlock()
|
||||||
|
// Alarm only when a key of the same type is on record and differs; a
|
||||||
|
// key of a type we have no record for is merely unknown.
|
||||||
|
changed := false
|
||||||
|
known := make([]HostIdentity, 0, len(wants))
|
||||||
|
for _, k := range wants {
|
||||||
|
known = append(known, IdentityOf(k))
|
||||||
|
if k.Type() == key.Type() {
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
herr := &HostKeyError{Host: hostname, Identity: id, Known: known, Changed: changed}
|
||||||
|
if p == nil {
|
||||||
|
return herr
|
||||||
|
}
|
||||||
|
var dec HostKeyDecision
|
||||||
|
if err := prompt(func() error {
|
||||||
|
var err error
|
||||||
|
dec, err = p.HostKey(ctx, ep, id, known, changed)
|
||||||
|
return err
|
||||||
|
}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch dec {
|
||||||
|
case AcceptOnce:
|
||||||
|
h.remember(hostname, key)
|
||||||
|
return nil
|
||||||
|
case AcceptAndSave:
|
||||||
|
if changed {
|
||||||
|
// Replacing a stale line is left to `ssh-keygen -R`; trust the
|
||||||
|
// new key for this process only.
|
||||||
|
h.remember(hostname, key)
|
||||||
|
h.warnf("changed host key for %s accepted for this session only", hostname)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
h.save(hostname, key)
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return herr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
83
internal/ssh/conn/keepalive.go
Normal file
83
internal/ssh/conn/keepalive.go
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// errKeepalive is the reason recorded when keepalives go unanswered.
|
||||||
|
var errKeepalive = errors.New("no reply to keepalive")
|
||||||
|
|
||||||
|
// keepalive sends keepalive@openssh.com every interval. KeepaliveMaxMiss
|
||||||
|
// unanswered requests in a row (each waits KeepaliveTimeout) close the SSH
|
||||||
|
// client: every pending request fails at once and the state becomes Lost
|
||||||
|
// (N-P1-2). Worst-case detection: interval*(maxMiss+1) + timeout.
|
||||||
|
func (c *Conn) keepalive(g *generation) {
|
||||||
|
t := time.NewTicker(c.opts.KeepaliveInterval)
|
||||||
|
defer t.Stop()
|
||||||
|
miss := 0
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-g.done:
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
}
|
||||||
|
if c.ping(g, c.opts.KeepaliveTimeout) {
|
||||||
|
miss = 0
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
miss++
|
||||||
|
if miss >= c.opts.KeepaliveMaxMiss {
|
||||||
|
c.lose(g, fmt.Errorf("%w (%d × %v)", errKeepalive, miss, c.opts.KeepaliveTimeout))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ping sends one keepalive and reports whether a reply (any reply: OpenSSH
|
||||||
|
// and x/crypto servers answer "failure" to unknown global requests) arrived
|
||||||
|
// within timeout. A request stuck on a dead link finishes when the client
|
||||||
|
// is closed (it is not tracked in c.wg: Probe may run concurrently with
|
||||||
|
// close, and WaitGroup.Add must not race with Wait).
|
||||||
|
func (c *Conn) ping(g *generation, timeout time.Duration) bool {
|
||||||
|
res := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, _, err := g.ssh.SendRequest("keepalive@openssh.com", true, nil)
|
||||||
|
res <- err
|
||||||
|
}()
|
||||||
|
timer := time.NewTimer(timeout)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
return err == nil
|
||||||
|
case <-timer.C:
|
||||||
|
return false
|
||||||
|
case <-g.done:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Probe is the operation watchdog (§3.4): when an SFTP call has hung for a
|
||||||
|
// long time, sftpfs sends an out-of-band keepalive. No reply within timeout
|
||||||
|
// marks the connection Lost (closing it, so the hung call returns) and
|
||||||
|
// returns ErrConnLost. ctx only bounds the wait; it does not mark anything.
|
||||||
|
func (c *Conn) Probe(ctx context.Context, timeout time.Duration) error {
|
||||||
|
if err := c.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
g := c.cur.Load()
|
||||||
|
ok := make(chan bool, 1)
|
||||||
|
go func() { ok <- c.ping(g, timeout) }()
|
||||||
|
select {
|
||||||
|
case alive := <-ok:
|
||||||
|
if alive {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
c.lose(g, fmt.Errorf("%w (probe, %v)", errKeepalive, timeout))
|
||||||
|
return c.Err()
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
5
internal/ssh/conn/owner_other.go
Normal file
5
internal/ssh/conn/owner_other.go
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
//go:build !unix
|
||||||
|
|
||||||
|
package conn
|
||||||
|
|
||||||
|
func foreignOwner(string) bool { return false }
|
||||||
23
internal/ssh/conn/owner_unix.go
Normal file
23
internal/ssh/conn/owner_unix.go
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
//go:build unix
|
||||||
|
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// foreignOwner reports whether path (or, if it does not exist, its parent
|
||||||
|
// directory) belongs to a user other than the effective one, e.g. the
|
||||||
|
// invoking user's ~/.ssh while vcom runs under sudo.
|
||||||
|
func foreignOwner(path string) bool {
|
||||||
|
fi, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
if fi, err = os.Stat(filepath.Dir(path)); err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||||
|
return ok && int(st.Uid) != os.Geteuid()
|
||||||
|
}
|
||||||
328
internal/ssh/conn/pool.go
Normal file
328
internal/ssh/conn/pool.go
Normal file
|
|
@ -0,0 +1,328 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrPoolClosed is returned by Acquire after Pool.Close.
|
||||||
|
var ErrPoolClosed = errors.New("connection pool closed")
|
||||||
|
|
||||||
|
// DefaultIdleClose is how long a connection without leases stays open.
|
||||||
|
const DefaultIdleClose = 60 * time.Second
|
||||||
|
|
||||||
|
// DefaultReconnectBackoff: delays between Pool.Reconnect attempts (5 tries).
|
||||||
|
var DefaultReconnectBackoff = []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second}
|
||||||
|
|
||||||
|
// PoolOptions configure a Pool.
|
||||||
|
type PoolOptions struct {
|
||||||
|
DialOptions // Prompter, HandshakeTimeout, known_hosts, agent, ...
|
||||||
|
|
||||||
|
KeepaliveInterval time.Duration // 15s (or ServerAliveInterval)
|
||||||
|
KeepaliveTimeout time.Duration // 10s
|
||||||
|
KeepaliveMaxMiss int // 2 (or ServerAliveCountMax)
|
||||||
|
// IdleClose closes a connection this long after its last lease is
|
||||||
|
// released. Default 60s; negative closes immediately.
|
||||||
|
IdleClose time.Duration
|
||||||
|
// ReconnectBackoff are the delays between Reconnect attempts; attempts
|
||||||
|
// = len+1. nil means DefaultReconnectBackoff (1,2,4,8s).
|
||||||
|
ReconnectBackoff []time.Duration
|
||||||
|
// OnEvent receives connection state changes (main forwards them with
|
||||||
|
// program.Send). Called from pool goroutines; must not block.
|
||||||
|
OnEvent func(Event)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pool shares one connection per Endpoint.Key() among panels, jobs,
|
||||||
|
// previews and size counters. Each user holds a Lease; the pool alone
|
||||||
|
// closes connections: when the last lease has been released for IdleClose,
|
||||||
|
// or on Close (N-P0-8, N-P1-12). It is safe for concurrent use.
|
||||||
|
type Pool struct {
|
||||||
|
d *dialer
|
||||||
|
opts PoolOptions
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
closed bool
|
||||||
|
entries map[string]*entry
|
||||||
|
inflight map[string]*call
|
||||||
|
wg sync.WaitGroup // dial goroutines and idle closes
|
||||||
|
}
|
||||||
|
|
||||||
|
type entry struct {
|
||||||
|
key string
|
||||||
|
conn *Conn
|
||||||
|
refs int
|
||||||
|
idle *time.Timer
|
||||||
|
seq uint64 // invalidates stale idle timers
|
||||||
|
}
|
||||||
|
|
||||||
|
// call is one in-flight dial shared by every concurrent Acquire of a key.
|
||||||
|
type call struct {
|
||||||
|
done chan struct{}
|
||||||
|
waiters int
|
||||||
|
cancel context.CancelFunc
|
||||||
|
e *entry
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewPool creates a pool.
|
||||||
|
func NewPool(o PoolOptions) *Pool {
|
||||||
|
if o.IdleClose == 0 {
|
||||||
|
o.IdleClose = DefaultIdleClose
|
||||||
|
}
|
||||||
|
if o.ReconnectBackoff == nil {
|
||||||
|
o.ReconnectBackoff = DefaultReconnectBackoff
|
||||||
|
}
|
||||||
|
return &Pool{
|
||||||
|
d: newDialer(o.DialOptions),
|
||||||
|
opts: o,
|
||||||
|
entries: map[string]*entry{},
|
||||||
|
inflight: map[string]*call{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pool) connOptions() ConnOptions {
|
||||||
|
return ConnOptions{
|
||||||
|
KeepaliveInterval: p.opts.KeepaliveInterval,
|
||||||
|
KeepaliveTimeout: p.opts.KeepaliveTimeout,
|
||||||
|
KeepaliveMaxMiss: p.opts.KeepaliveMaxMiss,
|
||||||
|
OnEvent: p.opts.OnEvent,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire returns a lease on the connection for ep, dialing it if needed.
|
||||||
|
// Concurrent Acquires of the same key share one dial (N-P2-8: a double
|
||||||
|
// Enter makes one connection). A Lost connection gets one reconnect
|
||||||
|
// attempt. If every waiter gives up (ctx), the dial is cancelled; a dial
|
||||||
|
// that still completes is parked idle and closed after IdleClose.
|
||||||
|
func (p *Pool) Acquire(ctx context.Context, ep Endpoint) (*Lease, error) {
|
||||||
|
key := ep.Key()
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil, ErrPoolClosed
|
||||||
|
}
|
||||||
|
if e := p.entries[key]; e != nil {
|
||||||
|
l := p.lease(e)
|
||||||
|
p.mu.Unlock()
|
||||||
|
if e.conn.State() == Lost {
|
||||||
|
if err := e.conn.Reconnect(ctx); err != nil {
|
||||||
|
l.Release()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
c := p.inflight[key]
|
||||||
|
if c == nil {
|
||||||
|
dctx, cancel := context.WithCancel(context.Background())
|
||||||
|
c = &call{done: make(chan struct{}), cancel: cancel}
|
||||||
|
p.inflight[key] = c
|
||||||
|
p.wg.Add(1)
|
||||||
|
go p.dial(dctx, key, ep, c)
|
||||||
|
}
|
||||||
|
c.waiters++
|
||||||
|
p.mu.Unlock()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-c.done:
|
||||||
|
case <-ctx.Done():
|
||||||
|
p.mu.Lock()
|
||||||
|
c.waiters--
|
||||||
|
select {
|
||||||
|
case <-c.done:
|
||||||
|
// Finished concurrently: the entry may now have no users.
|
||||||
|
if c.e != nil && c.e.refs == 0 {
|
||||||
|
p.startIdle(c.e)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
if c.waiters == 0 {
|
||||||
|
c.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
if c.err != nil {
|
||||||
|
return nil, c.err
|
||||||
|
}
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
if p.closed || p.entries[key] != c.e {
|
||||||
|
return nil, ErrPoolClosed
|
||||||
|
}
|
||||||
|
return p.lease(c.e), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pool) dial(ctx context.Context, key string, ep Endpoint, c *call) {
|
||||||
|
defer p.wg.Done()
|
||||||
|
conn, err := p.d.connect(ctx, ep, p.connOptions())
|
||||||
|
c.cancel()
|
||||||
|
p.mu.Lock()
|
||||||
|
delete(p.inflight, key)
|
||||||
|
if err == nil && p.closed {
|
||||||
|
err = ErrPoolClosed
|
||||||
|
p.mu.Unlock()
|
||||||
|
conn.close()
|
||||||
|
p.mu.Lock()
|
||||||
|
}
|
||||||
|
c.err = err
|
||||||
|
if err == nil {
|
||||||
|
c.e = &entry{key: key, conn: conn}
|
||||||
|
p.entries[key] = c.e
|
||||||
|
if c.waiters == 0 {
|
||||||
|
p.startIdle(c.e) // everyone gave up; keep briefly, then close
|
||||||
|
}
|
||||||
|
}
|
||||||
|
close(c.done)
|
||||||
|
p.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// lease takes a reference on e; p.mu is held.
|
||||||
|
func (p *Pool) lease(e *entry) *Lease {
|
||||||
|
e.refs++
|
||||||
|
e.seq++
|
||||||
|
if e.idle != nil {
|
||||||
|
e.idle.Stop()
|
||||||
|
e.idle = nil
|
||||||
|
}
|
||||||
|
return &Lease{p: p, e: e}
|
||||||
|
}
|
||||||
|
|
||||||
|
// startIdle schedules e to close after IdleClose; p.mu is held.
|
||||||
|
func (p *Pool) startIdle(e *entry) {
|
||||||
|
e.seq++
|
||||||
|
seq := e.seq
|
||||||
|
if e.idle != nil {
|
||||||
|
e.idle.Stop()
|
||||||
|
}
|
||||||
|
fire := func() {
|
||||||
|
p.mu.Lock()
|
||||||
|
if e.seq != seq || e.refs != 0 || p.entries[e.key] != e {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delete(p.entries, e.key)
|
||||||
|
// The entry was still registered, so Close has not started waiting:
|
||||||
|
// this Add cannot race with p.wg.Wait.
|
||||||
|
p.wg.Add(1)
|
||||||
|
p.mu.Unlock()
|
||||||
|
defer p.wg.Done()
|
||||||
|
e.conn.close()
|
||||||
|
}
|
||||||
|
if p.opts.IdleClose < 0 {
|
||||||
|
e.idle = nil
|
||||||
|
go fire()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.idle = time.AfterFunc(p.opts.IdleClose, fire)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pool) release(e *entry) {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
e.refs--
|
||||||
|
if e.refs == 0 && !p.closed && p.entries[e.key] == e {
|
||||||
|
p.startIdle(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reconnect re-dials a Lost connection with backoff (1,2,4,8s between at
|
||||||
|
// most 5 attempts by default). A Ready connection is left alone. Host key
|
||||||
|
// problems and ctx cancellation stop the retries.
|
||||||
|
func (p *Pool) Reconnect(ctx context.Context, key string) error {
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return ErrPoolClosed
|
||||||
|
}
|
||||||
|
e := p.entries[key]
|
||||||
|
p.mu.Unlock()
|
||||||
|
if e == nil {
|
||||||
|
return ErrClosed
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
for i := 0; ; i++ {
|
||||||
|
if err = e.conn.Reconnect(ctx); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, ErrClosed) || errors.Is(err, ErrHostKeyChanged) ||
|
||||||
|
errors.Is(err, ErrHostKeyRejected) || errors.Is(err, ErrIdentityChanged) || ctx.Err() != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if i >= len(p.opts.ReconnectBackoff) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t := time.NewTimer(p.opts.ReconnectBackoff[i])
|
||||||
|
select {
|
||||||
|
case <-t.C:
|
||||||
|
case <-ctx.Done():
|
||||||
|
t.Stop()
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes every connection, cancels pending dials and waits for them.
|
||||||
|
// Leases stay safe to use: their calls fail with ErrClosed.
|
||||||
|
func (p *Pool) Close() error {
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
p.closed = true
|
||||||
|
var conns []*Conn
|
||||||
|
for k, e := range p.entries {
|
||||||
|
if e.idle != nil {
|
||||||
|
e.idle.Stop()
|
||||||
|
}
|
||||||
|
e.seq++
|
||||||
|
conns = append(conns, e.conn)
|
||||||
|
delete(p.entries, k)
|
||||||
|
}
|
||||||
|
for _, c := range p.inflight {
|
||||||
|
c.cancel()
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
for _, c := range conns {
|
||||||
|
c.close()
|
||||||
|
}
|
||||||
|
p.wg.Wait()
|
||||||
|
p.d.close()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lease is one user's reference to a pooled connection. Release it when
|
||||||
|
// done; it is idempotent. A lease stays safe to use after the connection
|
||||||
|
// died or the pool closed: calls return errors, never panic.
|
||||||
|
type Lease struct {
|
||||||
|
p *Pool
|
||||||
|
e *entry
|
||||||
|
released atomic.Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Conn returns the leased connection.
|
||||||
|
func (l *Lease) Conn() *Conn { return l.e.conn }
|
||||||
|
|
||||||
|
// Client is shorthand for Conn().Client().
|
||||||
|
func (l *Lease) Client() (*sftp.Client, error) { return l.e.conn.Client() }
|
||||||
|
|
||||||
|
// Acquire takes another reference to the same connection (mirror panel,
|
||||||
|
// background job). Release each lease separately.
|
||||||
|
func (l *Lease) Acquire() *Lease {
|
||||||
|
l.p.mu.Lock()
|
||||||
|
defer l.p.mu.Unlock()
|
||||||
|
return l.p.lease(l.e)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release drops this reference; the second and later calls do nothing.
|
||||||
|
func (l *Lease) Release() {
|
||||||
|
if l.released.CompareAndSwap(false, true) {
|
||||||
|
l.p.release(l.e)
|
||||||
|
}
|
||||||
|
}
|
||||||
339
internal/ssh/conn/pool_test.go
Normal file
339
internal/ssh/conn/pool_test.go
Normal file
|
|
@ -0,0 +1,339 @@
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/testutil/sshtest"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (e *env) pool(o PoolOptions) *Pool {
|
||||||
|
e.t.Helper()
|
||||||
|
if o.Home == "" {
|
||||||
|
o.Home = e.home
|
||||||
|
}
|
||||||
|
if o.AgentSocket == "" {
|
||||||
|
o.AgentSocket = "-"
|
||||||
|
}
|
||||||
|
if o.KnownHostsFiles == nil {
|
||||||
|
o.KnownHostsFiles = []string{e.kh}
|
||||||
|
}
|
||||||
|
p := NewPool(o)
|
||||||
|
e.t.Cleanup(func() { p.Close() })
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Pool) entryCount() int {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return len(p.entries)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustAcquire(t *testing.T, p *Pool, ep Endpoint) *Lease {
|
||||||
|
t.Helper()
|
||||||
|
l, err := p.Acquire(context.Background(), ep)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Acquire: %v", err)
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ported from TestCloseRace (B5), N-P0-8: Close raced with running calls
|
||||||
|
// and could call a method on a nil *sftp.Client. Leases are used, released,
|
||||||
|
// re-acquired and the pool closed concurrently under -race.
|
||||||
|
func TestLeaseReleaseRace(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
p := e.pool(PoolOptions{IdleClose: 10 * time.Millisecond})
|
||||||
|
ep := endpointFor(srv.Addr, srv.Password)
|
||||||
|
base := mustAcquire(t, p, ep)
|
||||||
|
dir := t.TempDir()
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
panicked := make(chan any, 8)
|
||||||
|
worker := func(fn func(i int)) {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
defer func() {
|
||||||
|
if r := recover(); r != nil {
|
||||||
|
panicked <- r
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for i := 0; i < 300; i++ {
|
||||||
|
fn(i)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
for w := 0; w < 3; w++ {
|
||||||
|
worker(func(int) {
|
||||||
|
l := base.Acquire()
|
||||||
|
defer l.Release()
|
||||||
|
defer l.Release() // idempotent
|
||||||
|
if sc, err := l.Client(); err == nil {
|
||||||
|
_, err := sc.ReadDir(dir)
|
||||||
|
if err != nil && !errors.Is(l.Conn().MapErr(err), ErrClosed) && !errors.Is(l.Conn().MapErr(err), ErrConnLost) {
|
||||||
|
t.Errorf("ReadDir: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
worker(func(int) {
|
||||||
|
if l, err := p.Acquire(context.Background(), ep); err == nil {
|
||||||
|
l.Conn().State()
|
||||||
|
l.Release()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
worker(func(i int) {
|
||||||
|
switch i {
|
||||||
|
case 0:
|
||||||
|
time.Sleep(50 * time.Millisecond) // let the readers get going
|
||||||
|
case 1:
|
||||||
|
p.Close()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
wg.Wait()
|
||||||
|
close(panicked)
|
||||||
|
for r := range panicked {
|
||||||
|
t.Fatalf("panic: %v", r)
|
||||||
|
}
|
||||||
|
if _, err := base.Client(); !errors.Is(err, ErrClosed) {
|
||||||
|
t.Errorf("Client after pool Close: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := p.Acquire(context.Background(), ep); !errors.Is(err, ErrPoolClosed) {
|
||||||
|
t.Errorf("Acquire after Close: %v", err)
|
||||||
|
}
|
||||||
|
base.Release()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-8: a double Enter made two connections.
|
||||||
|
func TestAcquireSingleflight(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
px.SetDelay(20 * time.Millisecond) // keep the dial in flight while all callers arrive
|
||||||
|
p := e.pool(PoolOptions{})
|
||||||
|
ep := endpointFor(px.Addr, srv.Password)
|
||||||
|
const n = 10
|
||||||
|
leases := make([]*Lease, n)
|
||||||
|
errs := make([]error, n)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
leases[i], errs[i] = p.Acquire(context.Background(), ep)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
for i := 0; i < n; i++ {
|
||||||
|
if errs[i] != nil {
|
||||||
|
t.Fatal(errs[i])
|
||||||
|
}
|
||||||
|
if leases[i].Conn() != leases[0].Conn() {
|
||||||
|
t.Error("leases on different connections")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d := p.d.dials.Load(); d != 1 {
|
||||||
|
t.Errorf("dials = %d, want 1", d)
|
||||||
|
}
|
||||||
|
// Same user@host:port through another alias shares the connection.
|
||||||
|
ep2 := ep
|
||||||
|
ep2.Alias = "other-alias"
|
||||||
|
l := mustAcquire(t, p, ep2)
|
||||||
|
if l.Conn() != leases[0].Conn() || p.d.dials.Load() != 1 {
|
||||||
|
t.Error("alias with the same key did not share the connection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every caller gave up: the dial is cancelled and nothing stays open.
|
||||||
|
func TestAcquireAllWaitersGone(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
px.Freeze(true)
|
||||||
|
p := e.pool(PoolOptions{})
|
||||||
|
ep := endpointFor(px.Addr, srv.Password)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
start := time.Now()
|
||||||
|
if _, err := p.Acquire(ctx, ep); !errors.Is(err, context.DeadlineExceeded) {
|
||||||
|
t.Fatalf("err = %v", err)
|
||||||
|
}
|
||||||
|
if el := time.Since(start); el > time.Second {
|
||||||
|
t.Errorf("Acquire returned after %v", el)
|
||||||
|
}
|
||||||
|
waitFor(t, 2*time.Second, "in-flight dial gone", func() bool {
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
return len(p.inflight) == 0 && len(p.entries) == 0
|
||||||
|
})
|
||||||
|
px.Freeze(false)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIdleClose(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
var ev events
|
||||||
|
p := e.pool(PoolOptions{IdleClose: 150 * time.Millisecond, OnEvent: ev.add})
|
||||||
|
ep := endpointFor(srv.Addr, srv.Password)
|
||||||
|
l := mustAcquire(t, p, ep)
|
||||||
|
c := l.Conn()
|
||||||
|
l.Release()
|
||||||
|
l = mustAcquire(t, p, ep) // within IdleClose: reused
|
||||||
|
if l.Conn() != c || p.d.dials.Load() != 1 {
|
||||||
|
t.Fatal("connection not reused within IdleClose")
|
||||||
|
}
|
||||||
|
time.Sleep(300 * time.Millisecond)
|
||||||
|
if c.State() != Ready {
|
||||||
|
t.Fatal("connection with a live lease was closed")
|
||||||
|
}
|
||||||
|
l.Release()
|
||||||
|
waitFor(t, 2*time.Second, "idle close", func() bool { return ev.has(Closed) && p.entryCount() == 0 })
|
||||||
|
if c.State() != Closed {
|
||||||
|
t.Errorf("state = %v", c.State())
|
||||||
|
}
|
||||||
|
l = mustAcquire(t, p, ep)
|
||||||
|
if l.Conn() == c || p.d.dials.Load() != 2 {
|
||||||
|
t.Error("expected a fresh connection after idle close")
|
||||||
|
}
|
||||||
|
l.Release()
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P1-12: mirror shared one client and a second mirror closed it.
|
||||||
|
func TestMirrorLeaseSurvivesRelease(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
p := e.pool(PoolOptions{IdleClose: -1})
|
||||||
|
left := mustAcquire(t, p, endpointFor(srv.Addr, srv.Password))
|
||||||
|
right := left.Acquire() // mirror
|
||||||
|
left.Release()
|
||||||
|
left.Release()
|
||||||
|
left.Release() // over-release must not steal right's reference
|
||||||
|
sc, err := right.Client()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("mirror lease broken: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := sc.ReadDir(t.TempDir()); err != nil {
|
||||||
|
t.Fatalf("ReadDir on mirror: %v", err)
|
||||||
|
}
|
||||||
|
c := right.Conn()
|
||||||
|
right.Release()
|
||||||
|
waitFor(t, 2*time.Second, "close after last release", func() bool { return c.State() == Closed })
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAcquireReconnectsLost(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
p := e.pool(PoolOptions{})
|
||||||
|
ep := endpointFor(px.Addr, srv.Password)
|
||||||
|
l := mustAcquire(t, p, ep)
|
||||||
|
defer l.Release()
|
||||||
|
px.KillAll()
|
||||||
|
waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost })
|
||||||
|
l2 := mustAcquire(t, p, ep)
|
||||||
|
defer l2.Release()
|
||||||
|
if l2.Conn() != l.Conn() || l.Conn().State() != Ready || l.Conn().Gen() != 2 {
|
||||||
|
t.Errorf("state %v gen %d", l.Conn().State(), l.Conn().Gen())
|
||||||
|
}
|
||||||
|
if _, err := l.Client(); err != nil {
|
||||||
|
t.Errorf("old lease after reconnect: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPoolReconnectBackoff(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
var mu sync.Mutex
|
||||||
|
connecting := 0
|
||||||
|
p := e.pool(PoolOptions{
|
||||||
|
ReconnectBackoff: []time.Duration{10 * time.Millisecond, 10 * time.Millisecond},
|
||||||
|
OnEvent: func(ev Event) {
|
||||||
|
if ev.State == Connecting {
|
||||||
|
mu.Lock()
|
||||||
|
connecting++
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
ep := endpointFor(px.Addr, srv.Password)
|
||||||
|
l := mustAcquire(t, p, ep)
|
||||||
|
defer l.Release()
|
||||||
|
px.Freeze(true)
|
||||||
|
px.KillAll()
|
||||||
|
waitFor(t, 2*time.Second, "Lost", func() bool { return l.Conn().State() == Lost })
|
||||||
|
p.d.opts.HandshakeTimeout = 100 * time.Millisecond
|
||||||
|
if err := p.Reconnect(context.Background(), ep.Key()); err == nil {
|
||||||
|
t.Fatal("reconnect through a frozen link succeeded")
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
if connecting != 3 {
|
||||||
|
t.Errorf("attempts = %d, want 3", connecting)
|
||||||
|
}
|
||||||
|
mu.Unlock()
|
||||||
|
px.Freeze(false)
|
||||||
|
if err := p.Reconnect(context.Background(), ep.Key()); err != nil {
|
||||||
|
t.Fatalf("reconnect after recovery: %v", err)
|
||||||
|
}
|
||||||
|
if l.Conn().State() != Ready {
|
||||||
|
t.Errorf("state = %v", l.Conn().State())
|
||||||
|
}
|
||||||
|
if err := p.Reconnect(context.Background(), "nobody@nowhere:22"); !errors.Is(err, ErrClosed) {
|
||||||
|
t.Errorf("unknown key: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPoolCloseCancelsDial(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
px := e.proxy(srv)
|
||||||
|
px.Freeze(true)
|
||||||
|
p := e.pool(PoolOptions{})
|
||||||
|
res := make(chan error, 1)
|
||||||
|
go func() {
|
||||||
|
_, err := p.Acquire(context.Background(), endpointFor(px.Addr, srv.Password))
|
||||||
|
res <- err
|
||||||
|
}()
|
||||||
|
waitFor(t, time.Second, "dial in flight", func() bool { return p.d.dials.Load() == 1 })
|
||||||
|
start := time.Now()
|
||||||
|
p.Close()
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("Acquire succeeded on a closed pool")
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("Acquire still blocked after Close")
|
||||||
|
}
|
||||||
|
if el := time.Since(start); el > time.Second {
|
||||||
|
t.Errorf("Close took %v", el)
|
||||||
|
}
|
||||||
|
px.Freeze(false)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPoolDifferentUsersSeparate(t *testing.T) {
|
||||||
|
e := newEnv(t)
|
||||||
|
srv := e.startTrusted(sshtest.Options{})
|
||||||
|
p := e.pool(PoolOptions{})
|
||||||
|
a := endpointFor(srv.Addr, srv.Password)
|
||||||
|
b := a
|
||||||
|
b.User = "other"
|
||||||
|
la, lb := mustAcquire(t, p, a), mustAcquire(t, p, b)
|
||||||
|
defer la.Release()
|
||||||
|
defer lb.Release()
|
||||||
|
if la.Conn() == lb.Conn() {
|
||||||
|
t.Error(fmt.Sprintf("users %s and %s share a connection", a.User, b.User))
|
||||||
|
}
|
||||||
|
}
|
||||||
55
internal/ssh/conn/prompter.go
Normal file
55
internal/ssh/conn/prompter.go
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
// Package conn owns SSH connections: dialing with a bounded handshake,
|
||||||
|
// host-key verification, authentication, keepalive, reconnect, remote exec
|
||||||
|
// and a reference-counted pool. Nothing outside the Pool closes a
|
||||||
|
// connection.
|
||||||
|
package conn
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
|
||||||
|
"vcom/internal/ssh/sshconfig"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Endpoint is the resolved host to dial.
|
||||||
|
type Endpoint = sshconfig.Endpoint
|
||||||
|
|
||||||
|
// HostIdentity identifies a server host key.
|
||||||
|
type HostIdentity struct {
|
||||||
|
KeyType string // e.g. "ssh-ed25519"
|
||||||
|
FingerprintSHA256 string // "SHA256:..." as printed by ssh-keygen -l
|
||||||
|
}
|
||||||
|
|
||||||
|
// IdentityOf returns the identity of a public key.
|
||||||
|
func IdentityOf(k ssh.PublicKey) HostIdentity {
|
||||||
|
sum := sha256.Sum256(k.Marshal())
|
||||||
|
return HostIdentity{
|
||||||
|
KeyType: k.Type(),
|
||||||
|
FingerprintSHA256: "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// HostKeyDecision is the answer to an unknown or changed host key.
|
||||||
|
type HostKeyDecision uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
Reject HostKeyDecision = iota // refuse to connect
|
||||||
|
AcceptOnce // trust for this process only
|
||||||
|
AcceptAndSave // trust and append to known_hosts
|
||||||
|
)
|
||||||
|
|
||||||
|
// Prompter asks the user. The UI implements it via jobs.Ask; every method
|
||||||
|
// must return promptly when ctx is cancelled. A nil Prompter rejects unknown
|
||||||
|
// host keys and offers no interactive authentication.
|
||||||
|
type Prompter interface {
|
||||||
|
// HostKey is called for a key that is not in known_hosts. changed is
|
||||||
|
// true when known_hosts has a different key of the same type (possible
|
||||||
|
// MITM); known lists the keys known_hosts has for the host.
|
||||||
|
HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error)
|
||||||
|
Password(ctx context.Context, ep Endpoint) (string, error)
|
||||||
|
KeyboardInteractive(ctx context.Context, ep Endpoint, instruction string, questions []string, echo []bool) ([]string, error)
|
||||||
|
Passphrase(ctx context.Context, keyPath string) ([]byte, error)
|
||||||
|
}
|
||||||
199
internal/ssh/sshconfig/flatten.go
Normal file
199
internal/ssh/sshconfig/flatten.go
Normal file
|
|
@ -0,0 +1,199 @@
|
||||||
|
package sshconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// hashMark stands in for a literal '#' inside a value while the flattened
|
||||||
|
// config goes through kevinburke/ssh_config, whose lexer treats every '#' as
|
||||||
|
// the start of a comment. OpenSSH only starts a comment at a '#' that begins
|
||||||
|
// a word outside quotes (N-P1-5: "IdentityFile ~/.ssh/key#1").
|
||||||
|
const hashMark = ""
|
||||||
|
|
||||||
|
const maxIncludeDepth = 5
|
||||||
|
|
||||||
|
// flattener turns an ssh_config file and everything it Includes into a single
|
||||||
|
// text that kevinburke/ssh_config can parse without touching the disk:
|
||||||
|
// - comments are stripped with OpenSSH rules, literal '#' is escaped;
|
||||||
|
// - Include is inlined (relative to ~/.ssh), restoring the enclosing Host
|
||||||
|
// context after the included text, as OpenSSH does;
|
||||||
|
// - Host patterns are lowercased (OpenSSH matches host names
|
||||||
|
// case-insensitively; the alias is lowercased too before lookup);
|
||||||
|
// - "Match all" and "Match host a,b" become Host blocks; other Match
|
||||||
|
// criteria (user, exec, canonical, ...) become a block that never
|
||||||
|
// matches, instead of failing the whole file.
|
||||||
|
type flattener struct {
|
||||||
|
home string
|
||||||
|
b strings.Builder
|
||||||
|
explicit []string // non-wildcard Host names, in file order
|
||||||
|
seen map[string]bool
|
||||||
|
warnings []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flattener) warnf(format string, args ...any) {
|
||||||
|
f.warnings = append(f.warnings, fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flattener) file(path string, depth int) error {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f.text(path, string(data), depth)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flattener) text(path, data string, depth int) {
|
||||||
|
context := "" // current Host line written to the output, "" = implicit Host *
|
||||||
|
for n, raw := range strings.Split(data, "\n") {
|
||||||
|
line := strings.TrimSpace(stripComment(strings.TrimRight(raw, "\r")))
|
||||||
|
if line == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
kw, rest := splitKeyword(line)
|
||||||
|
switch strings.ToLower(kw) {
|
||||||
|
case "host":
|
||||||
|
pats := splitArgs(rest)
|
||||||
|
for i, p := range pats {
|
||||||
|
pats[i] = strings.ToLower(p)
|
||||||
|
if !strings.ContainsAny(p, "*?!") && !f.seen[pats[i]] {
|
||||||
|
f.seen[pats[i]] = true
|
||||||
|
f.explicit = append(f.explicit, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(pats) == 0 {
|
||||||
|
f.warnf("%s:%d: Host without patterns", path, n+1)
|
||||||
|
pats = []string{"!*"}
|
||||||
|
}
|
||||||
|
context = "Host " + strings.Join(pats, " ")
|
||||||
|
f.b.WriteString(context + "\n")
|
||||||
|
case "match":
|
||||||
|
context = f.match(path, n+1, rest)
|
||||||
|
f.b.WriteString(context + "\n")
|
||||||
|
case "include":
|
||||||
|
if depth >= maxIncludeDepth {
|
||||||
|
f.warnf("%s:%d: Include nested too deep, ignored", path, n+1)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, pat := range splitArgs(rest) {
|
||||||
|
for _, m := range f.glob(pat) {
|
||||||
|
if err := f.file(m, depth+1); err != nil {
|
||||||
|
f.warnf("%s:%d: Include %s: %v", path, n+1, m, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The included text may have opened its own Host blocks; the rest
|
||||||
|
// of this file continues in the block that contained the Include.
|
||||||
|
if context == "" {
|
||||||
|
f.b.WriteString("Host *\n")
|
||||||
|
} else {
|
||||||
|
f.b.WriteString(context + "\n")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
f.b.WriteString(kw + " " + strings.ReplaceAll(rest, "#", hashMark) + "\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flattener) match(path string, line int, rest string) string {
|
||||||
|
fields := splitArgs(rest)
|
||||||
|
if len(fields) == 1 && strings.EqualFold(fields[0], "all") {
|
||||||
|
return "Host *"
|
||||||
|
}
|
||||||
|
if len(fields) == 2 && (strings.EqualFold(fields[0], "host") || strings.EqualFold(fields[0], "originalhost")) {
|
||||||
|
var pats []string
|
||||||
|
for _, p := range strings.Split(fields[1], ",") {
|
||||||
|
if p != "" {
|
||||||
|
pats = append(pats, strings.ToLower(p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(pats) > 0 {
|
||||||
|
return "Host " + strings.Join(pats, " ")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.warnf("%s:%d: unsupported Match %q, block ignored", path, line, rest)
|
||||||
|
return "Host !*"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *flattener) glob(pat string) []string {
|
||||||
|
p := expandTilde(pat, f.home)
|
||||||
|
if !filepath.IsAbs(p) {
|
||||||
|
p = filepath.Join(f.home, ".ssh", p)
|
||||||
|
}
|
||||||
|
ms, err := filepath.Glob(p)
|
||||||
|
if err != nil {
|
||||||
|
f.warnf("Include %s: %v", pat, err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
sort.Strings(ms)
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
|
||||||
|
// stripComment removes a trailing comment: a '#' that starts a word and is
|
||||||
|
// not inside double quotes (OpenSSH argv_split rules).
|
||||||
|
func stripComment(s string) string {
|
||||||
|
inQuote := false
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
switch c := s[i]; {
|
||||||
|
case c == '"':
|
||||||
|
inQuote = !inQuote
|
||||||
|
case c == '#' && !inQuote && (i == 0 || s[i-1] == ' ' || s[i-1] == '\t'):
|
||||||
|
return s[:i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitKeyword splits "Key value", "Key=value" and "Key = value".
|
||||||
|
func splitKeyword(line string) (kw, rest string) {
|
||||||
|
i := strings.IndexAny(line, " \t=")
|
||||||
|
if i < 0 {
|
||||||
|
return line, ""
|
||||||
|
}
|
||||||
|
kw, rest = line[:i], strings.TrimLeft(line[i:], " \t")
|
||||||
|
if strings.HasPrefix(rest, "=") {
|
||||||
|
rest = strings.TrimLeft(rest[1:], " \t")
|
||||||
|
}
|
||||||
|
return kw, rest
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitArgs splits on whitespace, honouring double quotes.
|
||||||
|
func splitArgs(s string) []string {
|
||||||
|
var out []string
|
||||||
|
var cur strings.Builder
|
||||||
|
inQuote, have := false, false
|
||||||
|
for _, r := range s {
|
||||||
|
switch {
|
||||||
|
case r == '"':
|
||||||
|
inQuote = !inQuote
|
||||||
|
have = true
|
||||||
|
case (r == ' ' || r == '\t') && !inQuote:
|
||||||
|
if have {
|
||||||
|
out = append(out, cur.String())
|
||||||
|
cur.Reset()
|
||||||
|
have = false
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
cur.WriteRune(r)
|
||||||
|
have = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if have {
|
||||||
|
out = append(out, cur.String())
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func expandTilde(p, home string) string {
|
||||||
|
if p == "~" {
|
||||||
|
return home
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(p, "~/") {
|
||||||
|
return filepath.Join(home, p[2:])
|
||||||
|
}
|
||||||
|
return p
|
||||||
|
}
|
||||||
391
internal/ssh/sshconfig/resolver.go
Normal file
391
internal/ssh/sshconfig/resolver.go
Normal file
|
|
@ -0,0 +1,391 @@
|
||||||
|
// Package sshconfig resolves host aliases into connection endpoints using
|
||||||
|
// ~/.ssh/config (parsed with github.com/kevinburke/ssh_config) and vcom's own
|
||||||
|
// encrypted host list (hosts.dat, see Store).
|
||||||
|
package sshconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"os/user"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
ssh_config "github.com/kevinburke/ssh_config"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultPort is the SSH port used when none is configured.
|
||||||
|
const DefaultPort = 22
|
||||||
|
|
||||||
|
// Endpoint is everything needed to dial one host.
|
||||||
|
type Endpoint struct {
|
||||||
|
Alias string // as the user named the host
|
||||||
|
User string
|
||||||
|
Host string // HostName; the alias when the config has none (N-P1-5)
|
||||||
|
Port int
|
||||||
|
|
||||||
|
IdentityFiles []string // absolute paths, in config order
|
||||||
|
IdentitiesOnly bool
|
||||||
|
|
||||||
|
// ProxyJump hops, resolved through the same config. Dialing through them
|
||||||
|
// is stage 8; for now the field is informational.
|
||||||
|
ProxyJump []Endpoint
|
||||||
|
|
||||||
|
ServerAliveInterval time.Duration
|
||||||
|
ServerAliveCountMax int
|
||||||
|
ConnectTimeout time.Duration
|
||||||
|
|
||||||
|
// Password is set only for hosts added in vcom (hosts.dat).
|
||||||
|
Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
// port returns Port or DefaultPort.
|
||||||
|
func (e Endpoint) port() int {
|
||||||
|
if e.Port <= 0 {
|
||||||
|
return DefaultPort
|
||||||
|
}
|
||||||
|
return e.Port
|
||||||
|
}
|
||||||
|
|
||||||
|
// Addr is "host:port" for dialing.
|
||||||
|
func (e Endpoint) Addr() string {
|
||||||
|
return net.JoinHostPort(e.Host, strconv.Itoa(e.port()))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Key is "user@host:port", the connection pool key. Aliases that resolve to
|
||||||
|
// the same user, host and port share a connection; different users never do
|
||||||
|
// (N-P2-3).
|
||||||
|
func (e Endpoint) Key() string {
|
||||||
|
return e.User + "@" + e.Addr()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Label is a short name for the UI: "user@alias".
|
||||||
|
func (e Endpoint) Label() string {
|
||||||
|
name := e.Alias
|
||||||
|
if name == "" {
|
||||||
|
name = e.Host
|
||||||
|
}
|
||||||
|
if e.User == "" {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
return e.User + "@" + name
|
||||||
|
}
|
||||||
|
|
||||||
|
// Source tells where a host entry comes from.
|
||||||
|
type Source uint8
|
||||||
|
|
||||||
|
const (
|
||||||
|
FromSSHConfig Source = iota // ~/.ssh/config
|
||||||
|
FromStore // hosts.dat (added in vcom)
|
||||||
|
)
|
||||||
|
|
||||||
|
// HostEntry is one row of the host list.
|
||||||
|
type HostEntry struct {
|
||||||
|
Alias string
|
||||||
|
Source Source
|
||||||
|
User string
|
||||||
|
Host string
|
||||||
|
Port int
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisplayName is "alias (user@host[:port])".
|
||||||
|
func (h HostEntry) DisplayName() string {
|
||||||
|
addr := h.Host
|
||||||
|
if h.Port != 0 && h.Port != DefaultPort {
|
||||||
|
addr = net.JoinHostPort(h.Host, strconv.Itoa(h.Port))
|
||||||
|
}
|
||||||
|
if h.User != "" {
|
||||||
|
addr = h.User + "@" + addr
|
||||||
|
}
|
||||||
|
return h.Alias + " (" + addr + ")"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Options configures a Resolver.
|
||||||
|
type Options struct {
|
||||||
|
// ConfigPath is the ssh config to read. "" means Home/.ssh/config; a
|
||||||
|
// missing file is not an error.
|
||||||
|
ConfigPath string
|
||||||
|
// Home is used for "~", relative Include and IdentityFile paths and the
|
||||||
|
// default config path. "" means os.UserHomeDir().
|
||||||
|
Home string
|
||||||
|
// LocalUser is the default remote user. "" means the current user.
|
||||||
|
LocalUser string
|
||||||
|
// Store adds the hosts saved in vcom. May be nil.
|
||||||
|
Store *Store
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolver answers host lookups. It is safe for concurrent use.
|
||||||
|
type Resolver struct {
|
||||||
|
opts Options
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
cfg *ssh_config.Config
|
||||||
|
explicit []string
|
||||||
|
warnings []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewResolver loads the ssh config. On a parse error the returned Resolver
|
||||||
|
// is still usable (it knows only the Store hosts) and the error is returned
|
||||||
|
// alongside it.
|
||||||
|
func NewResolver(o Options) (*Resolver, error) {
|
||||||
|
if o.Home == "" {
|
||||||
|
o.Home, _ = os.UserHomeDir()
|
||||||
|
}
|
||||||
|
if o.ConfigPath == "" && o.Home != "" {
|
||||||
|
o.ConfigPath = filepath.Join(o.Home, ".ssh", "config")
|
||||||
|
}
|
||||||
|
if o.LocalUser == "" {
|
||||||
|
o.LocalUser = currentUser()
|
||||||
|
}
|
||||||
|
r := &Resolver{opts: o}
|
||||||
|
return r, r.Reload()
|
||||||
|
}
|
||||||
|
|
||||||
|
func currentUser() string {
|
||||||
|
if u, err := user.Current(); err == nil && u.Username != "" {
|
||||||
|
return u.Username
|
||||||
|
}
|
||||||
|
return os.Getenv("USER")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload re-reads the ssh config file.
|
||||||
|
func (r *Resolver) Reload() error {
|
||||||
|
f := &flattener{home: r.opts.Home, seen: map[string]bool{}}
|
||||||
|
var loadErr error
|
||||||
|
if r.opts.ConfigPath != "" {
|
||||||
|
if err := f.file(r.opts.ConfigPath, 0); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
loadErr = err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg, err := ssh_config.DecodeBytes([]byte(f.b.String()))
|
||||||
|
if err != nil {
|
||||||
|
cfg, _ = ssh_config.DecodeBytes(nil)
|
||||||
|
f.explicit = nil
|
||||||
|
loadErr = fmt.Errorf("parse %s: %w", r.opts.ConfigPath, err)
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.cfg, r.explicit, r.warnings = cfg, f.explicit, f.warnings
|
||||||
|
r.mu.Unlock()
|
||||||
|
return loadErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warnings lists non-fatal problems found by the last Reload (unsupported
|
||||||
|
// Match criteria, unreadable Include files).
|
||||||
|
func (r *Resolver) Warnings() []string {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
return append([]string(nil), r.warnings...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hosts lists the explicit (non-pattern) Host names of the ssh config, then
|
||||||
|
// the Store hosts whose names are not in the config.
|
||||||
|
func (r *Resolver) Hosts() []HostEntry {
|
||||||
|
r.mu.RLock()
|
||||||
|
names := append([]string(nil), r.explicit...)
|
||||||
|
r.mu.RUnlock()
|
||||||
|
var out []HostEntry
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, n := range names {
|
||||||
|
seen[strings.ToLower(n)] = true
|
||||||
|
ep, err := r.resolveConfig(n, 0)
|
||||||
|
if err != nil {
|
||||||
|
ep = Endpoint{Alias: n, Host: n}
|
||||||
|
}
|
||||||
|
out = append(out, HostEntry{Alias: n, Source: FromSSHConfig, User: ep.User, Host: ep.Host, Port: ep.Port})
|
||||||
|
}
|
||||||
|
if r.opts.Store != nil {
|
||||||
|
for _, h := range r.opts.Store.Hosts() {
|
||||||
|
if seen[strings.ToLower(h.Name)] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[strings.ToLower(h.Name)] = true
|
||||||
|
ep := h.Endpoint(r.opts.LocalUser)
|
||||||
|
out = append(out, HostEntry{Alias: h.Name, Source: FromStore, User: ep.User, Host: ep.Host, Port: ep.Port})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) isExplicit(alias string) bool {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
for _, n := range r.explicit {
|
||||||
|
if strings.EqualFold(n, alias) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve turns an alias into an Endpoint. Hosts named explicitly in the ssh
|
||||||
|
// config win over Store hosts with the same name; anything else not in the
|
||||||
|
// Store is resolved through the config (wildcard blocks apply, HostName
|
||||||
|
// defaults to the alias).
|
||||||
|
func (r *Resolver) Resolve(alias string) (Endpoint, error) {
|
||||||
|
alias = strings.TrimSpace(alias)
|
||||||
|
if alias == "" {
|
||||||
|
return Endpoint{}, errors.New("sshconfig: empty host name")
|
||||||
|
}
|
||||||
|
if r.opts.Store != nil && !r.isExplicit(alias) {
|
||||||
|
if h, ok := r.opts.Store.Find(alias); ok {
|
||||||
|
return h.Endpoint(r.opts.LocalUser), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return r.resolveConfig(alias, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) get(alias, key string) string {
|
||||||
|
r.mu.RLock()
|
||||||
|
cfg := r.cfg
|
||||||
|
r.mu.RUnlock()
|
||||||
|
v, _ := cfg.Get(strings.ToLower(alias), key)
|
||||||
|
return strings.ReplaceAll(strings.TrimSpace(v), hashMark, "#")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) getAll(alias, key string) []string {
|
||||||
|
r.mu.RLock()
|
||||||
|
cfg := r.cfg
|
||||||
|
r.mu.RUnlock()
|
||||||
|
vs, _ := cfg.GetAll(strings.ToLower(alias), key)
|
||||||
|
out := make([]string, 0, len(vs))
|
||||||
|
for _, v := range vs {
|
||||||
|
out = append(out, strings.ReplaceAll(strings.TrimSpace(v), hashMark, "#"))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Resolver) resolveConfig(alias string, depth int) (Endpoint, error) {
|
||||||
|
ep := Endpoint{Alias: alias, Port: DefaultPort}
|
||||||
|
ep.User = r.get(alias, "User")
|
||||||
|
if ep.User == "" {
|
||||||
|
ep.User = r.opts.LocalUser
|
||||||
|
}
|
||||||
|
ep.Host = r.get(alias, "HostName")
|
||||||
|
if ep.Host == "" {
|
||||||
|
ep.Host = alias
|
||||||
|
} else {
|
||||||
|
ep.Host = r.expandTokens(ep.Host, alias, ep.User)
|
||||||
|
}
|
||||||
|
if p := r.get(alias, "Port"); p != "" {
|
||||||
|
n, err := strconv.Atoi(p)
|
||||||
|
if err != nil || n <= 0 || n > 65535 {
|
||||||
|
return Endpoint{}, fmt.Errorf("sshconfig: host %s: invalid Port %q", alias, p)
|
||||||
|
}
|
||||||
|
ep.Port = n
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for _, id := range r.getAll(alias, "IdentityFile") {
|
||||||
|
if strings.EqualFold(id, "none") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p := r.expandPath(r.expandTokens(id, ep.Host, ep.User))
|
||||||
|
if !seen[p] {
|
||||||
|
seen[p] = true
|
||||||
|
ep.IdentityFiles = append(ep.IdentityFiles, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ep.IdentitiesOnly = strings.EqualFold(r.get(alias, "IdentitiesOnly"), "yes")
|
||||||
|
if v := r.get(alias, "ServerAliveInterval"); v != "" {
|
||||||
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||||
|
ep.ServerAliveInterval = time.Duration(n) * time.Second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v := r.get(alias, "ServerAliveCountMax"); v != "" {
|
||||||
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||||
|
ep.ServerAliveCountMax = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if v := r.get(alias, "ConnectTimeout"); v != "" {
|
||||||
|
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||||
|
ep.ConnectTimeout = time.Duration(n) * time.Second
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pj := r.get(alias, "ProxyJump"); pj != "" && !strings.EqualFold(pj, "none") {
|
||||||
|
if depth >= maxIncludeDepth {
|
||||||
|
return Endpoint{}, fmt.Errorf("sshconfig: host %s: ProxyJump chain too long", alias)
|
||||||
|
}
|
||||||
|
for _, hop := range strings.Split(pj, ",") {
|
||||||
|
h, err := r.parseHop(strings.TrimSpace(hop), depth+1)
|
||||||
|
if err != nil {
|
||||||
|
return Endpoint{}, fmt.Errorf("sshconfig: host %s: ProxyJump: %w", alias, err)
|
||||||
|
}
|
||||||
|
ep.ProxyJump = append(ep.ProxyJump, h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ep, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseHop resolves one ProxyJump element "[user@]host[:port]".
|
||||||
|
func (r *Resolver) parseHop(hop string, depth int) (Endpoint, error) {
|
||||||
|
hop = strings.TrimPrefix(hop, "ssh://")
|
||||||
|
var u string
|
||||||
|
if i := strings.LastIndex(hop, "@"); i >= 0 {
|
||||||
|
u, hop = hop[:i], hop[i+1:]
|
||||||
|
}
|
||||||
|
host, port := hop, ""
|
||||||
|
if h, p, err := net.SplitHostPort(hop); err == nil {
|
||||||
|
host, port = h, p
|
||||||
|
}
|
||||||
|
if host == "" {
|
||||||
|
return Endpoint{}, errors.New("empty hop")
|
||||||
|
}
|
||||||
|
ep, err := r.resolveConfig(host, depth)
|
||||||
|
if err != nil {
|
||||||
|
return Endpoint{}, err
|
||||||
|
}
|
||||||
|
if u != "" {
|
||||||
|
ep.User = u
|
||||||
|
}
|
||||||
|
if port != "" {
|
||||||
|
n, err := strconv.Atoi(port)
|
||||||
|
if err != nil || n <= 0 || n > 65535 {
|
||||||
|
return Endpoint{}, fmt.Errorf("invalid port %q", port)
|
||||||
|
}
|
||||||
|
ep.Port = n
|
||||||
|
}
|
||||||
|
return ep, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// expandTokens handles the ssh_config tokens that make sense here.
|
||||||
|
func (r *Resolver) expandTokens(s, host, remoteUser string) string {
|
||||||
|
if !strings.Contains(s, "%") {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
if s[i] != '%' || i+1 == len(s) {
|
||||||
|
b.WriteByte(s[i])
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
switch s[i] {
|
||||||
|
case '%':
|
||||||
|
b.WriteByte('%')
|
||||||
|
case 'h':
|
||||||
|
b.WriteString(host)
|
||||||
|
case 'd':
|
||||||
|
b.WriteString(r.opts.Home)
|
||||||
|
case 'u':
|
||||||
|
b.WriteString(r.opts.LocalUser)
|
||||||
|
case 'r':
|
||||||
|
b.WriteString(remoteUser)
|
||||||
|
default:
|
||||||
|
b.WriteByte('%')
|
||||||
|
b.WriteByte(s[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
// expandPath expands "~" and makes relative paths relative to ~/.ssh.
|
||||||
|
func (r *Resolver) expandPath(p string) string {
|
||||||
|
p = expandTilde(p, r.opts.Home)
|
||||||
|
if !filepath.IsAbs(p) && r.opts.Home != "" {
|
||||||
|
p = filepath.Join(r.opts.Home, ".ssh", p)
|
||||||
|
}
|
||||||
|
return filepath.Clean(p)
|
||||||
|
}
|
||||||
285
internal/ssh/sshconfig/resolver_test.go
Normal file
285
internal/ssh/sshconfig/resolver_test.go
Normal file
|
|
@ -0,0 +1,285 @@
|
||||||
|
package sshconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newTestResolver writes config text to home/.ssh/config and returns a
|
||||||
|
// Resolver over it.
|
||||||
|
func newTestResolver(t *testing.T, config string, store *Store) (*Resolver, string) {
|
||||||
|
t.Helper()
|
||||||
|
home := t.TempDir()
|
||||||
|
writeFile(t, filepath.Join(home, ".ssh", "config"), config)
|
||||||
|
r, err := NewResolver(Options{Home: home, LocalUser: "local", Store: store})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("NewResolver: %v", err)
|
||||||
|
}
|
||||||
|
return r, home
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(t *testing.T, p, s string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mustResolve(t *testing.T, r *Resolver, alias string) Endpoint {
|
||||||
|
t.Helper()
|
||||||
|
ep, err := r.Resolve(alias)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Resolve(%q): %v", alias, err)
|
||||||
|
}
|
||||||
|
return ep
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ported from the testbed (B10): a Host without HostName dialed ":22",
|
||||||
|
// i.e. localhost; "HostName=10.0.0.1" was not parsed at all (N-P1-5).
|
||||||
|
func TestConfigNoHostName(t *testing.T) {
|
||||||
|
r, _ := newTestResolver(t, "Host myserver.example.com\n User bob\nHost alias\n HostName=10.0.0.1\n", nil)
|
||||||
|
ep := mustResolve(t, r, "myserver.example.com")
|
||||||
|
if ep.Host != "myserver.example.com" || ep.User != "bob" || ep.Port != 22 {
|
||||||
|
t.Errorf("no HostName: got %+v", ep)
|
||||||
|
}
|
||||||
|
if got := ep.Addr(); got != "myserver.example.com:22" {
|
||||||
|
t.Errorf("Addr = %q", got)
|
||||||
|
}
|
||||||
|
ep = mustResolve(t, r, "alias")
|
||||||
|
if ep.Host != "10.0.0.1" {
|
||||||
|
t.Errorf("HostName=10.0.0.1: got Host %q", ep.Host)
|
||||||
|
}
|
||||||
|
if ep.User != "local" {
|
||||||
|
t.Errorf("default user: got %q", ep.User)
|
||||||
|
}
|
||||||
|
for _, h := range r.Hosts() {
|
||||||
|
if h.Host == "" {
|
||||||
|
t.Errorf("host %q has empty Host", h.Alias)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigEqualsAndSpaces(t *testing.T) {
|
||||||
|
r, _ := newTestResolver(t, "Host a\n HostName = 10.0.0.2\n Port=2222\n User\tcarol\n", nil)
|
||||||
|
ep := mustResolve(t, r, "a")
|
||||||
|
if ep.Host != "10.0.0.2" || ep.Port != 2222 || ep.User != "carol" {
|
||||||
|
t.Errorf("got %+v", ep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigHostStarDefaults(t *testing.T) {
|
||||||
|
cfg := `Host special
|
||||||
|
User alice
|
||||||
|
IdentityFile ~/.ssh/id_special
|
||||||
|
|
||||||
|
Host *
|
||||||
|
User defuser
|
||||||
|
IdentityFile ~/.ssh/id_star
|
||||||
|
ServerAliveInterval 7
|
||||||
|
ServerAliveCountMax 4
|
||||||
|
ConnectTimeout 3
|
||||||
|
`
|
||||||
|
r, home := newTestResolver(t, cfg, nil)
|
||||||
|
ep := mustResolve(t, r, "plain.example.com")
|
||||||
|
if ep.User != "defuser" {
|
||||||
|
t.Errorf("Host * User not applied: %q", ep.User)
|
||||||
|
}
|
||||||
|
if want := []string{filepath.Join(home, ".ssh", "id_star")}; !reflect.DeepEqual(ep.IdentityFiles, want) {
|
||||||
|
t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want)
|
||||||
|
}
|
||||||
|
if ep.ServerAliveInterval != 7*time.Second || ep.ServerAliveCountMax != 4 || ep.ConnectTimeout != 3*time.Second {
|
||||||
|
t.Errorf("alive/timeout: %+v", ep)
|
||||||
|
}
|
||||||
|
ep = mustResolve(t, r, "special")
|
||||||
|
if ep.User != "alice" {
|
||||||
|
t.Errorf("first match must win: User %q", ep.User)
|
||||||
|
}
|
||||||
|
want := []string{filepath.Join(home, ".ssh", "id_special"), filepath.Join(home, ".ssh", "id_star")}
|
||||||
|
if !reflect.DeepEqual(ep.IdentityFiles, want) {
|
||||||
|
t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want)
|
||||||
|
}
|
||||||
|
hosts := r.Hosts()
|
||||||
|
if len(hosts) != 1 || hosts[0].Alias != "special" {
|
||||||
|
t.Errorf("Hosts() must list only explicit hosts: %+v", hosts)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigMultipleIdentityFiles(t *testing.T) {
|
||||||
|
r, home := newTestResolver(t, "Host m\n IdentityFile ~/.ssh/one\n IdentityFile two\n IdentityFile /abs/three\n IdentityFile ~/.ssh/one\n IdentitiesOnly yes\n", nil)
|
||||||
|
ep := mustResolve(t, r, "m")
|
||||||
|
want := []string{filepath.Join(home, ".ssh", "one"), filepath.Join(home, ".ssh", "two"), "/abs/three"}
|
||||||
|
if !reflect.DeepEqual(ep.IdentityFiles, want) {
|
||||||
|
t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want)
|
||||||
|
}
|
||||||
|
if !ep.IdentitiesOnly {
|
||||||
|
t.Error("IdentitiesOnly not parsed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigQuotes(t *testing.T) {
|
||||||
|
r, home := newTestResolver(t, "Host q\n IdentityFile \"~/.ssh/my key\"\n HostName \"q.example.com\"\n", nil)
|
||||||
|
ep := mustResolve(t, r, "q")
|
||||||
|
if want := filepath.Join(home, ".ssh", "my key"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want {
|
||||||
|
t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want)
|
||||||
|
}
|
||||||
|
if ep.Host != "q.example.com" {
|
||||||
|
t.Errorf("Host = %q", ep.Host)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigHashInValue(t *testing.T) {
|
||||||
|
cfg := "# leading comment\nHost h # trailing comment on Host\n IdentityFile ~/.ssh/key#1 # real comment\n User \"u#2\"\n"
|
||||||
|
r, home := newTestResolver(t, cfg, nil)
|
||||||
|
ep := mustResolve(t, r, "h")
|
||||||
|
if want := filepath.Join(home, ".ssh", "key#1"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want {
|
||||||
|
t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want)
|
||||||
|
}
|
||||||
|
if ep.User != "u#2" {
|
||||||
|
t.Errorf("User = %q, want u#2", ep.User)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigInclude(t *testing.T) {
|
||||||
|
home := t.TempDir()
|
||||||
|
writeFile(t, filepath.Join(home, ".ssh", "conf.d", "10-work"), "Host work\n HostName work.example.com\n User worker\n")
|
||||||
|
writeFile(t, filepath.Join(home, ".ssh", "conf.d", "20-misc"), "Host misc\n Port 2200\n")
|
||||||
|
abs := filepath.Join(home, "elsewhere.conf")
|
||||||
|
writeFile(t, abs, "Host abs\n HostName 192.168.1.1\n")
|
||||||
|
cfg := "Include conf.d/*\nHost outer\n Include " + abs + "\n User outeruser\nHost *\n User fallback\n"
|
||||||
|
writeFile(t, filepath.Join(home, ".ssh", "config"), cfg)
|
||||||
|
r, err := NewResolver(Options{Home: home, LocalUser: "local"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ep := mustResolve(t, r, "work"); ep.Host != "work.example.com" || ep.User != "worker" {
|
||||||
|
t.Errorf("work: %+v", ep)
|
||||||
|
}
|
||||||
|
if ep := mustResolve(t, r, "misc"); ep.Port != 2200 || ep.User != "fallback" {
|
||||||
|
t.Errorf("misc: %+v", ep)
|
||||||
|
}
|
||||||
|
if ep := mustResolve(t, r, "abs"); ep.Host != "192.168.1.1" {
|
||||||
|
t.Errorf("abs: %+v", ep)
|
||||||
|
}
|
||||||
|
// Lines after an Include stay in the block that contained it.
|
||||||
|
if ep := mustResolve(t, r, "outer"); ep.User != "outeruser" {
|
||||||
|
t.Errorf("outer: User %q, want outeruser", ep.User)
|
||||||
|
}
|
||||||
|
var names []string
|
||||||
|
for _, h := range r.Hosts() {
|
||||||
|
names = append(names, h.Alias)
|
||||||
|
}
|
||||||
|
if want := []string{"work", "misc", "outer", "abs"}; !reflect.DeepEqual(names, want) {
|
||||||
|
t.Errorf("Hosts = %v, want %v", names, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigUnsupportedMatchIgnored(t *testing.T) {
|
||||||
|
cfg := "Match user root\n User ignored\nMatch host *.corp,10.*\n User corp\nHost x\n HostName x.example.com\n"
|
||||||
|
r, _ := newTestResolver(t, cfg, nil)
|
||||||
|
if ep := mustResolve(t, r, "x"); ep.User != "local" {
|
||||||
|
t.Errorf("unsupported Match applied: %+v", ep)
|
||||||
|
}
|
||||||
|
if ep := mustResolve(t, r, "a.corp"); ep.User != "corp" {
|
||||||
|
t.Errorf("Match host not applied: %+v", ep)
|
||||||
|
}
|
||||||
|
if len(r.Warnings()) != 1 {
|
||||||
|
t.Errorf("warnings = %v", r.Warnings())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigCaseInsensitiveHost(t *testing.T) {
|
||||||
|
r, _ := newTestResolver(t, "Host MyBox\n HostName 10.1.1.1\n", nil)
|
||||||
|
if ep := mustResolve(t, r, "mybox"); ep.Host != "10.1.1.1" {
|
||||||
|
t.Errorf("got %+v", ep)
|
||||||
|
}
|
||||||
|
if ep := mustResolve(t, r, "MYBOX"); ep.Host != "10.1.1.1" || ep.Alias != "MYBOX" {
|
||||||
|
t.Errorf("got %+v", ep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigInvalidPort(t *testing.T) {
|
||||||
|
r, _ := newTestResolver(t, "Host p\n Port abc\n", nil)
|
||||||
|
if _, err := r.Resolve("p"); err == nil {
|
||||||
|
t.Fatal("want error for invalid port")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigProxyJump(t *testing.T) {
|
||||||
|
r, _ := newTestResolver(t, "Host target\n ProxyJump admin@bastion:2022,hop2\nHost bastion\n HostName b.example.com\n", nil)
|
||||||
|
ep := mustResolve(t, r, "target")
|
||||||
|
if len(ep.ProxyJump) != 2 {
|
||||||
|
t.Fatalf("ProxyJump = %+v", ep.ProxyJump)
|
||||||
|
}
|
||||||
|
if h := ep.ProxyJump[0]; h.Host != "b.example.com" || h.User != "admin" || h.Port != 2022 {
|
||||||
|
t.Errorf("hop 1: %+v", h)
|
||||||
|
}
|
||||||
|
if h := ep.ProxyJump[1]; h.Host != "hop2" || h.Port != 22 {
|
||||||
|
t.Errorf("hop 2: %+v", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigMissingFile(t *testing.T) {
|
||||||
|
r, err := NewResolver(Options{Home: t.TempDir(), LocalUser: "me"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("missing config must not be an error: %v", err)
|
||||||
|
}
|
||||||
|
ep := mustResolve(t, r, "anything")
|
||||||
|
if ep.Host != "anything" || ep.User != "me" || ep.Port != 22 {
|
||||||
|
t.Errorf("got %+v", ep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// N-P2-3: SameAs ignored User, so two users on one host shared a client.
|
||||||
|
func TestEndpointKeyIncludesUser(t *testing.T) {
|
||||||
|
r, _ := newTestResolver(t, "Host a1\n HostName srv\n User alice\nHost a2\n HostName srv\n User alice\nHost b\n HostName srv\n User bob\n", nil)
|
||||||
|
a1, a2, b := mustResolve(t, r, "a1"), mustResolve(t, r, "a2"), mustResolve(t, r, "b")
|
||||||
|
if a1.Key() != a2.Key() {
|
||||||
|
t.Errorf("same user@host:port must share a key: %q vs %q", a1.Key(), a2.Key())
|
||||||
|
}
|
||||||
|
if a1.Key() == b.Key() {
|
||||||
|
t.Errorf("different users must not share a key: %q", a1.Key())
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(a1.Key(), "alice@") || a1.Key() != "alice@srv:22" {
|
||||||
|
t.Errorf("Key = %q", a1.Key())
|
||||||
|
}
|
||||||
|
v6 := Endpoint{User: "u", Host: "::1", Port: 2222}
|
||||||
|
if v6.Key() != "u@[::1]:2222" {
|
||||||
|
t.Errorf("IPv6 key = %q", v6.Key())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolverStoreHosts(t *testing.T) {
|
||||||
|
st, err := OpenStore(t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := st.Put(StoredHost{Name: "mine", HostName: "10.9.9.9", Port: 2022, User: "me", Password: "secret"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := st.Put(StoredHost{Name: "dup", HostName: "store.example.com"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
r, _ := newTestResolver(t, "Host dup\n HostName config.example.com\n", st)
|
||||||
|
ep := mustResolve(t, r, "mine")
|
||||||
|
if ep.Host != "10.9.9.9" || ep.Port != 2022 || ep.User != "me" || ep.Password != "secret" {
|
||||||
|
t.Errorf("store host: %+v", ep)
|
||||||
|
}
|
||||||
|
if ep := mustResolve(t, r, "dup"); ep.Host != "config.example.com" {
|
||||||
|
t.Errorf("ssh config must win over the store: %+v", ep)
|
||||||
|
}
|
||||||
|
hosts := r.Hosts()
|
||||||
|
if len(hosts) != 2 || hosts[0].Alias != "dup" || hosts[0].Source != FromSSHConfig ||
|
||||||
|
hosts[1].Alias != "mine" || hosts[1].Source != FromStore {
|
||||||
|
t.Errorf("Hosts = %+v", hosts)
|
||||||
|
}
|
||||||
|
if got := hosts[1].DisplayName(); got != "mine (me@10.9.9.9:2022)" {
|
||||||
|
t.Errorf("DisplayName = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
317
internal/ssh/sshconfig/store.go
Normal file
317
internal/ssh/sshconfig/store.go
Normal file
|
|
@ -0,0 +1,317 @@
|
||||||
|
package sshconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/aes"
|
||||||
|
"crypto/cipher"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"vcom/internal/atomicfile"
|
||||||
|
)
|
||||||
|
|
||||||
|
// File names inside the Store directory (compatible with vcom <= 0.2.x).
|
||||||
|
const (
|
||||||
|
HostsFile = "hosts.dat"
|
||||||
|
KeyFile = ".hosts-key"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrHostNotFound is returned by Store.Remove for an unknown name.
|
||||||
|
var ErrHostNotFound = errors.New("sshconfig: host not found")
|
||||||
|
|
||||||
|
// StoredHost is a host added in vcom.
|
||||||
|
type StoredHost struct {
|
||||||
|
Name string
|
||||||
|
HostName string
|
||||||
|
Port int // 0 = default
|
||||||
|
User string
|
||||||
|
Password string // plaintext in memory, encrypted on disk
|
||||||
|
IdentityFile string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Endpoint converts a stored host to an Endpoint; localUser is the default
|
||||||
|
// user.
|
||||||
|
func (h StoredHost) Endpoint(localUser string) Endpoint {
|
||||||
|
ep := Endpoint{
|
||||||
|
Alias: h.Name,
|
||||||
|
User: h.User,
|
||||||
|
Host: h.HostName,
|
||||||
|
Port: h.Port,
|
||||||
|
Password: h.Password,
|
||||||
|
}
|
||||||
|
if ep.Host == "" {
|
||||||
|
ep.Host = h.Name
|
||||||
|
}
|
||||||
|
if ep.Port <= 0 {
|
||||||
|
ep.Port = DefaultPort
|
||||||
|
}
|
||||||
|
if ep.User == "" {
|
||||||
|
ep.User = localUser
|
||||||
|
}
|
||||||
|
if h.IdentityFile != "" {
|
||||||
|
ep.IdentityFiles = []string{h.IdentityFile}
|
||||||
|
}
|
||||||
|
return ep
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store is vcom's own host list: hosts.dat, AES-256-GCM encrypted with the
|
||||||
|
// key in .hosts-key (both in the vcom config directory). Every save is
|
||||||
|
// atomic. It is safe for concurrent use.
|
||||||
|
type Store struct {
|
||||||
|
path string
|
||||||
|
key []byte
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
hosts []StoredHost
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenStore loads dir/hosts.dat, creating the encryption key if there is
|
||||||
|
// none yet. A missing hosts.dat means an empty list.
|
||||||
|
func OpenStore(dir string) (*Store, error) {
|
||||||
|
if dir == "" {
|
||||||
|
return nil, errors.New("sshconfig: empty store directory")
|
||||||
|
}
|
||||||
|
key, err := loadOrCreateKey(filepath.Join(dir, KeyFile))
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("sshconfig: hosts key: %w", err)
|
||||||
|
}
|
||||||
|
s := &Store{path: filepath.Join(dir, HostsFile), key: key}
|
||||||
|
if err := s.load(); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadOrCreateKey(path string) ([]byte, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err == nil {
|
||||||
|
key, derr := base64.StdEncoding.DecodeString(strings.TrimSpace(string(data)))
|
||||||
|
if derr == nil && len(key) == 32 {
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
// A damaged key must not be silently replaced: hosts.dat would become
|
||||||
|
// undecryptable for good.
|
||||||
|
return nil, fmt.Errorf("%s: invalid key", path)
|
||||||
|
}
|
||||||
|
if !errors.Is(err, os.ErrNotExist) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
key := make([]byte, 32)
|
||||||
|
if _, err := rand.Read(key); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := atomicfile.WriteFile(path, []byte(base64.StdEncoding.EncodeToString(key)), 0o600); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// On-disk format (unchanged from vcom 0.2.x).
|
||||||
|
type storedHosts struct {
|
||||||
|
Hosts []storedHost `json:"hosts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type storedHost struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
HostName string `json:"hostname"`
|
||||||
|
Port string `json:"port,omitempty"`
|
||||||
|
User string `json:"user,omitempty"`
|
||||||
|
Password string `json:"password,omitempty"` // encrypted
|
||||||
|
IdentityFile string `json:"identity_file,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) load() error {
|
||||||
|
data, err := os.ReadFile(s.path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
plain, err := decrypt(data, s.key)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("sshconfig: decrypt %s: %w", s.path, err)
|
||||||
|
}
|
||||||
|
var st storedHosts
|
||||||
|
if err := json.Unmarshal(plain, &st); err != nil {
|
||||||
|
return fmt.Errorf("sshconfig: parse %s: %w", s.path, err)
|
||||||
|
}
|
||||||
|
hosts := make([]StoredHost, 0, len(st.Hosts))
|
||||||
|
for _, h := range st.Hosts {
|
||||||
|
pw := decryptPassword(h.Password, s.key)
|
||||||
|
port, _ := strconv.Atoi(h.Port)
|
||||||
|
hosts = append(hosts, StoredHost{
|
||||||
|
Name: h.Name, HostName: h.HostName, Port: port, User: h.User,
|
||||||
|
Password: pw, IdentityFile: h.IdentityFile,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
s.hosts = hosts
|
||||||
|
s.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// save writes hosts.dat; the caller holds s.mu.
|
||||||
|
func (s *Store) save() error {
|
||||||
|
st := storedHosts{Hosts: make([]storedHost, 0, len(s.hosts))}
|
||||||
|
for _, h := range s.hosts {
|
||||||
|
pw := ""
|
||||||
|
if h.Password != "" {
|
||||||
|
enc, err := encrypt([]byte(h.Password), s.key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pw = base64.StdEncoding.EncodeToString(enc)
|
||||||
|
}
|
||||||
|
port := ""
|
||||||
|
if h.Port > 0 {
|
||||||
|
port = strconv.Itoa(h.Port)
|
||||||
|
}
|
||||||
|
st.Hosts = append(st.Hosts, storedHost{
|
||||||
|
Name: h.Name, HostName: h.HostName, Port: port, User: h.User,
|
||||||
|
Password: pw, IdentityFile: h.IdentityFile,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
data, err := json.Marshal(st)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
enc, err := encrypt(data, s.key)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return atomicfile.WriteFile(s.path, enc, 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hosts returns a copy of the stored hosts.
|
||||||
|
func (s *Store) Hosts() []StoredHost {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return append([]StoredHost(nil), s.hosts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find looks a host up by name (case-insensitive).
|
||||||
|
func (s *Store) Find(name string) (StoredHost, bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
for _, h := range s.hosts {
|
||||||
|
if strings.EqualFold(h.Name, name) {
|
||||||
|
return h, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return StoredHost{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put adds h, replacing a host with the same name, and saves. On a save
|
||||||
|
// error the in-memory list is left unchanged.
|
||||||
|
func (s *Store) Put(h StoredHost) error {
|
||||||
|
if strings.TrimSpace(h.Name) == "" {
|
||||||
|
return errors.New("sshconfig: host name is required")
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
old := s.hosts
|
||||||
|
next := make([]StoredHost, 0, len(old)+1)
|
||||||
|
replaced := false
|
||||||
|
for _, x := range old {
|
||||||
|
if strings.EqualFold(x.Name, h.Name) {
|
||||||
|
next = append(next, h)
|
||||||
|
replaced = true
|
||||||
|
} else {
|
||||||
|
next = append(next, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !replaced {
|
||||||
|
next = append(next, h)
|
||||||
|
}
|
||||||
|
s.hosts = next
|
||||||
|
if err := s.save(); err != nil {
|
||||||
|
s.hosts = old
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove deletes a host by name and saves.
|
||||||
|
func (s *Store) Remove(name string) error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
old := s.hosts
|
||||||
|
next := make([]StoredHost, 0, len(old))
|
||||||
|
for _, x := range old {
|
||||||
|
if !strings.EqualFold(x.Name, name) {
|
||||||
|
next = append(next, x)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(next) == len(old) {
|
||||||
|
return fmt.Errorf("%w: %s", ErrHostNotFound, name)
|
||||||
|
}
|
||||||
|
s.hosts = next
|
||||||
|
if err := s.save(); err != nil {
|
||||||
|
s.hosts = old
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// decryptPassword reads the password field. vcom <= 0.2.x stored the raw
|
||||||
|
// ciphertext as a JSON string, which json.Marshal mangles (invalid UTF-8
|
||||||
|
// becomes U+FFFD), so such passwords usually cannot be recovered; the field
|
||||||
|
// is now base64. Both forms are tried; failure yields "".
|
||||||
|
func decryptPassword(field string, key []byte) string {
|
||||||
|
if field == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if raw, err := base64.StdEncoding.DecodeString(field); err == nil {
|
||||||
|
if p, err := decrypt(raw, key); err == nil {
|
||||||
|
return string(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p, err := decrypt([]byte(field), key); err == nil {
|
||||||
|
return string(p)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func encrypt(plaintext, key []byte) ([]byte, error) {
|
||||||
|
gcm, err := newGCM(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
nonce := make([]byte, gcm.NonceSize())
|
||||||
|
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return gcm.Seal(nonce, nonce, plaintext, nil), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decrypt(ciphertext, key []byte) ([]byte, error) {
|
||||||
|
gcm, err := newGCM(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
n := gcm.NonceSize()
|
||||||
|
if len(ciphertext) < n {
|
||||||
|
return nil, errors.New("ciphertext too short")
|
||||||
|
}
|
||||||
|
return gcm.Open(nil, ciphertext[:n], ciphertext[n:], nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newGCM(key []byte) (cipher.AEAD, error) {
|
||||||
|
block, err := aes.NewCipher(key)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return cipher.NewGCM(block)
|
||||||
|
}
|
||||||
102
internal/ssh/sshconfig/store_test.go
Normal file
102
internal/ssh/sshconfig/store_test.go
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
package sshconfig
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStoreRoundTrip(t *testing.T) {
|
||||||
|
dir := filepath.Join(t.TempDir(), "vcom")
|
||||||
|
st, err := OpenStore(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
h := StoredHost{Name: "box", HostName: "10.0.0.5", Port: 2200, User: "root", Password: "hunter2", IdentityFile: "/k"}
|
||||||
|
if err := st.Put(h); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(filepath.Join(dir, HostsFile))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if bytes.Contains(raw, []byte("hunter2")) || bytes.Contains(raw, []byte("10.0.0.5")) {
|
||||||
|
t.Fatal("hosts.dat must be encrypted")
|
||||||
|
}
|
||||||
|
for _, name := range []string{HostsFile, KeyFile} {
|
||||||
|
fi, err := os.Stat(filepath.Join(dir, name))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Errorf("%s mode = %v", name, fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
st2, err := OpenStore(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, ok := st2.Find("BOX")
|
||||||
|
if !ok || got != h {
|
||||||
|
t.Fatalf("reloaded = %+v (ok=%v), want %+v", got, ok, h)
|
||||||
|
}
|
||||||
|
|
||||||
|
h.Password = "changed"
|
||||||
|
if err := st2.Put(h); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if hs := st2.Hosts(); len(hs) != 1 || hs[0].Password != "changed" {
|
||||||
|
t.Errorf("Put must replace by name: %+v", hs)
|
||||||
|
}
|
||||||
|
if err := st2.Remove("box"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := st2.Remove("box"); !errors.Is(err, ErrHostNotFound) {
|
||||||
|
t.Errorf("Remove unknown: %v", err)
|
||||||
|
}
|
||||||
|
ents, _ := os.ReadDir(dir)
|
||||||
|
for _, e := range ents {
|
||||||
|
if e.Name() != HostsFile && e.Name() != KeyFile {
|
||||||
|
t.Errorf("leftover file %s (atomic write must clean up)", e.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStoreDamagedKeyNotReplaced(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
writeFile(t, filepath.Join(dir, KeyFile), "not base64 !!")
|
||||||
|
if _, err := OpenStore(dir); err == nil {
|
||||||
|
t.Fatal("damaged key must be an error")
|
||||||
|
}
|
||||||
|
b, _ := os.ReadFile(filepath.Join(dir, KeyFile))
|
||||||
|
if string(b) != "not base64 !!" {
|
||||||
|
t.Fatal("damaged key was overwritten")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStoreSaveFailureKeepsState(t *testing.T) {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("root ignores directory permissions")
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
st, err := OpenStore(dir)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := st.Put(StoredHost{Name: "a"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(dir, 0o500); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer os.Chmod(dir, 0o700)
|
||||||
|
if err := st.Put(StoredHost{Name: "b"}); err == nil {
|
||||||
|
t.Fatal("Put into read-only dir must fail")
|
||||||
|
}
|
||||||
|
if hs := st.Hosts(); len(hs) != 1 || hs[0].Name != "a" {
|
||||||
|
t.Errorf("failed save changed state: %+v", hs)
|
||||||
|
}
|
||||||
|
}
|
||||||
114
internal/state/qa_rc2_test.go
Normal file
114
internal/state/qa_rc2_test.go
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
package state
|
||||||
|
|
||||||
|
// QA (v0.2.8 RC2): session edge cases (stage 2C.3).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func qaWrite(t *testing.T, p, s string) {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, []byte(s), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestQASessionEmptyAndBroken(t *testing.T) {
|
||||||
|
home := isolate(t)
|
||||||
|
p := filepath.Join(home, ".local", "state", "vcom", "session.toml")
|
||||||
|
qaWrite(t, p, "")
|
||||||
|
if s, err := Load(); err != nil || s.Left.Path != "" {
|
||||||
|
t.Fatalf("empty session: %+v %v", s, err)
|
||||||
|
}
|
||||||
|
qaWrite(t, p, "active_pane = 'left'\n[left\npath = '/x'\n")
|
||||||
|
if _, err := Load(); err == nil {
|
||||||
|
t.Fatal("broken session must report an error")
|
||||||
|
}
|
||||||
|
// A broken new file must not trigger migration from the old one.
|
||||||
|
old := filepath.Join(home, ".config", "vcom", "session.toml")
|
||||||
|
qaWrite(t, old, "active_pane = 'right'\n")
|
||||||
|
_, _ = Load()
|
||||||
|
if _, err := os.Stat(old); err != nil {
|
||||||
|
t.Fatal("old session removed although the new one is broken")
|
||||||
|
}
|
||||||
|
// Saving replaces the broken file with a valid one.
|
||||||
|
if err := Save(Session{ActivePane: "right"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s, err := Load(); err != nil || s.ActivePane != "right" {
|
||||||
|
t.Fatalf("after save: %+v %v", s, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A broken OLD session is neither migrated nor deleted.
|
||||||
|
func TestQASessionBrokenOldKept(t *testing.T) {
|
||||||
|
home := isolate(t)
|
||||||
|
old := filepath.Join(home, ".config", "vcom", "session.toml")
|
||||||
|
qaWrite(t, old, "[[[")
|
||||||
|
if _, err := Load(); err == nil {
|
||||||
|
t.Fatal("broken old session must report an error")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(old); err != nil {
|
||||||
|
t.Fatal("broken old session deleted")
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("broken old session migrated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Session as a symlink (dotfiles) stays a symlink.
|
||||||
|
func TestQASessionSymlink(t *testing.T) {
|
||||||
|
home := isolate(t)
|
||||||
|
target := filepath.Join(home, "elsewhere", "session.toml")
|
||||||
|
qaWrite(t, target, "active_pane = 'left'\n")
|
||||||
|
p := filepath.Join(home, ".local", "state", "vcom", "session.toml")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(target, p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := Save(Session{ActivePane: "right"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Lstat(p); fi.Mode()&os.ModeSymlink == 0 {
|
||||||
|
t.Fatal("session symlink replaced")
|
||||||
|
}
|
||||||
|
if s, _ := Load(); s.ActivePane != "right" {
|
||||||
|
t.Fatal("target not updated")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// When the new state dir cannot be written, Load returns the old session
|
||||||
|
// AND an error; the caller (ui.applySession) drops the session on any
|
||||||
|
// error, so the user loses the restored panes although they were read.
|
||||||
|
func TestQASessionMigrationUnwritableStateDir(t *testing.T) {
|
||||||
|
if os.Geteuid() == 0 {
|
||||||
|
t.Skip("root ignores permissions")
|
||||||
|
}
|
||||||
|
home := isolate(t)
|
||||||
|
old := filepath.Join(home, ".config", "vcom", "session.toml")
|
||||||
|
qaWrite(t, old, "active_pane = 'right'\n[left]\npath = '/tmp'\n")
|
||||||
|
ro := filepath.Join(home, "ro")
|
||||||
|
if err := os.MkdirAll(ro, 0o500); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { os.Chmod(ro, 0o700) })
|
||||||
|
t.Setenv("XDG_STATE_HOME", filepath.Join(ro, "state"))
|
||||||
|
s, err := Load()
|
||||||
|
if s.ActivePane != "right" {
|
||||||
|
t.Fatalf("old session not returned: %+v %v", s, err)
|
||||||
|
}
|
||||||
|
if _, serr := os.Stat(old); serr != nil {
|
||||||
|
t.Fatal("old session removed although migration failed")
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected a migration error")
|
||||||
|
}
|
||||||
|
// Documented in the report as QA-16: ui.applySession ignores s when err != nil.
|
||||||
|
}
|
||||||
184
internal/state/session.go
Normal file
184
internal/state/session.go
Normal file
|
|
@ -0,0 +1,184 @@
|
||||||
|
// Package state persists the UI session (design §9.1, §9.2):
|
||||||
|
// $XDG_STATE_HOME/vcom/session.toml, written atomically, migrated once from
|
||||||
|
// the pre-0.3 location next to the config.
|
||||||
|
package state
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
toml "github.com/pelletier/go-toml/v2"
|
||||||
|
|
||||||
|
"vcom/internal/atomicfile"
|
||||||
|
"vcom/internal/paths"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxCursorMemory bounds the remembered "cursor per directory" entries per pane.
|
||||||
|
const MaxCursorMemory = 200
|
||||||
|
|
||||||
|
// Session is the UI state restored on the next launch.
|
||||||
|
type Session struct {
|
||||||
|
ActivePane string `toml:"active_pane"`
|
||||||
|
Left PaneSession `toml:"left"`
|
||||||
|
Right PaneSession `toml:"right"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// PaneSession is one pane's state: its directory, the selected entry and the
|
||||||
|
// last selected entry per visited directory.
|
||||||
|
type PaneSession struct {
|
||||||
|
Path string `toml:"path"`
|
||||||
|
EntryName string `toml:"entry_name"`
|
||||||
|
CursorMemory map[string]string `toml:"cursor_memory"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// File is the session path: StateDir/session.toml.
|
||||||
|
func File() (string, error) {
|
||||||
|
d, err := paths.StateDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(d, "session.toml"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load reads the session. A missing file is not an error (zero Session). If
|
||||||
|
// only the old file (~/.config/vcom/session.toml) exists, it is read, saved
|
||||||
|
// to the new location and removed — except under sudo, where the old file
|
||||||
|
// belongs to the invoking user and is left alone.
|
||||||
|
func Load() (Session, error) {
|
||||||
|
p, err := File()
|
||||||
|
if err != nil {
|
||||||
|
return Session{}, err
|
||||||
|
}
|
||||||
|
s, err := read(p)
|
||||||
|
if err == nil || !errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return s, err
|
||||||
|
}
|
||||||
|
old, oerr := paths.OldSessionFile()
|
||||||
|
if oerr != nil {
|
||||||
|
return Session{}, nil
|
||||||
|
}
|
||||||
|
s, err = read(old)
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return Session{}, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return Session{}, err
|
||||||
|
}
|
||||||
|
if err := Save(s); err != nil {
|
||||||
|
return s, fmt.Errorf("migrate session from %s: %w", old, err)
|
||||||
|
}
|
||||||
|
if _, sudo := paths.SudoUser(); !sudo {
|
||||||
|
_ = os.Remove(old)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func read(p string) (Session, error) {
|
||||||
|
data, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return Session{}, err
|
||||||
|
}
|
||||||
|
var s Session
|
||||||
|
if err := toml.Unmarshal(data, &s); err != nil {
|
||||||
|
return Session{}, fmt.Errorf("parse %s: %w", p, err)
|
||||||
|
}
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save normalises s (see Normalize) and writes it atomically (0600) into a
|
||||||
|
// 0700 state directory.
|
||||||
|
func Save(s Session) error {
|
||||||
|
p, err := File()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := paths.EnsureDir(filepath.Dir(p)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.Normalize(transientPrefixes())
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := toml.NewEncoder(&buf).Encode(s); err != nil {
|
||||||
|
return fmt.Errorf("encode session: %w", err)
|
||||||
|
}
|
||||||
|
return atomicfile.WriteFile(p, buf.Bytes(), 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// transientPrefixes are directories whose paths are not worth remembering:
|
||||||
|
// vcom's cache/run dirs and the old UI's temp mounts.
|
||||||
|
func transientPrefixes() []string {
|
||||||
|
var out []string
|
||||||
|
if c, err := paths.CacheDir(); err == nil {
|
||||||
|
out = append(out, c)
|
||||||
|
}
|
||||||
|
tmp := os.TempDir()
|
||||||
|
out = append(out, filepath.Join(tmp, "vcom-archive-"), filepath.Join(tmp, "vcom-remote-"))
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize drops cursor-memory entries under any of the transient prefixes
|
||||||
|
// and caps each pane at MaxCursorMemory entries.
|
||||||
|
func (s *Session) Normalize(transient []string) {
|
||||||
|
s.Left.CursorMemory = capMemory(s.Left.CursorMemory, s.Left.Path, transient)
|
||||||
|
s.Right.CursorMemory = capMemory(s.Right.CursorMemory, s.Right.Path, transient)
|
||||||
|
}
|
||||||
|
|
||||||
|
// capMemory keeps at most MaxCursorMemory entries. The map carries no
|
||||||
|
// recency, so it keeps first the entries on the pane's current path (its
|
||||||
|
// ancestors and descendants: where the user is most likely to go back), then
|
||||||
|
// the rest in path order. Deterministic, which keeps the file diff-friendly.
|
||||||
|
func capMemory(m map[string]string, current string, transient []string) map[string]string {
|
||||||
|
if len(m) == 0 {
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
keys := make([]string, 0, len(m))
|
||||||
|
for k, v := range m {
|
||||||
|
if k == "" || v == "" || hasAnyPrefix(k, transient) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
related := func(k string) bool {
|
||||||
|
return current != "" && (isWithin(k, current) || isWithin(current, k))
|
||||||
|
}
|
||||||
|
sort.Slice(keys, func(i, j int) bool {
|
||||||
|
ri, rj := related(keys[i]), related(keys[j])
|
||||||
|
if ri != rj {
|
||||||
|
return ri
|
||||||
|
}
|
||||||
|
return keys[i] < keys[j]
|
||||||
|
})
|
||||||
|
if len(keys) > MaxCursorMemory {
|
||||||
|
keys = keys[:MaxCursorMemory]
|
||||||
|
}
|
||||||
|
out := make(map[string]string, len(keys))
|
||||||
|
for _, k := range keys {
|
||||||
|
out[k] = m[k]
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasAnyPrefix(p string, prefixes []string) bool {
|
||||||
|
for _, pre := range prefixes {
|
||||||
|
if pre != "" && (p == pre || strings.HasPrefix(p, pre)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func isWithin(child, parent string) bool {
|
||||||
|
child, parent = filepath.Clean(child), filepath.Clean(parent)
|
||||||
|
if child == parent {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(parent, string(filepath.Separator)) {
|
||||||
|
parent += string(filepath.Separator)
|
||||||
|
}
|
||||||
|
return strings.HasPrefix(child, parent)
|
||||||
|
}
|
||||||
121
internal/state/session_test.go
Normal file
121
internal/state/session_test.go
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
package state
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
// isolate points HOME and the XDG dirs at a temp dir.
|
||||||
|
func isolate(t *testing.T) (home string) {
|
||||||
|
home = t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||||
|
t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state"))
|
||||||
|
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
|
||||||
|
t.Setenv("SUDO_USER", "")
|
||||||
|
return home
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionAtomic(t *testing.T) {
|
||||||
|
home := isolate(t)
|
||||||
|
s := Session{ActivePane: "right", Left: PaneSession{Path: "/a", EntryName: "x"}}
|
||||||
|
if err := Save(s); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
dir := filepath.Join(home, ".local", "state", "vcom")
|
||||||
|
p := filepath.Join(dir, "session.toml")
|
||||||
|
if fi, err := os.Stat(p); err != nil || fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("session file: %v %v", fi, err)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(dir); fi.Mode().Perm() != 0o700 {
|
||||||
|
t.Fatalf("state dir mode %v", fi.Mode().Perm())
|
||||||
|
}
|
||||||
|
got, err := Load()
|
||||||
|
if err != nil || got.ActivePane != "right" || got.Left.EntryName != "x" {
|
||||||
|
t.Fatalf("round trip: %+v %v", got, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A failing write leaves the previous session intact and no temp files.
|
||||||
|
if os.Geteuid() != 0 {
|
||||||
|
before, _ := os.ReadFile(p)
|
||||||
|
if err := os.Chmod(dir, 0o500); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = os.Chmod(dir, 0o700) })
|
||||||
|
if err := Save(Session{ActivePane: "left"}); err == nil {
|
||||||
|
t.Fatal("save into a read-only dir succeeded")
|
||||||
|
}
|
||||||
|
_ = os.Chmod(dir, 0o700)
|
||||||
|
after, _ := os.ReadFile(p)
|
||||||
|
if string(before) != string(after) {
|
||||||
|
t.Fatal("old session damaged by a failed save")
|
||||||
|
}
|
||||||
|
if ents, _ := os.ReadDir(dir); len(ents) != 1 {
|
||||||
|
t.Fatalf("leftovers in state dir: %v", ents)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionMigratesFromOldPath(t *testing.T) {
|
||||||
|
home := isolate(t)
|
||||||
|
old := filepath.Join(home, ".config", "vcom", "session.toml")
|
||||||
|
if err := os.MkdirAll(filepath.Dir(old), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
content := "active_pane = 'right'\n[left]\npath = '/srv'\nentry_name = 'data'\n[left.cursor_memory]\n'/srv' = 'data'\n"
|
||||||
|
if err := os.WriteFile(old, []byte(content), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s.ActivePane != "right" || s.Left.Path != "/srv" || s.Left.CursorMemory["/srv"] != "data" {
|
||||||
|
t.Fatalf("migrated %+v", s)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(home, ".local", "state", "vcom", "session.toml")); err != nil {
|
||||||
|
t.Fatalf("not written to the new location: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(old); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("old session file not removed after migration")
|
||||||
|
}
|
||||||
|
// Nothing anywhere: empty session, no error.
|
||||||
|
isolate(t)
|
||||||
|
if s, err := Load(); err != nil || s.ActivePane != "" {
|
||||||
|
t.Fatalf("empty: %+v %v", s, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCursorMemoryCapped(t *testing.T) {
|
||||||
|
home := isolate(t)
|
||||||
|
mem := map[string]string{}
|
||||||
|
for i := range 500 {
|
||||||
|
mem[fmt.Sprintf("/data/d%03d", i)] = "f"
|
||||||
|
}
|
||||||
|
mem["/work/project/src"] = "main.go"
|
||||||
|
mem["/work"] = "project"
|
||||||
|
cache := filepath.Join(home, ".cache", "vcom", "run-1", "preview")
|
||||||
|
mem[cache] = "img.png"
|
||||||
|
mem[filepath.Join(os.TempDir(), "vcom-archive-123", "x")] = "y"
|
||||||
|
if err := Save(Session{Left: PaneSession{Path: "/work/project", CursorMemory: mem}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s, err := Load()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got := s.Left.CursorMemory
|
||||||
|
if len(got) != MaxCursorMemory {
|
||||||
|
t.Fatalf("%d entries, want %d", len(got), MaxCursorMemory)
|
||||||
|
}
|
||||||
|
if got["/work/project/src"] != "main.go" || got["/work"] != "project" {
|
||||||
|
t.Fatal("entries on the current path must survive the cap")
|
||||||
|
}
|
||||||
|
for k := range got {
|
||||||
|
if k == cache || filepath.Dir(k) == filepath.Join(os.TempDir(), "vcom-archive-123") {
|
||||||
|
t.Fatalf("transient path kept: %s", k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
320
internal/testutil/fstree/fstree.go
Normal file
320
internal/testutil/fstree/fstree.go
Normal file
|
|
@ -0,0 +1,320 @@
|
||||||
|
// Package fstree builds, snapshots and compares directory trees in tests.
|
||||||
|
//
|
||||||
|
// spec := fstree.Spec{
|
||||||
|
// fstree.File("a.txt", "hello"),
|
||||||
|
// fstree.Dir("ro").WithMode(0o555),
|
||||||
|
// fstree.File("ro/b.bin", "").WithSize(1 << 20),
|
||||||
|
// fstree.Symlink("link", "a.txt"),
|
||||||
|
// }
|
||||||
|
// fstree.Build(t, src, spec)
|
||||||
|
// ... copy src -> dst ...
|
||||||
|
// fstree.Equal(t, fstree.Snapshot(t, src), fstree.Snapshot(t, dst), fstree.Opts{Mode: true, Links: true})
|
||||||
|
package fstree
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Kind of a tree node.
|
||||||
|
type Kind int
|
||||||
|
|
||||||
|
const (
|
||||||
|
KindFile Kind = iota
|
||||||
|
KindDir
|
||||||
|
KindSymlink
|
||||||
|
KindFIFO
|
||||||
|
KindOther
|
||||||
|
)
|
||||||
|
|
||||||
|
func (k Kind) String() string {
|
||||||
|
switch k {
|
||||||
|
case KindFile:
|
||||||
|
return "file"
|
||||||
|
case KindDir:
|
||||||
|
return "dir"
|
||||||
|
case KindSymlink:
|
||||||
|
return "symlink"
|
||||||
|
case KindFIFO:
|
||||||
|
return "fifo"
|
||||||
|
}
|
||||||
|
return "other"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry describes one node to create. Path is slash-separated and relative
|
||||||
|
// to the root passed to Build.
|
||||||
|
type Entry struct {
|
||||||
|
Path string
|
||||||
|
Kind Kind
|
||||||
|
Content []byte
|
||||||
|
// Size, when > 0 and Content is empty, fills the file with a
|
||||||
|
// deterministic pattern of that many bytes.
|
||||||
|
Size int64
|
||||||
|
// Mode is the permission bits; 0 means 0644 for files/FIFOs, 0755 for dirs.
|
||||||
|
Mode fs.FileMode
|
||||||
|
// MTime is applied after the whole tree is built; zero leaves it alone
|
||||||
|
// (and means "don't care" when the spec is used as an expectation).
|
||||||
|
MTime time.Time
|
||||||
|
Target string // symlink target
|
||||||
|
}
|
||||||
|
|
||||||
|
// File, Dir, Symlink and FIFO construct entries.
|
||||||
|
func File(p, content string) Entry { return Entry{Path: p, Kind: KindFile, Content: []byte(content)} }
|
||||||
|
func Dir(p string) Entry { return Entry{Path: p, Kind: KindDir} }
|
||||||
|
func Symlink(p, target string) Entry {
|
||||||
|
return Entry{Path: p, Kind: KindSymlink, Target: target}
|
||||||
|
}
|
||||||
|
func FIFO(p string) Entry { return Entry{Path: p, Kind: KindFIFO} }
|
||||||
|
|
||||||
|
// WithMode, WithMTime and WithSize return a modified copy.
|
||||||
|
func (e Entry) WithMode(m fs.FileMode) Entry { e.Mode = m; return e }
|
||||||
|
func (e Entry) WithMTime(t time.Time) Entry { e.MTime = t; return e }
|
||||||
|
func (e Entry) WithSize(n int64) Entry { e.Size = n; return e }
|
||||||
|
func (e Entry) WithContent(b []byte) Entry { e.Content = b; return e }
|
||||||
|
|
||||||
|
// Spec is a list of entries; parents are created implicitly (0755).
|
||||||
|
type Spec []Entry
|
||||||
|
|
||||||
|
func (e Entry) data() []byte {
|
||||||
|
if len(e.Content) > 0 || e.Size <= 0 {
|
||||||
|
return e.Content
|
||||||
|
}
|
||||||
|
b := make([]byte, e.Size)
|
||||||
|
for i := range b {
|
||||||
|
b[i] = byte(i % 251)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e Entry) perm() fs.FileMode {
|
||||||
|
if e.Mode != 0 {
|
||||||
|
return e.Mode.Perm()
|
||||||
|
}
|
||||||
|
if e.Kind == KindDir {
|
||||||
|
return 0o755
|
||||||
|
}
|
||||||
|
return 0o644
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build creates spec under root (which must exist). Directory modes and all
|
||||||
|
// mtimes are applied after every node exists, deepest first, so a 0555
|
||||||
|
// directory can still be populated. A Cleanup restores write permission on
|
||||||
|
// directories so t.TempDir removal works.
|
||||||
|
func Build(t testing.TB, root string, spec Spec) {
|
||||||
|
t.Helper()
|
||||||
|
sorted := append(Spec(nil), spec...)
|
||||||
|
sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Path < sorted[j].Path })
|
||||||
|
var dirs []string
|
||||||
|
t.Cleanup(func() {
|
||||||
|
for _, d := range dirs {
|
||||||
|
os.Chmod(d, 0o755)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
for _, e := range sorted {
|
||||||
|
p := filepath.Join(root, filepath.FromSlash(e.Path))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatalf("fstree: %v", err)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
switch e.Kind {
|
||||||
|
case KindFile:
|
||||||
|
err = os.WriteFile(p, e.data(), 0o600)
|
||||||
|
if err == nil {
|
||||||
|
err = os.Chmod(p, e.perm())
|
||||||
|
}
|
||||||
|
case KindDir:
|
||||||
|
err = os.MkdirAll(p, 0o755)
|
||||||
|
dirs = append(dirs, p)
|
||||||
|
case KindSymlink:
|
||||||
|
err = os.Symlink(e.Target, p)
|
||||||
|
case KindFIFO:
|
||||||
|
err = syscall.Mkfifo(p, 0o600)
|
||||||
|
if err == nil {
|
||||||
|
err = os.Chmod(p, e.perm())
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
err = fmt.Errorf("unsupported kind %v", e.Kind)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fstree: build %s: %v", e.Path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Deepest first so setting a parent's mtime/mode comes last.
|
||||||
|
for i := len(sorted) - 1; i >= 0; i-- {
|
||||||
|
e := sorted[i]
|
||||||
|
p := filepath.Join(root, filepath.FromSlash(e.Path))
|
||||||
|
if !e.MTime.IsZero() && e.Kind != KindSymlink {
|
||||||
|
if err := os.Chtimes(p, e.MTime, e.MTime); err != nil {
|
||||||
|
t.Fatalf("fstree: chtimes %s: %v", e.Path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if e.Kind == KindDir {
|
||||||
|
if err := os.Chmod(p, e.perm()); err != nil {
|
||||||
|
t.Fatalf("fstree: chmod %s: %v", e.Path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Node is one entry of a snapshot.
|
||||||
|
type Node struct {
|
||||||
|
Kind Kind
|
||||||
|
Mode fs.FileMode // permission bits; 0 in an expectation means "don't care"
|
||||||
|
Data []byte // file content
|
||||||
|
MTime time.Time // zero in an expectation means "don't care"
|
||||||
|
Target string // symlink target
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tree maps slash-separated relative paths to nodes (root excluded).
|
||||||
|
type Tree map[string]Node
|
||||||
|
|
||||||
|
// FromSpec turns a spec into the tree Build would produce, for use as an
|
||||||
|
// expectation. Implicit parent directories are included with mode 0755.
|
||||||
|
func FromSpec(spec Spec) Tree {
|
||||||
|
tr := Tree{}
|
||||||
|
for _, e := range spec {
|
||||||
|
for d := path.Dir(e.Path); d != "." && d != "/"; d = path.Dir(d) {
|
||||||
|
if _, ok := tr[d]; !ok {
|
||||||
|
tr[d] = Node{Kind: KindDir, Mode: 0o755}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n := Node{Kind: e.Kind, Mode: e.perm(), MTime: e.MTime}
|
||||||
|
switch e.Kind {
|
||||||
|
case KindFile:
|
||||||
|
n.Data = e.data()
|
||||||
|
case KindSymlink:
|
||||||
|
n.Mode, n.MTime, n.Target = 0, time.Time{}, e.Target
|
||||||
|
}
|
||||||
|
tr[e.Path] = n
|
||||||
|
}
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Snapshot reads the tree under root without following symlinks.
|
||||||
|
func Snapshot(t testing.TB, root string) Tree {
|
||||||
|
t.Helper()
|
||||||
|
tr := Tree{}
|
||||||
|
err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if p == root {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rel, _ := filepath.Rel(root, p)
|
||||||
|
rel = filepath.ToSlash(rel)
|
||||||
|
info, err := d.Info()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n := Node{Mode: info.Mode().Perm(), MTime: info.ModTime()}
|
||||||
|
switch m := info.Mode(); {
|
||||||
|
case m.IsRegular():
|
||||||
|
n.Kind = KindFile
|
||||||
|
b, err := os.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
n.Data = b
|
||||||
|
case m.IsDir():
|
||||||
|
n.Kind = KindDir
|
||||||
|
case m&fs.ModeSymlink != 0:
|
||||||
|
n.Kind = KindSymlink
|
||||||
|
n.Target, err = os.Readlink(p)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
case m&fs.ModeNamedPipe != 0:
|
||||||
|
n.Kind = KindFIFO
|
||||||
|
default:
|
||||||
|
n.Kind = KindOther
|
||||||
|
}
|
||||||
|
tr[rel] = n
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("fstree: snapshot %s: %v", root, err)
|
||||||
|
}
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
// Opts selects what Equal compares besides kind and file content.
|
||||||
|
type Opts struct {
|
||||||
|
Mode bool // permission bits (skipped where want.Mode == 0)
|
||||||
|
MTime bool // mtime at 1 s granularity (skipped where want.MTime is zero); dirs included
|
||||||
|
Links bool // compare symlinks and their targets; false ignores symlinks on both sides
|
||||||
|
}
|
||||||
|
|
||||||
|
// Diff returns human-readable differences between want and got, sorted.
|
||||||
|
func Diff(want, got Tree, o Opts) []string {
|
||||||
|
var out []string
|
||||||
|
keys := map[string]bool{}
|
||||||
|
for k := range want {
|
||||||
|
keys[k] = true
|
||||||
|
}
|
||||||
|
for k := range got {
|
||||||
|
keys[k] = true
|
||||||
|
}
|
||||||
|
sorted := make([]string, 0, len(keys))
|
||||||
|
for k := range keys {
|
||||||
|
sorted = append(sorted, k)
|
||||||
|
}
|
||||||
|
sort.Strings(sorted)
|
||||||
|
for _, k := range sorted {
|
||||||
|
w, wok := want[k]
|
||||||
|
g, gok := got[k]
|
||||||
|
if !o.Links && ((wok && w.Kind == KindSymlink) || (gok && g.Kind == KindSymlink)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case !gok:
|
||||||
|
out = append(out, fmt.Sprintf("missing %s %s", w.Kind, k))
|
||||||
|
continue
|
||||||
|
case !wok:
|
||||||
|
out = append(out, fmt.Sprintf("unexpected %s %s", g.Kind, k))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if w.Kind != g.Kind {
|
||||||
|
out = append(out, fmt.Sprintf("%s: kind want %s, got %s", k, w.Kind, g.Kind))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if w.Kind == KindFile && !bytes.Equal(w.Data, g.Data) {
|
||||||
|
out = append(out, fmt.Sprintf("%s: content want %s, got %s", k, short(w.Data), short(g.Data)))
|
||||||
|
}
|
||||||
|
if w.Kind == KindSymlink && w.Target != g.Target {
|
||||||
|
out = append(out, fmt.Sprintf("%s: link target want %q, got %q", k, w.Target, g.Target))
|
||||||
|
}
|
||||||
|
if o.Mode && w.Kind != KindSymlink && w.Mode != 0 && w.Mode != g.Mode {
|
||||||
|
out = append(out, fmt.Sprintf("%s: mode want %04o, got %04o", k, w.Mode, g.Mode))
|
||||||
|
}
|
||||||
|
if o.MTime && w.Kind != KindSymlink && !w.MTime.IsZero() &&
|
||||||
|
!w.MTime.Truncate(time.Second).Equal(g.MTime.Truncate(time.Second)) {
|
||||||
|
out = append(out, fmt.Sprintf("%s: mtime want %s, got %s", k, w.MTime.Format(time.RFC3339), g.MTime.Format(time.RFC3339)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Equal fails t with a readable diff if the trees differ.
|
||||||
|
func Equal(t testing.TB, want, got Tree, o Opts) {
|
||||||
|
t.Helper()
|
||||||
|
if d := Diff(want, got, o); len(d) > 0 {
|
||||||
|
t.Errorf("fstree: trees differ (%d):\n %s", len(d), strings.Join(d, "\n "))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func short(b []byte) string {
|
||||||
|
if len(b) <= 32 {
|
||||||
|
return fmt.Sprintf("%q", b)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("%d bytes %q...", len(b), b[:16])
|
||||||
|
}
|
||||||
66
internal/testutil/fstree/fstree_test.go
Normal file
66
internal/testutil/fstree/fstree_test.go
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
package fstree
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFstreeRoundTrip(t *testing.T) {
|
||||||
|
old := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||||
|
spec := Spec{
|
||||||
|
File("a.txt", "hello").WithMTime(old),
|
||||||
|
File("bin/run.sh", "#!/bin/sh\n").WithMode(0o755),
|
||||||
|
Dir("ro").WithMode(0o555).WithMTime(old),
|
||||||
|
File("ro/inside.bin", "").WithSize(100000),
|
||||||
|
Symlink("link", "a.txt"),
|
||||||
|
Symlink("broken", "/nonexistent/zzz"),
|
||||||
|
FIFO("pipe"),
|
||||||
|
Dir("empty"),
|
||||||
|
}
|
||||||
|
root := t.TempDir()
|
||||||
|
Build(t, root, spec)
|
||||||
|
|
||||||
|
st, err := os.Stat(filepath.Join(root, "ro"))
|
||||||
|
if err != nil || st.Mode().Perm() != 0o555 {
|
||||||
|
t.Fatalf("ro dir: %v %v", st, err)
|
||||||
|
}
|
||||||
|
got := Snapshot(t, root)
|
||||||
|
if got["ro/inside.bin"].Kind != KindFile || len(got["ro/inside.bin"].Data) != 100000 {
|
||||||
|
t.Fatalf("sized file not built: %+v", got["ro/inside.bin"].Kind)
|
||||||
|
}
|
||||||
|
Equal(t, FromSpec(spec), got, Opts{Mode: true, MTime: true, Links: true})
|
||||||
|
|
||||||
|
// A second build of the same spec is equal, including mode and mtime.
|
||||||
|
root2 := t.TempDir()
|
||||||
|
Build(t, root2, spec)
|
||||||
|
Equal(t, got, Snapshot(t, root2), Opts{Mode: true, Links: true})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFstreeDiffReportsDifferences(t *testing.T) {
|
||||||
|
want := FromSpec(Spec{
|
||||||
|
File("a", "x"),
|
||||||
|
File("b", "y").WithMode(0o600),
|
||||||
|
Symlink("l", "a"),
|
||||||
|
Dir("d"),
|
||||||
|
})
|
||||||
|
got := FromSpec(Spec{
|
||||||
|
File("a", "z"),
|
||||||
|
File("b", "y").WithMode(0o644),
|
||||||
|
Symlink("l", "b"),
|
||||||
|
File("d", ""),
|
||||||
|
File("extra", ""),
|
||||||
|
})
|
||||||
|
d := Diff(want, got, Opts{Mode: true, Links: true})
|
||||||
|
joined := strings.Join(d, "\n")
|
||||||
|
for _, s := range []string{"a: content", "b: mode want 0600, got 0644", "l: link target", "d: kind want dir, got file", "unexpected file extra"} {
|
||||||
|
if !strings.Contains(joined, s) {
|
||||||
|
t.Errorf("diff lacks %q:\n%s", s, joined)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d := Diff(want, got, Opts{}); strings.Contains(strings.Join(d, "\n"), "link target") {
|
||||||
|
t.Errorf("Links=false must ignore symlinks: %v", d)
|
||||||
|
}
|
||||||
|
}
|
||||||
68
internal/testutil/sshtest/home.go
Normal file
68
internal/testutil/sshtest/home.go
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsolatedHome points HOME at a fresh temp dir (with ~/.ssh, mode 0700),
|
||||||
|
// clears SSH_AUTH_SOCK so no real agent is used, and returns the new HOME.
|
||||||
|
// Uses t.Setenv, so the test must not be parallel.
|
||||||
|
func IsolatedHome(t testing.TB) string {
|
||||||
|
t.Helper()
|
||||||
|
home := t.TempDir()
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
t.Setenv("SSH_AUTH_SOCK", "")
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
|
||||||
|
t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share"))
|
||||||
|
if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return home
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenKeys returns a fresh ed25519 signer and a fresh ECDSA P-256 signer.
|
||||||
|
func GenKeys(t testing.TB) (ed, ec ssh.Signer) {
|
||||||
|
t.Helper()
|
||||||
|
_, edPriv, err := ed25519.GenerateKey(rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ed, err = ssh.NewSignerFromKey(edPriv); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ecPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if ec, err = ssh.NewSignerFromKey(ecPriv); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return ed, ec
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteRandom creates p (and parents) with size random bytes and mode.
|
||||||
|
func WriteRandom(t testing.TB, p string, size int, mode os.FileMode) []byte {
|
||||||
|
t.Helper()
|
||||||
|
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b := make([]byte, size)
|
||||||
|
if _, err := rand.Read(b); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(p, b, mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Chmod(p, mode); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
222
internal/testutil/sshtest/proxy.go
Normal file
222
internal/testutil/sshtest/proxy.go
Normal file
|
|
@ -0,0 +1,222 @@
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Proxy is a TCP proxy in front of a target address that can inject latency,
|
||||||
|
// freeze traffic, or cut connections after a number of bytes.
|
||||||
|
type Proxy struct {
|
||||||
|
// Addr is host:port to dial instead of the target.
|
||||||
|
Addr string
|
||||||
|
|
||||||
|
target string
|
||||||
|
ln net.Listener
|
||||||
|
|
||||||
|
delay atomic.Int64 // one-way delay in nanoseconds, applied both ways
|
||||||
|
frozen atomic.Bool
|
||||||
|
sent atomic.Int64 // client->server bytes, all connections
|
||||||
|
cutAt atomic.Int64 // 0 = disabled; kill all when sent exceeds it
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
links map[*link]struct{}
|
||||||
|
closed bool
|
||||||
|
wg sync.WaitGroup
|
||||||
|
}
|
||||||
|
|
||||||
|
type link struct {
|
||||||
|
client, upstream net.Conn
|
||||||
|
done chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *link) kill() {
|
||||||
|
l.once.Do(func() {
|
||||||
|
close(l.done)
|
||||||
|
l.client.Close()
|
||||||
|
l.upstream.Close()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewProxy starts a proxy to target and registers its shutdown with
|
||||||
|
// t.Cleanup.
|
||||||
|
func NewProxy(t testing.TB, target string) *Proxy {
|
||||||
|
t.Helper()
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sshtest: proxy listen: %v", err)
|
||||||
|
}
|
||||||
|
p := &Proxy{Addr: ln.Addr().String(), target: target, ln: ln, links: map[*link]struct{}{}}
|
||||||
|
p.wg.Add(1)
|
||||||
|
go p.acceptLoop()
|
||||||
|
t.Cleanup(p.Close)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// Port returns the TCP port of Addr.
|
||||||
|
func (p *Proxy) Port() string {
|
||||||
|
_, port, _ := net.SplitHostPort(p.Addr)
|
||||||
|
return port
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDelay sets the one-way latency applied to every chunk in both
|
||||||
|
// directions (RTT grows by about 2*d).
|
||||||
|
func (p *Proxy) SetDelay(d time.Duration) { p.delay.Store(int64(d)) }
|
||||||
|
|
||||||
|
// Freeze stops (on=true) or resumes forwarding in both directions. Data is
|
||||||
|
// buffered while frozen, connections stay open.
|
||||||
|
func (p *Proxy) Freeze(on bool) { p.frozen.Store(on) }
|
||||||
|
|
||||||
|
// CutAfter kills all current connections once n more bytes have been sent
|
||||||
|
// client->server (counted across connections). The trigger fires once;
|
||||||
|
// n <= 0 disarms it.
|
||||||
|
func (p *Proxy) CutAfter(n int64) {
|
||||||
|
if n <= 0 {
|
||||||
|
p.cutAt.Store(0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.cutAt.Store(p.sent.Load() + n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sent reports the total client->server bytes forwarded so far.
|
||||||
|
func (p *Proxy) Sent() int64 { return p.sent.Load() }
|
||||||
|
|
||||||
|
// KillAll closes every current connection; the proxy keeps accepting new
|
||||||
|
// ones.
|
||||||
|
func (p *Proxy) KillAll() {
|
||||||
|
p.mu.Lock()
|
||||||
|
ls := make([]*link, 0, len(p.links))
|
||||||
|
for l := range p.links {
|
||||||
|
ls = append(ls, l)
|
||||||
|
}
|
||||||
|
p.mu.Unlock()
|
||||||
|
for _, l := range ls {
|
||||||
|
l.kill()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close stops the proxy and waits for all its goroutines. Idempotent.
|
||||||
|
func (p *Proxy) Close() {
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.closed = true
|
||||||
|
p.mu.Unlock()
|
||||||
|
p.ln.Close()
|
||||||
|
p.KillAll()
|
||||||
|
p.wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Proxy) acceptLoop() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
for {
|
||||||
|
c, err := p.ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
u, err := net.DialTimeout("tcp", p.target, 5*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
c.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
l := &link{client: c, upstream: u, done: make(chan struct{})}
|
||||||
|
p.mu.Lock()
|
||||||
|
if p.closed {
|
||||||
|
p.mu.Unlock()
|
||||||
|
l.kill()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
p.links[l] = struct{}{}
|
||||||
|
p.mu.Unlock()
|
||||||
|
var lw sync.WaitGroup
|
||||||
|
lw.Add(2)
|
||||||
|
p.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer p.wg.Done()
|
||||||
|
lw.Wait()
|
||||||
|
l.kill()
|
||||||
|
p.mu.Lock()
|
||||||
|
delete(p.links, l)
|
||||||
|
p.mu.Unlock()
|
||||||
|
}()
|
||||||
|
go func() { defer lw.Done(); p.pipe(l, c, u, true) }()
|
||||||
|
go func() { defer lw.Done(); p.pipe(l, u, c, false) }()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type chunk struct {
|
||||||
|
b []byte
|
||||||
|
at time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// pipe forwards src -> dst through a delay queue. Returning from either
|
||||||
|
// direction kills the whole link.
|
||||||
|
func (p *Proxy) pipe(l *link, src, dst net.Conn, upstream bool) {
|
||||||
|
defer l.kill()
|
||||||
|
q := make(chan chunk, 1024)
|
||||||
|
writerDone := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(writerDone)
|
||||||
|
defer l.kill()
|
||||||
|
for {
|
||||||
|
var c chunk
|
||||||
|
var ok bool
|
||||||
|
select {
|
||||||
|
case c, ok = <-q:
|
||||||
|
if !ok {
|
||||||
|
return // reader finished and queue drained
|
||||||
|
}
|
||||||
|
case <-l.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if d := time.Until(c.at); d > 0 {
|
||||||
|
t := time.NewTimer(d)
|
||||||
|
select {
|
||||||
|
case <-t.C:
|
||||||
|
case <-l.done:
|
||||||
|
t.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for p.frozen.Load() {
|
||||||
|
select {
|
||||||
|
case <-time.After(5 * time.Millisecond):
|
||||||
|
case <-l.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := dst.Write(c.b); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
defer func() { close(q); <-writerDone }()
|
||||||
|
buf := make([]byte, 32*1024)
|
||||||
|
for {
|
||||||
|
n, err := src.Read(buf)
|
||||||
|
if n > 0 {
|
||||||
|
if upstream {
|
||||||
|
total := p.sent.Add(int64(n))
|
||||||
|
if lim := p.cutAt.Load(); lim > 0 && total > lim && p.cutAt.CompareAndSwap(lim, 0) {
|
||||||
|
p.KillAll()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c := chunk{b: append([]byte(nil), buf[:n]...), at: time.Now().Add(time.Duration(p.delay.Load()))}
|
||||||
|
select {
|
||||||
|
case q <- c:
|
||||||
|
case <-l.done:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
357
internal/testutil/sshtest/server.go
Normal file
357
internal/testutil/sshtest/server.go
Normal file
|
|
@ -0,0 +1,357 @@
|
||||||
|
// Package sshtest provides an in-process SSH/SFTP server and a fault-injecting
|
||||||
|
// TCP proxy for tests. It is a regular (non _test) package so that tests in
|
||||||
|
// different packages can share it.
|
||||||
|
//
|
||||||
|
// The server serves the real OS filesystem over the "sftp" subsystem and runs
|
||||||
|
// "exec" requests through `sh -c`, reporting exit-status and stderr. Every
|
||||||
|
// goroutine it starts is stopped by t.Cleanup.
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os/exec"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultPassword is accepted when Options.Password is empty and no
|
||||||
|
// AuthorizedKeys are configured.
|
||||||
|
const DefaultPassword = "pw"
|
||||||
|
|
||||||
|
// Options configures Start.
|
||||||
|
type Options struct {
|
||||||
|
// Password accepted for any user. Empty means DefaultPassword (unless
|
||||||
|
// AuthorizedKeys is set, in which case password auth is disabled).
|
||||||
|
Password string
|
||||||
|
// AuthorizedKeys enables public-key auth for these keys.
|
||||||
|
AuthorizedKeys []ssh.PublicKey
|
||||||
|
// HostKeys the server offers. Empty means a fresh ed25519 + ECDSA pair.
|
||||||
|
HostKeys []ssh.Signer
|
||||||
|
// NoExec rejects "exec" requests, like `ForceCommand internal-sftp`.
|
||||||
|
NoExec bool
|
||||||
|
// Chroot sets the SFTP working directory and the cwd of exec commands.
|
||||||
|
// Relative paths resolve against it. It is NOT a security boundary:
|
||||||
|
// absolute paths still reach the whole filesystem.
|
||||||
|
Chroot string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Server is a running in-process SSH server.
|
||||||
|
type Server struct {
|
||||||
|
// Addr is host:port to dial.
|
||||||
|
Addr string
|
||||||
|
// HostKeys the server offers.
|
||||||
|
HostKeys []ssh.Signer
|
||||||
|
// Root is the directory relative paths resolve against ("/" by default).
|
||||||
|
Root string
|
||||||
|
// Password accepted by the server ("" when password auth is disabled).
|
||||||
|
Password string
|
||||||
|
|
||||||
|
opts Options
|
||||||
|
cfg *ssh.ServerConfig
|
||||||
|
ln net.Listener
|
||||||
|
ctx context.Context
|
||||||
|
cancel context.CancelFunc
|
||||||
|
wg sync.WaitGroup
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
conns map[net.Conn]struct{}
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start launches a server on 127.0.0.1 and registers its shutdown with
|
||||||
|
// t.Cleanup.
|
||||||
|
func Start(t testing.TB, o Options) *Server {
|
||||||
|
t.Helper()
|
||||||
|
if len(o.HostKeys) == 0 {
|
||||||
|
ed, ec := GenKeys(t)
|
||||||
|
o.HostKeys = []ssh.Signer{ed, ec}
|
||||||
|
}
|
||||||
|
pass := o.Password
|
||||||
|
if pass == "" && len(o.AuthorizedKeys) == 0 {
|
||||||
|
pass = DefaultPassword
|
||||||
|
}
|
||||||
|
cfg := &ssh.ServerConfig{}
|
||||||
|
if pass != "" {
|
||||||
|
cfg.PasswordCallback = func(_ ssh.ConnMetadata, p []byte) (*ssh.Permissions, error) {
|
||||||
|
if string(p) == pass {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return nil, errors.New("password rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(o.AuthorizedKeys) > 0 {
|
||||||
|
keys := o.AuthorizedKeys
|
||||||
|
cfg.PublicKeyCallback = func(_ ssh.ConnMetadata, k ssh.PublicKey) (*ssh.Permissions, error) {
|
||||||
|
for _, ak := range keys {
|
||||||
|
if ak.Type() == k.Type() && string(ak.Marshal()) == string(k.Marshal()) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, errors.New("key rejected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, k := range o.HostKeys {
|
||||||
|
cfg.AddHostKey(k)
|
||||||
|
}
|
||||||
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sshtest: listen: %v", err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
root := o.Chroot
|
||||||
|
if root == "" {
|
||||||
|
root = "/"
|
||||||
|
}
|
||||||
|
s := &Server{
|
||||||
|
Addr: ln.Addr().String(),
|
||||||
|
HostKeys: o.HostKeys,
|
||||||
|
Root: root,
|
||||||
|
Password: pass,
|
||||||
|
opts: o,
|
||||||
|
cfg: cfg,
|
||||||
|
ln: ln,
|
||||||
|
ctx: ctx,
|
||||||
|
cancel: cancel,
|
||||||
|
conns: map[net.Conn]struct{}{},
|
||||||
|
}
|
||||||
|
s.wg.Add(1)
|
||||||
|
go s.acceptLoop()
|
||||||
|
t.Cleanup(s.Close)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// Port returns the TCP port of Addr.
|
||||||
|
func (s *Server) Port() string {
|
||||||
|
_, p, _ := net.SplitHostPort(s.Addr)
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close stops the server, drops all connections and waits for every
|
||||||
|
// goroutine to exit. It is idempotent and called automatically by Cleanup.
|
||||||
|
func (s *Server) Close() {
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.closed {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.closed = true
|
||||||
|
for c := range s.conns {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
s.cancel()
|
||||||
|
s.ln.Close()
|
||||||
|
s.wg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
// DropConnections closes every live client connection, leaving the server
|
||||||
|
// listening (simulates a server-side disconnect).
|
||||||
|
func (s *Server) DropConnections() {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
for c := range s.conns {
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) track(c net.Conn) bool {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if s.closed {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
s.conns[c] = struct{}{}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) untrack(c net.Conn) {
|
||||||
|
s.mu.Lock()
|
||||||
|
delete(s.conns, c)
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) acceptLoop() {
|
||||||
|
defer s.wg.Done()
|
||||||
|
for {
|
||||||
|
nc, err := s.ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !s.track(nc) {
|
||||||
|
nc.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer s.wg.Done()
|
||||||
|
defer s.untrack(nc)
|
||||||
|
defer nc.Close()
|
||||||
|
s.handle(nc)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) handle(nc net.Conn) {
|
||||||
|
sconn, chans, reqs, err := ssh.NewServerConn(nc, s.cfg)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer sconn.Close()
|
||||||
|
s.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer s.wg.Done()
|
||||||
|
ssh.DiscardRequests(reqs)
|
||||||
|
}()
|
||||||
|
for nch := range chans {
|
||||||
|
if nch.ChannelType() != "session" {
|
||||||
|
nch.Reject(ssh.UnknownChannelType, "only session channels")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ch, creqs, err := nch.Accept()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
s.wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer s.wg.Done()
|
||||||
|
s.session(ch, creqs)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) session(ch ssh.Channel, reqs <-chan *ssh.Request) {
|
||||||
|
defer ch.Close()
|
||||||
|
started := false
|
||||||
|
var work sync.WaitGroup
|
||||||
|
defer work.Wait()
|
||||||
|
for req := range reqs {
|
||||||
|
switch {
|
||||||
|
case req.Type == "subsystem" && !started:
|
||||||
|
name, ok := parseString(req.Payload)
|
||||||
|
if !ok || name != "sftp" {
|
||||||
|
req.Reply(false, nil)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var opts []sftp.ServerOption
|
||||||
|
if s.opts.Chroot != "" {
|
||||||
|
opts = append(opts, sftp.WithServerWorkingDirectory(s.opts.Chroot))
|
||||||
|
}
|
||||||
|
srv, err := sftp.NewServer(ch, opts...)
|
||||||
|
if err != nil {
|
||||||
|
req.Reply(false, nil)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
started = true
|
||||||
|
req.Reply(true, nil)
|
||||||
|
work.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer work.Done()
|
||||||
|
srv.Serve()
|
||||||
|
srv.Close()
|
||||||
|
ch.Close()
|
||||||
|
}()
|
||||||
|
case req.Type == "exec" && !started:
|
||||||
|
if s.opts.NoExec {
|
||||||
|
req.Reply(false, nil)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
cmdStr, ok := parseString(req.Payload)
|
||||||
|
if !ok {
|
||||||
|
req.Reply(false, nil)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
started = true
|
||||||
|
req.Reply(true, nil)
|
||||||
|
work.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer work.Done()
|
||||||
|
s.runExec(ch, cmdStr)
|
||||||
|
}()
|
||||||
|
default:
|
||||||
|
if req.WantReply {
|
||||||
|
req.Reply(false, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Server) runExec(ch ssh.Channel, cmdStr string) {
|
||||||
|
c := exec.CommandContext(s.ctx, "sh", "-c", cmdStr)
|
||||||
|
c.WaitDelay = time.Second
|
||||||
|
if s.opts.Chroot != "" {
|
||||||
|
c.Dir = s.opts.Chroot
|
||||||
|
}
|
||||||
|
c.Stdout = ch
|
||||||
|
c.Stderr = ch.Stderr()
|
||||||
|
code := 0
|
||||||
|
if err := c.Run(); err != nil {
|
||||||
|
code = 127
|
||||||
|
var ee *exec.ExitError
|
||||||
|
if errors.As(err, &ee) && ee.ExitCode() >= 0 {
|
||||||
|
code = ee.ExitCode()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
st := make([]byte, 4)
|
||||||
|
binary.BigEndian.PutUint32(st, uint32(code))
|
||||||
|
ch.SendRequest("exit-status", false, st)
|
||||||
|
ch.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseString decodes an SSH wire-format string (uint32 length + bytes).
|
||||||
|
func parseString(b []byte) (string, bool) {
|
||||||
|
if len(b) < 4 {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
n := binary.BigEndian.Uint32(b)
|
||||||
|
if uint64(len(b)-4) < uint64(n) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return string(b[4 : 4+n]), true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientConfig returns an ssh.ClientConfig that authenticates to s with its
|
||||||
|
// password and pins its first host key.
|
||||||
|
func (s *Server) ClientConfig(user string) *ssh.ClientConfig {
|
||||||
|
if user == "" {
|
||||||
|
user = "u"
|
||||||
|
}
|
||||||
|
cfg := &ssh.ClientConfig{
|
||||||
|
User: user,
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error {
|
||||||
|
for _, hk := range s.HostKeys {
|
||||||
|
if string(hk.PublicKey().Marshal()) == string(key.Marshal()) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("sshtest: unexpected host key %s", key.Type())
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if s.Password != "" {
|
||||||
|
cfg.Auth = []ssh.AuthMethod{ssh.Password(s.Password)}
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dial connects to addr (s.Addr or a proxy in front of it) with
|
||||||
|
// ClientConfig and closes the client on Cleanup.
|
||||||
|
func (s *Server) Dial(t testing.TB, addr string) *ssh.Client {
|
||||||
|
t.Helper()
|
||||||
|
if addr == "" {
|
||||||
|
addr = s.Addr
|
||||||
|
}
|
||||||
|
c, err := ssh.Dial("tcp", addr, s.ClientConfig(""))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("sshtest: dial %s: %v", addr, err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { c.Close() })
|
||||||
|
return c
|
||||||
|
}
|
||||||
264
internal/testutil/sshtest/sshtest_test.go
Normal file
264
internal/testutil/sshtest/sshtest_test.go
Normal file
|
|
@ -0,0 +1,264 @@
|
||||||
|
package sshtest
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the
|
||||||
|
// goroutine count returns to the baseline within ±2.
|
||||||
|
func noLeak(t *testing.T, fn func(t *testing.T)) {
|
||||||
|
t.Helper()
|
||||||
|
runtime.GC()
|
||||||
|
base := runtime.NumGoroutine()
|
||||||
|
t.Run("body", fn)
|
||||||
|
deadline := time.Now().Add(3 * time.Second)
|
||||||
|
var n int
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
n = runtime.NumGoroutine()
|
||||||
|
if n <= base+2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
buf := make([]byte, 1<<20)
|
||||||
|
buf = buf[:runtime.Stack(buf, true)]
|
||||||
|
t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sftpClient(t *testing.T, c *ssh.Client) *sftp.Client {
|
||||||
|
t.Helper()
|
||||||
|
sc, err := sftp.NewClient(c)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { sc.Close() })
|
||||||
|
return sc
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerSFTPRoundTrip(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
sc := sftpClient(t, srv.Dial(t, ""))
|
||||||
|
dir := t.TempDir()
|
||||||
|
p := filepath.Join(dir, "sub", "f.bin")
|
||||||
|
if err := sc.MkdirAll(filepath.Dir(p)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := bytes.Repeat([]byte("vcom"), 50000)
|
||||||
|
f, err := sc.Create(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := f.Write(want); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := f.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := os.ReadFile(p)
|
||||||
|
if err != nil || !bytes.Equal(got, want) {
|
||||||
|
t.Fatalf("disk content mismatch: err=%v len=%d", err, len(got))
|
||||||
|
}
|
||||||
|
r, err := sc.Open(p)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
back, err := io.ReadAll(r)
|
||||||
|
r.Close()
|
||||||
|
if err != nil || !bytes.Equal(back, want) {
|
||||||
|
t.Fatalf("read back mismatch: err=%v len=%d", err, len(back))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerChrootWorkingDir(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
WriteRandom(t, filepath.Join(root, "x.bin"), 10, 0o644)
|
||||||
|
srv := Start(t, Options{Chroot: root})
|
||||||
|
sc := sftpClient(t, srv.Dial(t, ""))
|
||||||
|
if _, err := sc.Stat("x.bin"); err != nil {
|
||||||
|
t.Fatalf("relative path should resolve inside Chroot: %v", err)
|
||||||
|
}
|
||||||
|
if srv.Root != root {
|
||||||
|
t.Fatalf("Root=%q want %q", srv.Root, root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerExecStatusAndStderr(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
c := srv.Dial(t, "")
|
||||||
|
s, err := c.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out, errb bytes.Buffer
|
||||||
|
s.Stdout, s.Stderr = &out, &errb
|
||||||
|
err = s.Run("echo hi; echo oops >&2; exit 3")
|
||||||
|
s.Close()
|
||||||
|
var ee *ssh.ExitError
|
||||||
|
if !errors.As(err, &ee) || ee.ExitStatus() != 3 {
|
||||||
|
t.Fatalf("want exit status 3, got %v", err)
|
||||||
|
}
|
||||||
|
if out.String() != "hi\n" || errb.String() != "oops\n" {
|
||||||
|
t.Fatalf("stdout=%q stderr=%q", out.String(), errb.String())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerNoExec(t *testing.T) {
|
||||||
|
srv := Start(t, Options{NoExec: true})
|
||||||
|
c := srv.Dial(t, "")
|
||||||
|
s, err := c.NewSession()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
defer s.Close()
|
||||||
|
if err := s.Run("true"); err == nil {
|
||||||
|
t.Fatal("exec must be rejected with NoExec")
|
||||||
|
}
|
||||||
|
sftpClient(t, c) // sftp still works
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServerPublicKeyAuth(t *testing.T) {
|
||||||
|
ed, _ := GenKeys(t)
|
||||||
|
srv := Start(t, Options{AuthorizedKeys: []ssh.PublicKey{ed.PublicKey()}})
|
||||||
|
cfg := srv.ClientConfig("")
|
||||||
|
if _, err := ssh.Dial("tcp", srv.Addr, cfg); err == nil {
|
||||||
|
t.Fatal("password auth must be disabled when only keys are configured")
|
||||||
|
}
|
||||||
|
cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(ed)}
|
||||||
|
c, err := ssh.Dial("tcp", srv.Addr, cfg)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func rtt(t *testing.T, sc *sftp.Client, p string) time.Duration {
|
||||||
|
t0 := time.Now()
|
||||||
|
if _, err := sc.Stat(p); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return time.Since(t0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyDelay(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
sc := sftpClient(t, srv.Dial(t, px.Addr))
|
||||||
|
dir := t.TempDir()
|
||||||
|
base := rtt(t, sc, dir)
|
||||||
|
const d = 40 * time.Millisecond
|
||||||
|
px.SetDelay(d)
|
||||||
|
got := rtt(t, sc, dir)
|
||||||
|
t.Logf("rtt without delay=%v with %v one-way delay=%v", base, d, got)
|
||||||
|
if got < d {
|
||||||
|
t.Fatalf("rtt %v < delay %v", got, d)
|
||||||
|
}
|
||||||
|
px.SetDelay(0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyFreeze(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
sc := sftpClient(t, srv.Dial(t, px.Addr))
|
||||||
|
dir := t.TempDir()
|
||||||
|
px.Freeze(true)
|
||||||
|
res := make(chan error, 1)
|
||||||
|
go func() { _, err := sc.ReadDir(dir); res <- err }()
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
t.Fatalf("request completed while frozen: %v", err)
|
||||||
|
case <-time.After(300 * time.Millisecond):
|
||||||
|
}
|
||||||
|
px.Freeze(false)
|
||||||
|
select {
|
||||||
|
case err := <-res:
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("request failed after unfreeze: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("request did not complete after unfreeze")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyCut(t *testing.T) {
|
||||||
|
noLeak(t, func(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
c := srv.Dial(t, px.Addr)
|
||||||
|
sc := sftpClient(t, c)
|
||||||
|
dir := t.TempDir()
|
||||||
|
before := px.Sent()
|
||||||
|
px.CutAfter(256 << 10)
|
||||||
|
f, err := sc.Create(filepath.Join(dir, "big.bin"))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, werr := f.Write(make([]byte, 4<<20))
|
||||||
|
f.Close()
|
||||||
|
if werr == nil {
|
||||||
|
t.Fatal("write of 4 MiB should fail after cut at 256 KiB")
|
||||||
|
}
|
||||||
|
sent := px.Sent() - before
|
||||||
|
if sent > 1<<20 {
|
||||||
|
t.Fatalf("proxy forwarded %d bytes after a 256 KiB cut", sent)
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() { c.Wait(); close(done) }()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("ssh connection still alive after cut")
|
||||||
|
}
|
||||||
|
// The proxy keeps accepting connections after a cut.
|
||||||
|
sc2 := sftpClient(t, srv.Dial(t, px.Addr))
|
||||||
|
if _, err := sc2.Stat(dir); err != nil {
|
||||||
|
t.Fatalf("new connection after cut: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProxyKillAll(t *testing.T) {
|
||||||
|
srv := Start(t, Options{})
|
||||||
|
px := NewProxy(t, srv.Addr)
|
||||||
|
c := srv.Dial(t, px.Addr)
|
||||||
|
px.KillAll()
|
||||||
|
done := make(chan error, 1)
|
||||||
|
go func() { done <- c.Wait() }()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(5 * time.Second):
|
||||||
|
t.Fatal("connection survived KillAll")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsolatedHome(t *testing.T) {
|
||||||
|
h := IsolatedHome(t)
|
||||||
|
if os.Getenv("HOME") != h || os.Getenv("SSH_AUTH_SOCK") != "" {
|
||||||
|
t.Fatal("env not isolated")
|
||||||
|
}
|
||||||
|
st, err := os.Stat(filepath.Join(h, ".ssh"))
|
||||||
|
if err != nil || st.Mode().Perm() != 0o700 {
|
||||||
|
t.Fatalf(".ssh: %v %v", st, err)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(h, os.TempDir()) {
|
||||||
|
t.Logf("home outside TMPDIR: %s", h)
|
||||||
|
}
|
||||||
|
}
|
||||||
350
internal/testutil/teadriver/driver.go
Normal file
350
internal/testutil/teadriver/driver.go
Normal file
|
|
@ -0,0 +1,350 @@
|
||||||
|
// Package teadriver drives a Bubble Tea model in tests without a terminal:
|
||||||
|
// it feeds key/mouse messages to Update, executes returned commands in
|
||||||
|
// goroutines (unwrapping Batch and Sequence) and feeds their results back
|
||||||
|
// until the model is quiet, and renders View without ANSI escapes.
|
||||||
|
//
|
||||||
|
// The lipgloss color profile is process-global, so tests using a Driver must
|
||||||
|
// not run in parallel with each other.
|
||||||
|
package teadriver
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
|
"github.com/charmbracelet/x/ansi"
|
||||||
|
"github.com/muesli/termenv"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultLongCmd is how long Settle waits for a single command before
|
||||||
|
// treating it as a timer or long wait (e.g. tea.Tick with a long delay) and
|
||||||
|
// returning without it. Its result is still delivered on a later Settle.
|
||||||
|
const DefaultLongCmd = time.Second
|
||||||
|
|
||||||
|
// Option configures New.
|
||||||
|
type Option func(*Driver)
|
||||||
|
|
||||||
|
// WithProfile renders with the given color profile instead of Ascii.
|
||||||
|
func WithProfile(p termenv.Profile) Option { return func(d *Driver) { d.profile = p } }
|
||||||
|
|
||||||
|
// WithLongCmd overrides DefaultLongCmd.
|
||||||
|
func WithLongCmd(dur time.Duration) Option { return func(d *Driver) { d.LongCmd = dur } }
|
||||||
|
|
||||||
|
// WithoutInit skips running the model's Init command.
|
||||||
|
func WithoutInit() Option { return func(d *Driver) { d.skipInit = true } }
|
||||||
|
|
||||||
|
// Driver runs a model. It is not safe for concurrent use.
|
||||||
|
type Driver struct {
|
||||||
|
// LongCmd: see DefaultLongCmd.
|
||||||
|
LongCmd time.Duration
|
||||||
|
|
||||||
|
t testing.TB
|
||||||
|
m tea.Model
|
||||||
|
w, h int
|
||||||
|
profile termenv.Profile
|
||||||
|
skipInit bool
|
||||||
|
|
||||||
|
pending []tea.Cmd
|
||||||
|
nextID int
|
||||||
|
inflight map[int]time.Time
|
||||||
|
results chan result
|
||||||
|
|
||||||
|
quit bool
|
||||||
|
execs []tea.Msg
|
||||||
|
msgs int
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
id int
|
||||||
|
msg tea.Msg
|
||||||
|
final bool // the command (or whole sequence) is done
|
||||||
|
panic any
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a driver, sets the color profile (Ascii by default), sends a
|
||||||
|
// WindowSizeMsg of w×h and queues the model's Init command (run by the
|
||||||
|
// next Settle).
|
||||||
|
func New(t testing.TB, m tea.Model, w, h int, opts ...Option) *Driver {
|
||||||
|
t.Helper()
|
||||||
|
d := &Driver{
|
||||||
|
LongCmd: DefaultLongCmd,
|
||||||
|
t: t,
|
||||||
|
m: m,
|
||||||
|
w: w,
|
||||||
|
h: h,
|
||||||
|
profile: termenv.Ascii,
|
||||||
|
inflight: map[int]time.Time{},
|
||||||
|
results: make(chan result, 1024),
|
||||||
|
}
|
||||||
|
for _, o := range opts {
|
||||||
|
o(d)
|
||||||
|
}
|
||||||
|
prev := lipgloss.ColorProfile()
|
||||||
|
lipgloss.SetColorProfile(d.profile)
|
||||||
|
t.Cleanup(func() { lipgloss.SetColorProfile(prev) })
|
||||||
|
if !d.skipInit {
|
||||||
|
d.enqueue(m.Init())
|
||||||
|
}
|
||||||
|
d.Send(tea.WindowSizeMsg{Width: w, Height: h})
|
||||||
|
return d
|
||||||
|
}
|
||||||
|
|
||||||
|
// Model returns the current model.
|
||||||
|
func (d *Driver) Model() tea.Model { return d.m }
|
||||||
|
|
||||||
|
// Quit reports whether a command returned tea.QuitMsg.
|
||||||
|
func (d *Driver) Quit() bool { return d.quit }
|
||||||
|
|
||||||
|
// Execs returns the tea.ExecProcess requests the model made. They are
|
||||||
|
// recorded, never run.
|
||||||
|
func (d *Driver) Execs() []tea.Msg { return d.execs }
|
||||||
|
|
||||||
|
// Send passes msg to Update synchronously and queues the returned command.
|
||||||
|
func (d *Driver) Send(msg tea.Msg) {
|
||||||
|
d.t.Helper()
|
||||||
|
m, cmd := d.m.Update(msg)
|
||||||
|
if m == nil {
|
||||||
|
d.t.Fatalf("teadriver: Update(%T) returned nil model", msg)
|
||||||
|
}
|
||||||
|
d.m = m
|
||||||
|
d.msgs++
|
||||||
|
d.enqueue(cmd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Press sends one key message per argument, using tea key names: "enter",
|
||||||
|
// "esc", "tab", "f5", "pgdown", "ctrl+r", "alt+left", "shift+up", " " or
|
||||||
|
// "space", or literal text ("j", "п") sent as runes.
|
||||||
|
func (d *Driver) Press(keys ...string) {
|
||||||
|
d.t.Helper()
|
||||||
|
for _, k := range keys {
|
||||||
|
d.Send(Key(d.t, k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Type sends one rune key message per rune of text.
|
||||||
|
func (d *Driver) Type(text string) {
|
||||||
|
d.t.Helper()
|
||||||
|
for _, r := range text {
|
||||||
|
if r == ' ' {
|
||||||
|
d.Send(tea.KeyMsg{Type: tea.KeySpace, Runes: []rune{' '}})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
d.Send(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mouse sends a press of button at cell (x, y) followed by a release.
|
||||||
|
func (d *Driver) Mouse(x, y int, button tea.MouseButton) {
|
||||||
|
d.t.Helper()
|
||||||
|
d.Send(tea.MouseMsg{X: x, Y: y, Button: button, Action: tea.MouseActionPress})
|
||||||
|
if button != tea.MouseButtonWheelUp && button != tea.MouseButtonWheelDown {
|
||||||
|
d.Send(tea.MouseMsg{X: x, Y: y, Button: button, Action: tea.MouseActionRelease})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Screen renders View with ANSI escapes stripped.
|
||||||
|
func (d *Driver) Screen() string { return ansi.Strip(d.m.View()) }
|
||||||
|
|
||||||
|
// ScreenContains reports whether the rendered screen contains s.
|
||||||
|
func (d *Driver) ScreenContains(s string) bool { return strings.Contains(d.Screen(), s) }
|
||||||
|
|
||||||
|
// Settle runs queued commands concurrently and feeds their messages back to
|
||||||
|
// Update until nothing is left, except commands that have been running
|
||||||
|
// longer than LongCmd (timers); their results arrive on a later Settle. It
|
||||||
|
// also returns at timeout, logging what is still running.
|
||||||
|
func (d *Driver) Settle(timeout time.Duration) {
|
||||||
|
d.t.Helper()
|
||||||
|
deadline := time.Now().Add(timeout)
|
||||||
|
for {
|
||||||
|
d.launchPending()
|
||||||
|
// Deliver whatever is already done without blocking.
|
||||||
|
if d.drainReady() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(d.inflight) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
var wake time.Time
|
||||||
|
for _, started := range d.inflight {
|
||||||
|
if old := started.Add(d.LongCmd); old.After(now) && (wake.IsZero() || old.Before(wake)) {
|
||||||
|
wake = old
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wake.IsZero() {
|
||||||
|
return // only long-running commands remain
|
||||||
|
}
|
||||||
|
if now.After(deadline) {
|
||||||
|
d.t.Logf("teadriver: Settle timed out after %v with %d command(s) running", timeout, len(d.inflight))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if deadline.Before(wake) {
|
||||||
|
wake = deadline
|
||||||
|
}
|
||||||
|
timer := time.NewTimer(time.Until(wake))
|
||||||
|
select {
|
||||||
|
case r := <-d.results:
|
||||||
|
timer.Stop()
|
||||||
|
d.handle(r)
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Driver) drainReady() bool {
|
||||||
|
got := false
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case r := <-d.results:
|
||||||
|
d.handle(r)
|
||||||
|
got = true
|
||||||
|
default:
|
||||||
|
return got
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Driver) enqueue(cmd tea.Cmd) {
|
||||||
|
if cmd != nil {
|
||||||
|
d.pending = append(d.pending, cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Driver) launchPending() {
|
||||||
|
cmds := d.pending
|
||||||
|
d.pending = nil
|
||||||
|
for _, c := range cmds {
|
||||||
|
d.launch([]tea.Cmd{c})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// launch runs cmds one after another in a goroutine (one cmd for a plain
|
||||||
|
// command, several for a Sequence).
|
||||||
|
func (d *Driver) launch(cmds []tea.Cmd) {
|
||||||
|
id := d.nextID
|
||||||
|
d.nextID++
|
||||||
|
d.inflight[id] = time.Now()
|
||||||
|
results := d.results
|
||||||
|
go func() {
|
||||||
|
var once sync.Once
|
||||||
|
defer func() {
|
||||||
|
if p := recover(); p != nil {
|
||||||
|
once.Do(func() { results <- result{id: id, final: true, panic: p} })
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for _, c := range cmds {
|
||||||
|
if c != nil {
|
||||||
|
results <- result{id: id, msg: c()}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
once.Do(func() { results <- result{id: id, final: true} })
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Driver) handle(r result) {
|
||||||
|
d.t.Helper()
|
||||||
|
if r.final {
|
||||||
|
delete(d.inflight, r.id)
|
||||||
|
}
|
||||||
|
if r.panic != nil {
|
||||||
|
d.t.Fatalf("teadriver: command panicked: %v", r.panic)
|
||||||
|
}
|
||||||
|
d.deliver(r.msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Driver) deliver(msg tea.Msg) {
|
||||||
|
d.t.Helper()
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case nil:
|
||||||
|
return
|
||||||
|
case tea.BatchMsg:
|
||||||
|
for _, c := range msg {
|
||||||
|
d.enqueue(c)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
case tea.QuitMsg:
|
||||||
|
d.quit = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if cmds, ok := asSequence(msg); ok {
|
||||||
|
d.launch(cmds)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if isExec(msg) {
|
||||||
|
d.execs = append(d.execs, msg)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
d.Send(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
const teaPkg = "github.com/charmbracelet/bubbletea"
|
||||||
|
|
||||||
|
func asSequence(msg tea.Msg) ([]tea.Cmd, bool) {
|
||||||
|
v := reflect.ValueOf(msg)
|
||||||
|
t := v.Type()
|
||||||
|
if t.PkgPath() != teaPkg || t.Name() != "sequenceMsg" || t.Kind() != reflect.Slice {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
cmds := make([]tea.Cmd, v.Len())
|
||||||
|
for i := range cmds {
|
||||||
|
cmds[i], _ = v.Index(i).Interface().(tea.Cmd)
|
||||||
|
}
|
||||||
|
return cmds, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func isExec(msg tea.Msg) bool {
|
||||||
|
t := reflect.TypeOf(msg)
|
||||||
|
return t.PkgPath() == teaPkg && t.Name() == "execMsg"
|
||||||
|
}
|
||||||
|
|
||||||
|
var keyTypes = func() map[string]tea.KeyType {
|
||||||
|
m := map[string]tea.KeyType{}
|
||||||
|
for kt := tea.KeyType(-200); kt <= 200; kt++ {
|
||||||
|
if kt == tea.KeyRunes {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
name := tea.Key{Type: kt}.String()
|
||||||
|
if name == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, dup := m[name]; !dup {
|
||||||
|
m[name] = kt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m["space"] = tea.KeySpace
|
||||||
|
return m
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Key converts a key name (see Press) to a tea.KeyMsg.
|
||||||
|
func Key(t testing.TB, s string) tea.KeyMsg {
|
||||||
|
t.Helper()
|
||||||
|
if kt, ok := keyTypes[s]; ok {
|
||||||
|
k := tea.KeyMsg{Type: kt}
|
||||||
|
if kt == tea.KeySpace {
|
||||||
|
k.Runes = []rune{' '}
|
||||||
|
}
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
if rest, ok := strings.CutPrefix(s, "alt+"); ok && rest != "" {
|
||||||
|
k := Key(t, rest)
|
||||||
|
k.Alt = true
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
if s == "" {
|
||||||
|
t.Fatalf("teadriver: empty key")
|
||||||
|
}
|
||||||
|
if strings.Contains(s, "+") && len([]rune(s)) > 1 {
|
||||||
|
t.Fatalf("teadriver: unknown key %q", s)
|
||||||
|
}
|
||||||
|
return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)}
|
||||||
|
}
|
||||||
|
|
||||||
|
// String describes the driver state for failure messages.
|
||||||
|
func (d *Driver) String() string {
|
||||||
|
return fmt.Sprintf("teadriver{msgs=%d inflight=%d pending=%d quit=%v}", d.msgs, len(d.inflight), len(d.pending), d.quit)
|
||||||
|
}
|
||||||
107
internal/testutil/teadriver/driver_test.go
Normal file
107
internal/testutil/teadriver/driver_test.go
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
package teadriver
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
)
|
||||||
|
|
||||||
|
type note string
|
||||||
|
|
||||||
|
type toy struct {
|
||||||
|
got []string
|
||||||
|
keys []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m toy) Init() tea.Cmd { return func() tea.Msg { return note("init") } }
|
||||||
|
|
||||||
|
func emit(s string) tea.Cmd { return func() tea.Msg { return note(s) } }
|
||||||
|
|
||||||
|
func (m toy) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
|
switch msg := msg.(type) {
|
||||||
|
case note:
|
||||||
|
m.got = append(m.got, string(msg))
|
||||||
|
if msg == "a" {
|
||||||
|
return m, emit("a-followup")
|
||||||
|
}
|
||||||
|
case tea.KeyMsg:
|
||||||
|
m.keys = append(m.keys, msg.String())
|
||||||
|
switch msg.String() {
|
||||||
|
case "x":
|
||||||
|
return m, tea.Batch(
|
||||||
|
emit("a"),
|
||||||
|
tea.Batch(emit("b"), nil, emit("c")),
|
||||||
|
tea.Sequence(emit("s1"), emit("s2")),
|
||||||
|
tea.Tick(time.Hour, func(time.Time) tea.Msg { return note("never") }),
|
||||||
|
)
|
||||||
|
case "q":
|
||||||
|
return m, tea.Quit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return m, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m toy) View() string { return "\x1b[1mgot:\x1b[0m " + strings.Join(m.got, ",") }
|
||||||
|
|
||||||
|
func TestDriverSettleBatch(t *testing.T) {
|
||||||
|
d := New(t, toy{}, 80, 24, WithLongCmd(100*time.Millisecond))
|
||||||
|
d.Settle(time.Second)
|
||||||
|
d.Press("x")
|
||||||
|
t0 := time.Now()
|
||||||
|
d.Settle(5 * time.Second)
|
||||||
|
if el := time.Since(t0); el > 2*time.Second {
|
||||||
|
t.Fatalf("Settle waited for the long tick: %v", el)
|
||||||
|
}
|
||||||
|
m := d.Model().(toy)
|
||||||
|
have := map[string]bool{}
|
||||||
|
for _, g := range m.got {
|
||||||
|
have[g] = true
|
||||||
|
}
|
||||||
|
for _, want := range []string{"init", "a", "a-followup", "b", "c", "s1", "s2"} {
|
||||||
|
if !have[want] {
|
||||||
|
t.Errorf("missing %q in %v", want, m.got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if have["never"] {
|
||||||
|
t.Error("hour-long tick must not be awaited")
|
||||||
|
}
|
||||||
|
idx := func(s string) int {
|
||||||
|
for i, g := range m.got {
|
||||||
|
if g == s {
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
if idx("s1") > idx("s2") {
|
||||||
|
t.Errorf("sequence out of order: %v", m.got)
|
||||||
|
}
|
||||||
|
if s := d.Screen(); strings.Contains(s, "\x1b") || !strings.HasPrefix(s, "got: init") {
|
||||||
|
t.Errorf("screen not stripped: %q", s)
|
||||||
|
}
|
||||||
|
d.Press("q")
|
||||||
|
d.Settle(time.Second)
|
||||||
|
if !d.Quit() {
|
||||||
|
t.Error("tea.Quit not detected")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDriverKeys(t *testing.T) {
|
||||||
|
for _, k := range []string{"enter", "esc", "tab", "f5", "f12", "pgdown", "ctrl+r", "shift+up", "alt+left", "backspace", "delete", " ", "j", "п"} {
|
||||||
|
got := Key(t, k).String()
|
||||||
|
want := k
|
||||||
|
if k == "alt+left" {
|
||||||
|
want = "alt+left"
|
||||||
|
}
|
||||||
|
if got != want {
|
||||||
|
t.Errorf("Key(%q).String() = %q", k, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d := New(t, toy{}, 80, 24, WithoutInit())
|
||||||
|
d.Type("ab п")
|
||||||
|
if got := strings.Join(d.Model().(toy).keys, "|"); got != "a|b| |п" {
|
||||||
|
t.Errorf("typed keys %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
36
internal/theme/chroma.go
Normal file
36
internal/theme/chroma.go
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
package theme
|
||||||
|
|
||||||
|
import "strings"
|
||||||
|
|
||||||
|
// chromaStyles maps every built-in theme to the closest chroma style
|
||||||
|
// (U-P2: the old table knew 7 of the themes and fell back to catppuccin).
|
||||||
|
var chromaStyles = map[string]string{
|
||||||
|
"catppuccin-mocha": "catppuccin-mocha",
|
||||||
|
"catppuccin-macchiato": "catppuccin-macchiato",
|
||||||
|
"catppuccin-lavender": "catppuccin-mocha",
|
||||||
|
"tokyo-night": "tokyonight-night",
|
||||||
|
"gruvbox-dark": "gruvbox",
|
||||||
|
"nord": "nord",
|
||||||
|
"one-dark": "onedark",
|
||||||
|
"everforest": "evergarden",
|
||||||
|
"github-dark": "github-dark",
|
||||||
|
"ayu-dark": "doom-one",
|
||||||
|
"breeze": "nordic",
|
||||||
|
"cyberpunk": "aura-theme-dark",
|
||||||
|
"dracula": "dracula",
|
||||||
|
"eldritch": "aura-theme-dark-soft",
|
||||||
|
"kanagawa": "tokyonight-storm",
|
||||||
|
"kanagawa-paper": "tokyonight-moon",
|
||||||
|
"rose-pine": "rose-pine",
|
||||||
|
"solarized-dark": "solarized-dark",
|
||||||
|
"vesper": "monokai",
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChromaStyle returns the chroma style name for a theme (unknown themes get
|
||||||
|
// the default theme's style).
|
||||||
|
func ChromaStyle(theme string) string {
|
||||||
|
if s, ok := chromaStyles[strings.ToLower(strings.TrimSpace(theme))]; ok {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return chromaStyles[builtInThemes[0]]
|
||||||
|
}
|
||||||
26
internal/theme/chroma_test.go
Normal file
26
internal/theme/chroma_test.go
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
package theme
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/alecthomas/chroma/v2/styles"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestEveryThemeHasChromaStyle(t *testing.T) {
|
||||||
|
for _, name := range Names() {
|
||||||
|
s, ok := chromaStyles[name]
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("theme %q has no chroma mapping", name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := styles.Registry[s]; !ok {
|
||||||
|
t.Errorf("theme %q maps to unknown chroma style %q", name, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(chromaStyles) != len(Names()) {
|
||||||
|
t.Errorf("mapping has %d entries for %d themes", len(chromaStyles), len(Names()))
|
||||||
|
}
|
||||||
|
if ChromaStyle("no-such-theme") != "catppuccin-mocha" {
|
||||||
|
t.Error("fallback")
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue