feat(vfs/localfs): freedesktop trash with topdir support (2A.4)

Items on another volume go to $topdir/.Trash/$uid (real, sticky .Trash only)
or $topdir/.Trash-$uid instead of failing with EXDEV (N-P2-12). The
.trashinfo is reserved with O_EXCL (collisions get a .N suffix and skip
orphans in files/), Path= is URL-encoded, DeletionDate is local time, and
under sudo the effective user's trash is used. The old UI's MoveToTrash now
delegates here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
vrubelroman 2026-10-31 23:28:31 +03:00
parent 9d5b6bf0c4
commit 39e8264528
4 changed files with 492 additions and 60 deletions

View file

@ -12,7 +12,7 @@ import (
"syscall" "syscall"
"time" "time"
"vcom/internal/homedir" "vcom/internal/vfs/localfs"
) )
type TransferStats struct { type TransferStats struct {
@ -272,63 +272,12 @@ 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) {

View file

@ -21,6 +21,7 @@ type FS struct {
var ( var (
_ vfs.FS = (*FS)(nil) _ vfs.FS = (*FS)(nil)
_ vfs.Trasher = (*FS)(nil)
_ vfs.BirthTimer = (*FS)(nil) _ vfs.BirthTimer = (*FS)(nil)
) )
@ -40,6 +41,7 @@ func (*FS) Caps() vfs.Caps {
Chmod: true, Chmod: true,
Chtimes: true, Chtimes: true,
Fsync: true, Fsync: true,
Trash: true,
Exec: true, Exec: true,
} }
} }

View file

@ -1,6 +1,263 @@
package localfs package localfs
// trashConfig is filled in by the trash implementation (2A.4). import (
type trashConfig struct{} "context"
"errors"
"fmt"
"io/fs"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
func defaultTrashConfig() trashConfig { return trashConfig{} } "vcom/internal/vfs"
)
// trashConfig holds what the freedesktop trash depends on, so tests can fake
// devices and homes.
type trashConfig struct {
// dataHome returns the effective user's XDG data home; the home trash
// is dataHome()/Trash.
dataHome func() (string, error)
// uid is the effective uid (topdir trash names, sudo → root's trash).
uid int
// statDev returns the device of p without following a final symlink.
statDev func(p string) (uint64, error)
now func() time.Time
}
func defaultTrashConfig() trashConfig {
return trashConfig{dataHome: effectiveDataHome, uid: os.Geteuid(), statDev: lstatDev, now: time.Now}
}
func lstatDev(p string) (uint64, error) {
fi, err := os.Lstat(p)
if err != nil {
return 0, err
}
st, ok := fi.Sys().(*syscall.Stat_t)
if !ok {
return 0, fmt.Errorf("stat %s: no device information", p)
}
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):
// - 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
// real directory with the sticky bit, else $topdir/.Trash-$uid; info Path=
// relative to $topdir. Never a cross-device copy.
//
// The .trashinfo file is created with O_EXCL first (it reserves the name;
// collisions get a ".N" suffix), Path= is URL-encoded and DeletionDate is local
// time. p itself is moved without following a final symlink.
func (f *FS) Trash(_ context.Context, p string) error {
c := f.trash
abs, err := filepath.Abs(p)
if err != nil {
return err
}
if abs == string(filepath.Separator) {
return fmt.Errorf("trash %s: refusing to trash the root directory", abs)
}
if _, err := os.Lstat(abs); err != nil {
return mapErr(err)
}
dev, err := c.statDev(abs)
if err != nil {
return mapErr(err)
}
trashDir, infoPath, err := c.pickTrash(abs, dev)
if err != nil {
return err
}
filesDir := filepath.Join(trashDir, "files")
infoDir := filepath.Join(trashDir, "info")
for _, d := range []string{filesDir, infoDir} {
if err := ensurePrivateDir(d); err != nil {
return fmt.Errorf("trash %s: %w", abs, err)
}
}
name, info, err := reserveTrashName(filesDir, infoDir, filepath.Base(abs))
if err != nil {
return fmt.Errorf("trash %s: %w", abs, err)
}
content := "[Trash Info]\nPath=" + trashEscape(infoPath) +
"\nDeletionDate=" + c.now().Format("2006-01-02T15:04:05") + "\n"
if _, err := info.WriteString(content); err == nil {
err = info.Sync()
}
cerr := info.Close()
infoFile := filepath.Join(infoDir, name+".trashinfo")
if err != nil || cerr != nil {
_ = os.Remove(infoFile)
return fmt.Errorf("trash %s: write info: %w", abs, errors.Join(err, cerr))
}
if err := renameNoReplace(abs, filepath.Join(filesDir, name)); err != nil {
_ = os.Remove(infoFile)
return mapErr(err)
}
return nil
}
// pickTrash returns the trash directory for abs and the Path= value for its
// info file.
func (c trashConfig) pickTrash(abs string, dev uint64) (dir, infoPath string, err error) {
home, err := c.dataHome()
if err != nil {
return "", "", err
}
homeTrash := filepath.Join(home, "Trash")
if vfs.IsWithin(vfs.NativePaths, abs, homeTrash) {
return "", "", fmt.Errorf("trash %s: already in the trash", abs)
}
homeDev, err := c.statDev(existingAncestor(homeTrash))
if err != nil {
return "", "", err
}
if homeDev == dev {
if err := os.MkdirAll(homeTrash, 0o700); err != nil {
return "", "", fmt.Errorf("trash %s: %w", abs, err)
}
return homeTrash, abs, nil
}
top := c.topdir(abs, dev)
rel, err := filepath.Rel(top, abs)
if err != nil {
return "", "", err
}
uid := strconv.Itoa(c.uid)
// $topdir/.Trash/$uid: only if .Trash is a real, sticky directory.
shared := filepath.Join(top, ".Trash")
if fi, err := os.Lstat(shared); err == nil && fi.IsDir() && fi.Mode()&fs.ModeSticky != 0 {
d := filepath.Join(shared, uid)
if err := ensurePrivateDir(d); err == nil {
return d, rel, nil
}
}
d := filepath.Join(top, ".Trash-"+uid)
if err := ensurePrivateDir(d); err != nil {
return "", "", fmt.Errorf("trash %s: no usable trash on this volume (%s): %w", abs, top, err)
}
return d, rel, nil
}
// topdir climbs from abs's parent while the device stays the same: the mount
// point of the volume abs lives on.
func (c trashConfig) topdir(abs string, dev uint64) string {
d := filepath.Dir(abs)
for {
parent := filepath.Dir(d)
if parent == d {
return d
}
if pd, err := c.statDev(parent); err != nil || pd != dev {
return d
}
d = parent
}
}
func existingAncestor(p string) string {
for {
if _, err := os.Lstat(p); err == nil {
return p
}
parent := filepath.Dir(p)
if parent == p {
return p
}
p = parent
}
}
// ensurePrivateDir creates d (0700) if missing and checks it is a real
// directory, not a symlink planted by someone else.
func ensurePrivateDir(d string) error {
if err := os.Mkdir(d, 0o700); err != nil && !errors.Is(err, fs.ErrExist) {
return err
}
fi, err := os.Lstat(d)
if err != nil {
return err
}
if !fi.IsDir() {
return fmt.Errorf("%s is not a directory", d)
}
return nil
}
// reserveTrashName creates info/<name>.trashinfo with O_EXCL for the first
// free name (base, base.2, base.3, ...) that is also free in files/.
func reserveTrashName(filesDir, infoDir, base string) (string, *os.File, error) {
for i := 1; i <= 10000; i++ {
name := base
if i > 1 {
name = base + "." + strconv.Itoa(i)
}
infoFile := filepath.Join(infoDir, name+".trashinfo")
f, err := os.OpenFile(infoFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if errors.Is(err, fs.ErrExist) {
continue
}
if err != nil {
return "", nil, err
}
if _, err := os.Lstat(filepath.Join(filesDir, name)); err == nil {
// An orphan in files/ without info: leave it, try the next name.
f.Close()
_ = os.Remove(infoFile)
continue
}
return name, f, nil
}
return "", nil, fmt.Errorf("no free name for %q in the trash", base)
}
// trashEscape URL-encodes a path for Path= (RFC 2396 as the spec asks): bytes
// other than unreserved characters and '/' become %XX, so spaces and
// non-ASCII names survive other tools' restore.
func trashEscape(p string) string {
const hex = "0123456789ABCDEF"
var b strings.Builder
for i := 0; i < len(p); i++ {
c := p[i]
switch {
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9',
c == '/', c == '-', c == '_', c == '.', c == '~':
b.WriteByte(c)
default:
b.WriteByte('%')
b.WriteByte(hex[c>>4])
b.WriteByte(hex[c&15])
}
}
return b.String()
}

View file

@ -0,0 +1,224 @@
package localfs
import (
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"vcom/internal/testutil/fstree"
)
var fixedNow = time.Date(2026, 10, 31, 12, 34, 56, 0, time.Local)
// newTrashFS returns an FS whose home trash lives in <tmp>/home/.local/share/Trash.
func newTrashFS(t *testing.T) (fsys *FS, tmp, trash string) {
tmp = t.TempDir()
data := filepath.Join(tmp, "home", ".local", "share")
fsys = New()
fsys.trash.dataHome = func() (string, error) { return data, nil }
fsys.trash.now = func() time.Time { return fixedNow }
return fsys, tmp, filepath.Join(data, "Trash")
}
func readInfo(t *testing.T, trash, name string) (path, date string) {
t.Helper()
b, err := os.ReadFile(filepath.Join(trash, "info", name+".trashinfo"))
if err != nil {
t.Fatal(err)
}
lines := strings.Split(strings.TrimSpace(string(b)), "\n")
if len(lines) != 3 || lines[0] != "[Trash Info]" {
t.Fatalf("info file:\n%s", b)
}
return strings.TrimPrefix(lines[1], "Path="), strings.TrimPrefix(lines[2], "DeletionDate=")
}
func TestTrashHome(t *testing.T) {
fsys, tmp, trash := newTrashFS(t)
fstree.Build(t, tmp, fstree.Spec{
fstree.File("work/a.txt", "A"),
fstree.File("work/dir/x", "X"),
fstree.File("target/keep", "K"),
fstree.Symlink("work/link", "../target"),
})
for _, n := range []string{"a.txt", "dir", "link"} {
if err := fsys.Trash(ctx, filepath.Join(tmp, "work", n)); err != nil {
t.Fatalf("trash %s: %v", n, err)
}
if _, err := os.Lstat(filepath.Join(tmp, "work", n)); !os.IsNotExist(err) {
t.Fatalf("%s still in place", n)
}
p, date := readInfo(t, trash, n)
if p != filepath.Join(tmp, "work", n) { // temp paths are plain ASCII
t.Fatalf("Path=%s", p)
}
if date != "2026-10-31T12:34:56" {
t.Fatalf("DeletionDate=%s", date)
}
}
if b, _ := os.ReadFile(filepath.Join(trash, "files", "a.txt")); string(b) != "A" {
t.Fatal("file content not in trash")
}
if b, _ := os.ReadFile(filepath.Join(trash, "files", "dir", "x")); string(b) != "X" {
t.Fatal("dir not in trash")
}
if fi, err := os.Lstat(filepath.Join(trash, "files", "link")); err != nil || fi.Mode()&os.ModeSymlink == 0 {
t.Fatalf("link must be trashed as a link: %v %v", fi, err)
}
if b, _ := os.ReadFile(filepath.Join(tmp, "target", "keep")); string(b) != "K" {
t.Fatal("link target damaged")
}
for _, d := range []string{"files", "info"} {
if fi, _ := os.Stat(filepath.Join(trash, d)); fi.Mode().Perm() != 0o700 {
t.Fatalf("%s mode %v", d, fi.Mode().Perm())
}
}
if err := fsys.Trash(ctx, filepath.Join(trash, "files", "a.txt")); err == nil {
t.Fatal("trashing inside the trash must fail")
}
if err := fsys.Trash(ctx, filepath.Join(tmp, "work", "missing")); !os.IsNotExist(err) {
t.Fatalf("missing: %v", err)
}
}
func TestTrashInfoURLEncoded(t *testing.T) {
fsys, tmp, trash := newTrashFS(t)
rel := "папка/my file ё%.txt"
fstree.Build(t, tmp, fstree.Spec{fstree.File(rel, "")})
src := filepath.Join(tmp, rel)
if err := fsys.Trash(ctx, src); err != nil {
t.Fatal(err)
}
p, _ := readInfo(t, trash, "my file ё%.txt")
if strings.ContainsAny(p, " ёп") {
t.Fatalf("Path= not encoded: %s", p)
}
if !strings.HasSuffix(p, "/%D0%BF%D0%B0%D0%BF%D0%BA%D0%B0/my%20file%20%D1%91%25.txt") {
t.Fatalf("Path=%s", p)
}
if dec, err := url.PathUnescape(p); err != nil || dec != src {
t.Fatalf("decoded %q, %v; want %q", dec, err, src)
}
}
func TestTrashNameCollision(t *testing.T) {
fsys, tmp, trash := newTrashFS(t)
fstree.Build(t, tmp, fstree.Spec{
fstree.File("one/a.txt", "1"),
fstree.File("two/a.txt", "2"),
fstree.File("three/a.txt", "3"),
})
for _, d := range []string{"one", "two"} {
if err := fsys.Trash(ctx, filepath.Join(tmp, d, "a.txt")); err != nil {
t.Fatal(err)
}
}
// An orphan in files/ without an info file blocks its name too.
if err := os.WriteFile(filepath.Join(trash, "files", "a.txt.3"), []byte("orphan"), 0o600); err != nil {
t.Fatal(err)
}
if err := fsys.Trash(ctx, filepath.Join(tmp, "three", "a.txt")); err != nil {
t.Fatal(err)
}
for name, want := range map[string]string{"a.txt": "1", "a.txt.2": "2", "a.txt.3": "orphan", "a.txt.4": "3"} {
if b, _ := os.ReadFile(filepath.Join(trash, "files", name)); string(b) != want {
t.Errorf("files/%s = %q, want %q", name, b, want)
}
}
if p, _ := readInfo(t, trash, "a.txt.4"); p != filepath.Join(tmp, "three", "a.txt") {
t.Errorf("info a.txt.4 Path=%s", p)
}
if _, err := os.Stat(filepath.Join(trash, "info", "a.txt.3.trashinfo")); !os.IsNotExist(err) {
t.Error("an info file was left for the orphan's name")
}
}
// TestTrashTopdir fakes a second volume mounted at <tmp>/vol (N-P2-12: the
// old code failed with EXDEV here).
func TestTrashTopdir(t *testing.T) {
setup := func(t *testing.T) (*FS, string, string) {
fsys, tmp, _ := newTrashFS(t)
vol := filepath.Join(tmp, "vol")
fsys.trash.uid = 1234
fsys.trash.statDev = func(p string) (uint64, error) {
if _, err := os.Lstat(p); err != nil {
return 0, err
}
if p == vol || strings.HasPrefix(p, vol+"/") {
return 2, nil
}
return 1, nil
}
fstree.Build(t, tmp, fstree.Spec{fstree.File("vol/sub/f b.txt", "data")})
return fsys, tmp, vol
}
t.Run("TrashUID", func(t *testing.T) {
fsys, tmp, vol := setup(t)
if err := fsys.Trash(ctx, filepath.Join(vol, "sub", "f b.txt")); err != nil {
t.Fatal(err)
}
trash := filepath.Join(vol, ".Trash-1234")
if b, _ := os.ReadFile(filepath.Join(trash, "files", "f b.txt")); string(b) != "data" {
t.Fatal("not in $topdir/.Trash-$uid")
}
if p, _ := readInfo(t, trash, "f b.txt"); p != "sub/f%20b.txt" {
t.Fatalf("Path=%s, want relative to topdir", p)
}
if fi, _ := os.Stat(trash); fi.Mode().Perm() != 0o700 {
t.Fatalf("mode %v", fi.Mode().Perm())
}
if _, err := os.Stat(filepath.Join(tmp, "home", ".local", "share", "Trash", "files")); !os.IsNotExist(err) {
t.Fatal("home trash must not be used across devices")
}
})
t.Run("SharedStickyTrash", func(t *testing.T) {
fsys, _, vol := setup(t)
shared := filepath.Join(vol, ".Trash")
if err := os.Mkdir(shared, 0o777|os.ModeSticky); err != nil {
t.Fatal(err)
}
if err := os.Chmod(shared, 0o777|os.ModeSticky); err != nil {
t.Fatal(err)
}
if err := fsys.Trash(ctx, filepath.Join(vol, "sub", "f b.txt")); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(shared, strconv.Itoa(1234), "files", "f b.txt")); err != nil {
t.Fatalf("not in $topdir/.Trash/$uid: %v", err)
}
})
t.Run("RejectsSymlinkedOrNonStickyTrash", func(t *testing.T) {
fsys, tmp, vol := setup(t)
// .Trash as a symlink to a sticky dir elsewhere must be ignored.
elsewhere := filepath.Join(tmp, "elsewhere")
if err := os.Mkdir(elsewhere, 0o777); err != nil {
t.Fatal(err)
}
_ = os.Chmod(elsewhere, 0o777|os.ModeSticky)
if err := os.Symlink(elsewhere, filepath.Join(vol, ".Trash")); err != nil {
t.Fatal(err)
}
if err := fsys.Trash(ctx, filepath.Join(vol, "sub", "f b.txt")); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(vol, ".Trash-1234", "files", "f b.txt")); err != nil {
t.Fatalf("expected fallback to .Trash-$uid: %v", err)
}
if ents, _ := os.ReadDir(elsewhere); len(ents) != 0 {
t.Fatal("followed a symlinked .Trash")
}
})
}
func TestTrashEscape(t *testing.T) {
if got := trashEscape("/a b/~x_y-z.1/#?&"); got != "/a%20b/~x_y-z.1/%23%3F%26" {
t.Fatal(got)
}
}