* fix(installer): use 8 KiB HFS+ catalog B-tree nodes for REIMSTOOLS image * feat(guesttools): support Windows-to-macOS window drag-and-drop (Agent v13) --------- Co-authored-by: Shroap <184123002+YinLiaoCo@users.noreply.github.com>
429 lines
10 KiB
Go
429 lines
10 KiB
Go
package guesttools
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"reflect"
|
|
"regexp"
|
|
"runtime"
|
|
"sort"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
"unicode"
|
|
|
|
"golang.org/x/net/webdav"
|
|
)
|
|
|
|
const (
|
|
DropWebDAVTTL = 10 * time.Minute
|
|
DropWebDAVMaxLifetime = 60 * time.Minute
|
|
MaxDropWebDAVEntries = 64
|
|
)
|
|
|
|
var dropIDPattern = regexp.MustCompile("^[A-Za-z0-9_-]+$")
|
|
|
|
type DropShareEntry struct {
|
|
Name string
|
|
HostPath string
|
|
IsDir bool
|
|
}
|
|
|
|
type dropShareRecord struct {
|
|
id string
|
|
entries map[string]DropShareEntry
|
|
order []string
|
|
createdAt time.Time
|
|
expiresAt time.Time
|
|
}
|
|
|
|
type dropShareStore struct {
|
|
mu sync.RWMutex
|
|
now func() time.Time
|
|
modTime time.Time
|
|
records map[string]*dropShareRecord
|
|
}
|
|
|
|
func newDropShareStore() *dropShareStore {
|
|
return &dropShareStore{now: time.Now, modTime: time.Now(), records: make(map[string]*dropShareRecord)}
|
|
}
|
|
|
|
func (s *dropShareStore) touchRootLocked(now time.Time) {
|
|
if next := s.modTime.Truncate(time.Second).Add(time.Second); now.Before(next) {
|
|
now = next
|
|
}
|
|
s.modTime = now
|
|
}
|
|
|
|
func (s *dropShareStore) register(id string, entries []DropShareEntry) bool {
|
|
if !dropIDPattern.MatchString(id) || len(entries) == 0 {
|
|
return false
|
|
}
|
|
rec := &dropShareRecord{id: id, entries: make(map[string]DropShareEntry, len(entries))}
|
|
for _, e := range entries {
|
|
if e.Name == "" || e.Name == "." || e.Name == ".." || strings.ContainsAny(e.Name, "/\\") ||
|
|
strings.IndexFunc(e.Name, unicode.IsControl) >= 0 || !filepath.IsAbs(e.HostPath) {
|
|
return false
|
|
}
|
|
if _, exists := rec.entries[e.Name]; exists {
|
|
return false
|
|
}
|
|
e.HostPath = filepath.Clean(e.HostPath)
|
|
rec.entries[e.Name] = e
|
|
rec.order = append(rec.order, e.Name)
|
|
}
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
now := s.now()
|
|
s.prune(now)
|
|
delete(s.records, id)
|
|
for len(s.records) >= MaxDropWebDAVEntries {
|
|
var oldest *dropShareRecord
|
|
for _, r := range s.records {
|
|
if oldest == nil || r.createdAt.Before(oldest.createdAt) || (r.createdAt.Equal(oldest.createdAt) && r.id < oldest.id) {
|
|
oldest = r
|
|
}
|
|
}
|
|
delete(s.records, oldest.id)
|
|
}
|
|
rec.createdAt, rec.expiresAt = now, now.Add(DropWebDAVTTL)
|
|
s.records[id] = rec
|
|
s.touchRootLocked(now)
|
|
return true
|
|
}
|
|
|
|
// prune runs with the store locked.
|
|
func (s *dropShareStore) prune(now time.Time) {
|
|
count := len(s.records)
|
|
for id, rec := range s.records {
|
|
if !now.Before(rec.expiresAt) {
|
|
delete(s.records, id)
|
|
}
|
|
}
|
|
if len(s.records) != count {
|
|
s.touchRootLocked(now)
|
|
}
|
|
}
|
|
|
|
func (s *dropShareStore) touch(id string) *dropShareRecord {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
now := s.now()
|
|
rec := s.records[id]
|
|
if rec == nil {
|
|
return nil
|
|
}
|
|
if !now.Before(rec.expiresAt) {
|
|
delete(s.records, id)
|
|
s.touchRootLocked(now)
|
|
return nil
|
|
}
|
|
rec.expiresAt = now.Add(DropWebDAVTTL)
|
|
if limit := rec.createdAt.Add(DropWebDAVMaxLifetime); limit.Before(rec.expiresAt) {
|
|
rec.expiresAt = limit
|
|
}
|
|
snapshot := *rec // entries and order are immutable after registration.
|
|
return &snapshot
|
|
}
|
|
|
|
func (s *dropShareStore) rootSnapshot() (time.Time, []virtualFileInfo) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
s.prune(s.now())
|
|
entries := make([]virtualFileInfo, 0, len(s.records))
|
|
for id, rec := range s.records {
|
|
entries = append(entries, virtualFileInfo{name: id, when: rec.createdAt})
|
|
}
|
|
sort.Slice(entries, func(i, j int) bool { return entries[i].name < entries[j].name })
|
|
return s.modTime, entries
|
|
}
|
|
|
|
func (s *dropShareStore) revoke(id string) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if _, ok := s.records[id]; ok {
|
|
delete(s.records, id)
|
|
s.touchRootLocked(s.now())
|
|
}
|
|
}
|
|
|
|
func (s *dropShareStore) clear() {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
if len(s.records) > 0 {
|
|
clear(s.records)
|
|
s.touchRootLocked(s.now())
|
|
}
|
|
}
|
|
|
|
type dropWebDAVFS struct{ store *dropShareStore }
|
|
|
|
var _ webdav.FileSystem = (*dropWebDAVFS)(nil)
|
|
|
|
func (*dropWebDAVFS) Mkdir(context.Context, string, os.FileMode) error { return os.ErrPermission }
|
|
func (*dropWebDAVFS) RemoveAll(context.Context, string) error { return os.ErrPermission }
|
|
func (*dropWebDAVFS) Rename(context.Context, string, string) error { return os.ErrPermission }
|
|
|
|
type virtualFileInfo struct {
|
|
name string
|
|
when time.Time
|
|
}
|
|
|
|
func (i virtualFileInfo) Name() string { return i.name }
|
|
func (i virtualFileInfo) Size() int64 { return 0 }
|
|
func (i virtualFileInfo) Mode() os.FileMode { return os.ModeDir | 0555 }
|
|
func (i virtualFileInfo) ModTime() time.Time { return i.when }
|
|
func (i virtualFileInfo) IsDir() bool { return true }
|
|
func (i virtualFileInfo) Sys() any { return nil }
|
|
|
|
type virtualDAVDir struct {
|
|
info virtualFileInfo
|
|
entries []os.FileInfo
|
|
}
|
|
|
|
func (d *virtualDAVDir) Stat() (os.FileInfo, error) { return d.info, nil }
|
|
func (*virtualDAVDir) Close() error { return nil }
|
|
func (*virtualDAVDir) Read([]byte) (int, error) { return 0, os.ErrInvalid }
|
|
func (*virtualDAVDir) Seek(int64, int) (int64, error) { return 0, os.ErrInvalid }
|
|
func (*virtualDAVDir) Write([]byte) (int, error) { return 0, os.ErrPermission }
|
|
|
|
func (d *virtualDAVDir) Readdir(n int) ([]os.FileInfo, error) {
|
|
if n > 0 && len(d.entries) == 0 {
|
|
return nil, io.EOF
|
|
}
|
|
if n <= 0 || n > len(d.entries) {
|
|
n = len(d.entries)
|
|
}
|
|
out := d.entries[:n]
|
|
d.entries = d.entries[n:]
|
|
return out, nil
|
|
}
|
|
|
|
type dropNamedInfo struct {
|
|
os.FileInfo
|
|
name string
|
|
}
|
|
|
|
func (i dropNamedInfo) Name() string { return i.name }
|
|
|
|
// IsDropSymlink reports whether a drop entry is a symlink, irregular file, or Windows reparse point.
|
|
func IsDropSymlink(st os.FileInfo) bool {
|
|
if st.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0 {
|
|
return true
|
|
}
|
|
if runtime.GOOS == "windows" {
|
|
v := reflect.Indirect(reflect.ValueOf(st.Sys()))
|
|
if v.Kind() == reflect.Struct {
|
|
attr := v.FieldByName("FileAttributes")
|
|
return attr.CanUint() && attr.Uint()&0x400 != 0
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func dropEntryInfo(e DropShareEntry) (os.FileInfo, error) {
|
|
st, err := os.Lstat(e.HostPath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if IsDropSymlink(st) || st.IsDir() != e.IsDir || (!e.IsDir && !st.Mode().IsRegular()) {
|
|
return nil, os.ErrPermission
|
|
}
|
|
return st, nil
|
|
}
|
|
|
|
func (f *dropWebDAVFS) OpenFile(_ context.Context, name string, flag int, _ os.FileMode) (webdav.File, error) {
|
|
const writeFlags = os.O_WRONLY | os.O_RDWR | os.O_CREATE | os.O_TRUNC | os.O_APPEND | os.O_EXCL
|
|
if flag&writeFlags != 0 {
|
|
return nil, os.ErrPermission
|
|
}
|
|
if strings.Contains("/"+name+"/", "/../") {
|
|
return nil, os.ErrInvalid
|
|
}
|
|
rel, err := davRelativePath(name)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if rel == "." {
|
|
when, entries := f.store.rootSnapshot()
|
|
d := &virtualDAVDir{info: virtualFileInfo{name: ".", when: when}}
|
|
for _, entry := range entries {
|
|
d.entries = append(d.entries, entry)
|
|
}
|
|
return d, nil
|
|
}
|
|
id, rest, hasRest := strings.Cut(rel, "/")
|
|
rec := f.store.touch(id)
|
|
if rec == nil {
|
|
return nil, os.ErrNotExist
|
|
}
|
|
if !hasRest {
|
|
d := &virtualDAVDir{info: virtualFileInfo{name: id, when: rec.createdAt}}
|
|
for _, alias := range rec.order {
|
|
if st, err := dropEntryInfo(rec.entries[alias]); err == nil {
|
|
d.entries = append(d.entries, dropNamedInfo{st, alias})
|
|
}
|
|
}
|
|
return d, nil
|
|
}
|
|
alias, sub, hasSub := strings.Cut(rest, "/")
|
|
e, ok := rec.entries[alias]
|
|
if !ok || (hasSub && !e.IsDir) {
|
|
return nil, os.ErrNotExist
|
|
}
|
|
expected, err := dropEntryInfo(e)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
dir, target := filepath.Dir(e.HostPath), filepath.Base(e.HostPath)
|
|
if e.IsDir {
|
|
dir, target = e.HostPath, "."
|
|
}
|
|
root, err := os.OpenRoot(dir)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
// Pin each checked directory before looking up its child.
|
|
defer func() {
|
|
if root != nil {
|
|
root.Close()
|
|
}
|
|
}()
|
|
if e.IsDir {
|
|
st, err := statDAVEntry(root, ".")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if IsDropSymlink(st) || !os.SameFile(expected, st) {
|
|
return nil, os.ErrPermission
|
|
}
|
|
}
|
|
if hasSub {
|
|
alias = path.Base(sub)
|
|
for {
|
|
part, tail, more := strings.Cut(sub, "/")
|
|
expected, err = statDAVEntry(root, part)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if IsDropSymlink(expected) || (!expected.IsDir() && !expected.Mode().IsRegular()) {
|
|
return nil, os.ErrPermission
|
|
}
|
|
if !more {
|
|
target = part
|
|
break
|
|
}
|
|
next, err := root.OpenRoot(part)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
root.Close()
|
|
root = next
|
|
st, err := root.Stat(".")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !os.SameFile(expected, st) {
|
|
return nil, os.ErrPermission
|
|
}
|
|
sub = tail
|
|
}
|
|
}
|
|
file, err := root.Open(target)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
st, err := file.Stat()
|
|
if err != nil || !os.SameFile(expected, st) {
|
|
file.Close()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return nil, os.ErrPermission
|
|
}
|
|
handle := &dropRootFile{File: file, root: root, name: alias}
|
|
root = nil
|
|
return handle, nil
|
|
}
|
|
|
|
type dropRootFile struct {
|
|
*os.File
|
|
root *os.Root
|
|
name string
|
|
}
|
|
|
|
func (f *dropRootFile) Close() error { return errors.Join(f.File.Close(), f.root.Close()) }
|
|
|
|
func (f *dropRootFile) Stat() (os.FileInfo, error) {
|
|
st, err := f.File.Stat()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return dropNamedInfo{st, f.name}, nil
|
|
}
|
|
|
|
func (f *dropRootFile) Readdir(n int) ([]os.FileInfo, error) {
|
|
var out []os.FileInfo
|
|
for {
|
|
count := n
|
|
if n > 0 {
|
|
count -= len(out)
|
|
}
|
|
batch, err := f.File.Readdir(count)
|
|
for _, st := range batch {
|
|
if !IsDropSymlink(st) && (st.IsDir() || st.Mode().IsRegular()) {
|
|
out = append(out, st)
|
|
}
|
|
}
|
|
if err != nil || n <= 0 || len(out) == n {
|
|
return out, err
|
|
}
|
|
}
|
|
}
|
|
|
|
func (f *dropWebDAVFS) Stat(ctx context.Context, name string) (os.FileInfo, error) {
|
|
file, err := f.OpenFile(ctx, name, os.O_RDONLY, 0)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer file.Close()
|
|
return file.Stat()
|
|
}
|
|
|
|
func (f *dropWebDAVFS) serveDropFile(w http.ResponseWriter, r *http.Request, dropID, relPath string) {
|
|
rel, err := davRelativePath(relPath)
|
|
if !dropIDPattern.MatchString(dropID) || err != nil || rel != relPath || rel == "." {
|
|
http.Error(w, "invalid drop path", http.StatusBadRequest)
|
|
return
|
|
}
|
|
file, err := f.OpenFile(r.Context(), path.Join("/", dropID, rel), os.O_RDONLY, 0)
|
|
if err == nil {
|
|
defer file.Close()
|
|
var st os.FileInfo
|
|
st, err = file.Stat()
|
|
if err == nil {
|
|
if st.IsDir() {
|
|
http.Error(w, "expected a file", http.StatusBadRequest)
|
|
return
|
|
}
|
|
http.ServeContent(w, r, st.Name(), st.ModTime(), file)
|
|
return
|
|
}
|
|
}
|
|
status := http.StatusInternalServerError
|
|
switch {
|
|
case errors.Is(err, os.ErrNotExist):
|
|
status = http.StatusNotFound
|
|
case errors.Is(err, os.ErrPermission):
|
|
status = http.StatusForbidden
|
|
case errors.Is(err, os.ErrInvalid):
|
|
status = http.StatusBadRequest
|
|
}
|
|
http.Error(w, http.StatusText(status), status)
|
|
}
|