feat(paths,atomicfile): XDG/sudo path rules and atomic local file writes (2C.1)
paths: config lookup -config → $VCOM_CONFIG → XDG → ~/.config (never the working directory; StrayCwdConfig only reports one), state/cache/data dirs of the effective user under sudo (inherited XDG_* ignored for writes), run-<pid> dir with a sweep of dead processes' dirs (U-P1-15). atomicfile: temp + fsync + rename + dir fsync; keeps the old file on any error, writes through symlinks and keeps mode/owner of an existing file. The trash now takes its home from paths.DataHome. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2653df7a03
commit
1c57f92c42
5 changed files with 724 additions and 25 deletions
133
internal/atomicfile/atomicfile.go
Normal file
133
internal/atomicfile/atomicfile.go
Normal file
|
|
@ -0,0 +1,133 @@
|
||||||
|
// 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"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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, 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)
|
||||||
|
}
|
||||||
|
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()
|
||||||
|
}
|
||||||
100
internal/atomicfile/atomicfile_test.go
Normal file
100
internal/atomicfile/atomicfile_test.go
Normal file
|
|
@ -0,0 +1,100 @@
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
313
internal/paths/paths.go
Normal file
313
internal/paths/paths.go
Normal file
|
|
@ -0,0 +1,313 @@
|
||||||
|
// 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. Under sudo it is
|
||||||
|
// the effective user's, so root does not create files in ~user.
|
||||||
|
func DefaultConfigFile() (string, error) {
|
||||||
|
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
|
||||||
|
}
|
||||||
174
internal/paths/paths_test.go
Normal file
174
internal/paths/paths_test.go
Normal file
|
|
@ -0,0 +1,174 @@
|
||||||
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -6,21 +6,21 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"os"
|
"os"
|
||||||
"os/user"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"vcom/internal/paths"
|
||||||
"vcom/internal/vfs"
|
"vcom/internal/vfs"
|
||||||
)
|
)
|
||||||
|
|
||||||
// trashConfig holds what the freedesktop trash depends on, so tests can fake
|
// trashConfig holds what the freedesktop trash depends on, so tests can fake
|
||||||
// devices and homes.
|
// devices and homes.
|
||||||
type trashConfig struct {
|
type trashConfig struct {
|
||||||
// dataHome returns the effective user's XDG data home; the home trash
|
// dataHome returns the effective user's XDG data home (under sudo:
|
||||||
// is dataHome()/Trash.
|
// root's, never the invoking user's); the home trash is dataHome()/Trash.
|
||||||
dataHome func() (string, error)
|
dataHome func() (string, error)
|
||||||
// uid is the effective uid (topdir trash names, sudo → root's trash).
|
// uid is the effective uid (topdir trash names, sudo → root's trash).
|
||||||
uid int
|
uid int
|
||||||
|
|
@ -30,7 +30,7 @@ type trashConfig struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultTrashConfig() trashConfig {
|
func defaultTrashConfig() trashConfig {
|
||||||
return trashConfig{dataHome: effectiveDataHome, uid: os.Geteuid(), statDev: lstatDev, now: time.Now}
|
return trashConfig{dataHome: paths.DataHome, uid: os.Geteuid(), statDev: lstatDev, now: time.Now}
|
||||||
}
|
}
|
||||||
|
|
||||||
func lstatDev(p string) (uint64, error) {
|
func lstatDev(p string) (uint64, error) {
|
||||||
|
|
@ -45,27 +45,6 @@ func lstatDev(p string) (uint64, error) {
|
||||||
return uint64(st.Dev), nil //nolint:unconvert // Dev is int32 on darwin
|
return uint64(st.Dev), nil //nolint:unconvert // Dev is int32 on darwin
|
||||||
}
|
}
|
||||||
|
|
||||||
// effectiveDataHome is the data home of the EFFECTIVE user: under sudo the
|
|
||||||
// trash belongs to root, never to the invoking user's home (no root-owned
|
|
||||||
// files in ~user; U-P2 MoveToTrash).
|
|
||||||
func effectiveDataHome() (string, error) {
|
|
||||||
if os.Geteuid() == 0 && os.Getenv("SUDO_USER") != "" {
|
|
||||||
u, err := user.LookupId("0")
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("trash: resolve root's home: %w", err)
|
|
||||||
}
|
|
||||||
return filepath.Join(u.HomeDir, ".local", "share"), nil
|
|
||||||
}
|
|
||||||
if d := os.Getenv("XDG_DATA_HOME"); filepath.IsAbs(d) {
|
|
||||||
return d, nil
|
|
||||||
}
|
|
||||||
h, err := os.UserHomeDir()
|
|
||||||
if err != nil {
|
|
||||||
return "", fmt.Errorf("trash: %w", err)
|
|
||||||
}
|
|
||||||
return filepath.Join(h, ".local", "share"), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Trash moves p to the freedesktop.org trash (design §2.3):
|
// Trash moves p to the freedesktop.org trash (design §2.3):
|
||||||
// - same device as the home trash → $XDG_DATA_HOME/Trash, info Path= absolute;
|
// - same device as the home trash → $XDG_DATA_HOME/Trash, info Path= absolute;
|
||||||
// - otherwise the volume's top directory: $topdir/.Trash/$uid if .Trash is a
|
// - otherwise the volume's top directory: $topdir/.Trash/$uid if .Trash is a
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue