Files
Reims-Go/internal/guesttools/drop_webdav.go
T

490 lines
12 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
clipboard bool
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 sameDropEntries(rec *dropShareRecord, entries []DropShareEntry) bool {
if len(rec.order) != len(entries) {
return false
}
for i, entry := range entries {
entry.HostPath = filepath.Clean(entry.HostPath)
if rec.order[i] != entry.Name || rec.entries[entry.Name] != entry {
return false
}
}
return true
}
func (s *dropShareStore) ensure(id string, entries []DropShareEntry) bool {
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
if rec := s.records[id]; rec != nil && rec.clipboard && now.Before(rec.expiresAt) && sameDropEntries(rec, entries) {
rec.renew(now)
return true
}
return s.registerLocked(id, entries, true, now)
}
func (s *dropShareStore) register(id string, entries []DropShareEntry) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.registerLocked(id, entries, false, s.now())
}
func (s *dropShareStore) registerLocked(id string, entries []DropShareEntry, clipboard bool, now time.Time) bool {
if !dropIDPattern.MatchString(id) || len(entries) == 0 {
return false
}
rec := &dropShareRecord{id: id, clipboard: clipboard, 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.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 (rec *dropShareRecord) renew(now time.Time) {
rec.expiresAt = now.Add(DropWebDAVTTL)
if limit := rec.createdAt.Add(DropWebDAVMaxLifetime); limit.Before(rec.expiresAt) {
rec.expiresAt = limit
}
}
func (s *dropShareStore) touch(id string, allowClipboard bool) *dropShareRecord {
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
rec := s.records[id]
if rec == nil || (rec.clipboard && !allowClipboard) {
return nil
}
if !now.Before(rec.expiresAt) {
delete(s.records, id)
s.touchRootLocked(now)
return nil
}
rec.renew(now)
snapshot := *rec // entries and order are immutable after registration.
return &snapshot
}
func (s *dropShareStore) rootSnapshot(allowClipboard bool) (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 {
if rec.clipboard && !allowClipboard {
continue
}
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) revokeClipboard() {
s.mu.Lock()
defer s.mu.Unlock()
count := len(s.records)
for id, rec := range s.records {
if rec.clipboard {
delete(s.records, id)
}
}
if len(s.records) != count {
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
allowClipboard func() bool
}
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
}
// resolveDropPath returns a pinned parent and the checked leaf beneath it.
// Clipboard paths must be walked from the local volume root: opening the
// selected directory by its absolute name would follow junctions in its parents.
func resolveDropPath(hostPath, sub string, clipboard bool) (*os.Root, string, os.FileInfo, error) {
dir, rel := filepath.Dir(hostPath), filepath.Base(hostPath)
if clipboard {
dir = filepath.VolumeName(hostPath) + string(os.PathSeparator)
if err := checkClipboardDrive(dir); err != nil {
return nil, "", nil, err
}
rel = strings.TrimPrefix(hostPath, dir)
}
if dir == hostPath {
rel = "."
}
rel = filepath.ToSlash(rel)
if sub != "" {
rel += "/" + sub
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, "", nil, err
}
for {
part, tail, more := strings.Cut(rel, "/")
st, err := root.Lstat(part)
if err == nil && (IsDropSymlink(st) || (!st.IsDir() && (more || !st.Mode().IsRegular()))) {
err = os.ErrPermission
}
if err != nil {
root.Close()
return nil, "", nil, err
}
if !more {
return root, part, st, nil
}
child, err := root.OpenRoot(part)
root.Close()
if err != nil {
return nil, "", nil, err
}
actual, err := child.Stat(".")
if err == nil && (IsDropSymlink(actual) || !os.SameFile(st, actual)) {
err = os.ErrPermission
}
if err != nil {
child.Close()
return nil, "", nil, err
}
root, rel = child, tail
}
}
func statDropPath(hostPath string, clipboard bool) (os.FileInfo, error) {
root, _, st, err := resolveDropPath(hostPath, "", clipboard)
if err != nil {
return nil, err
}
root.Close()
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
}
allowClipboard := f.allowClipboard != nil && f.allowClipboard()
if rel == "." {
when, entries := f.store.rootSnapshot(allowClipboard)
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, allowClipboard)
if rec == nil {
return nil, os.ErrNotExist
}
if !hasRest {
d := &virtualDAVDir{info: virtualFileInfo{name: id, when: rec.createdAt}}
for _, alias := range rec.order {
e := rec.entries[alias]
if st, err := statDropPath(e.HostPath, rec.clipboard); err == nil && st.IsDir() == e.IsDir {
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
}
root, target, expected, err := resolveDropPath(e.HostPath, sub, rec.clipboard)
if err != nil {
return nil, err
}
defer func() {
if root != nil {
root.Close()
}
}()
if hasSub {
alias = path.Base(sub)
} else if expected.IsDir() != e.IsDir {
return nil, os.ErrPermission
}
file, err := root.Open(target)
if err != nil {
return nil, err
}
st, err := file.Stat()
if err != nil || IsDropSymlink(st) || !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 serveDropFile(f webdav.FileSystem, 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)
}