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

208 lines
5.4 KiB
Go

package guesttools
import (
"errors"
"fmt"
"net/http"
"os"
"regexp"
"slices"
"strings"
"unicode"
"golang.org/x/net/webdav"
)
const SharedFolderAgentVersion = 9
const KeymapAgentVersion = 10
const TimezoneAgentVersion = 11
const HostDNSAgentVersion = 12
const WindowDropAgentVersion = 13
const ClipboardReliabilityAgentVersion = 14
const ClipboardFilesAgentVersion = 15
const BidirectionalClipboardFilesAgentVersion = 16
const WindowReportAgentVersion = 17
const PasteReadyAgentVersion = 18
const FileClipboardReadinessAgentVersion = 19
const CurrentAgentVersion = FileClipboardReadinessAgentVersion
type SharedFolderConfig struct {
ID string `json:"id"`
Name string `json:"name"`
HostPath string `json:"host_path"`
Writable bool `json:"writable,omitempty"`
Enabled bool `json:"enabled"`
VolumeGUID string `json:"volume_guid,omitempty"`
}
type ResolvedSharedFolder struct {
ID string
Name string
RootPath string
VolumeGUID string
Writable bool
Generation uint64
}
var folderIDPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9_-]{0,47}$`)
func NormalizeFolderID(raw string) (string, bool) {
id := strings.ToLower(raw)
return id, folderIDPattern.MatchString(id)
}
func SanitizeFolderName(raw string) string {
name := strings.TrimLeftFunc(strings.Map(func(r rune) rune {
if unicode.IsControl(r) || strings.ContainsRune(`|/\:`, r) {
return -1
}
return r
}, raw), func(r rune) bool { return r == '.' || unicode.IsSpace(r) })
name = strings.TrimSpace(name)
lower := strings.ToLower(name)
if lower == "reimsshare" || lower == "reimssharedfolders" ||
(len(lower) == len("windows a") && strings.HasPrefix(lower, "windows ") &&
lower[len("windows ")] >= 'a' && lower[len("windows ")] <= 'z') {
return ""
}
return name
}
func (s *Server) handleFolders(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
ids := make([]string, 0, len(vm.resolvedFolders))
for id := range vm.resolvedFolders {
ids = append(ids, id)
}
slices.Sort(ids)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
for _, id := range ids {
folder := vm.resolvedFolders[id]
mode := "ro"
if folder.Writable {
mode = "rw"
}
fmt.Fprintf(w, "%s|%s|%d|%s\n", id, mode, folder.Generation, folder.Name)
}
}
func (s *Server) handleFolderWebDAV(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
w.Header().Set("WWW-Authenticate", `Basic realm="ReimsSharedFolders"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
vmPart, rest, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/dav-folders/"), "/")
if vmPart != vm.name {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
id, _, _ := strings.Cut(rest, "/")
folder, ok := vm.resolvedFolders[id]
if !ok {
http.Error(w, "folder not shared", http.StatusForbidden)
return
}
if !allowPROPFINDDepth(w, r) {
return
}
if !folder.Writable && !allowReadOnlyDAV(w, r) {
return
}
prefix := "/dav-folders/" + vm.name + "/" + id
var src, dst string
if r.Method == "MOVE" || r.Method == "COPY" {
var status int
src, dst, status = davTransferPaths(r, prefix, true)
if status != http.StatusOK {
http.Error(w, http.StatusText(status), status)
return
}
}
handler, err := s.folderDAVHandler(vm, folder, prefix)
if err != nil {
http.Error(w, "folder unavailable", http.StatusNotFound)
return
}
if dst != "" {
if err := handler.FileSystem.(*rootWebDAVFS).checkTransfer(src, dst); err != nil {
if errors.Is(err, os.ErrNotExist) {
http.NotFound(w, r)
return
}
http.Error(w, "invalid transfer paths", http.StatusForbidden)
return
}
}
handler.ServeHTTP(w, r)
}
func (s *Server) folderDAVHandler(vm *registeredVM, folder ResolvedSharedFolder, prefix string) (*webdav.Handler, error) {
current := func() *registeredVM {
live := s.vms[vm.key]
if live == nil || live.token != vm.token || live.resolvedFolders[folder.ID] != folder {
return nil
}
return live
}
verify := func() error {
s.mu.RLock()
defer s.mu.RUnlock()
if current() == nil {
return os.ErrPermission
}
return nil
}
verifyRoot := func(root *os.Root) error {
s.mu.RLock()
live := current()
if live == nil {
s.mu.RUnlock()
return os.ErrPermission
}
verifyRoot := live.verifyFolderRoot
s.mu.RUnlock()
if verifyRoot != nil {
return verifyRoot(root, folder)
}
return checkSharedRootPath(root, folder.RootPath)
}
key := vm.key + "/folders/" + folder.ID
s.mu.RLock()
entry := s.davCache[key]
s.mu.RUnlock()
if entry.generation == folder.Generation {
return entry.handler, nil
}
fsys := &rootWebDAVFS{
root: sharedRoot{path: folder.RootPath}, readOnly: !folder.Writable,
verify: verify, verifyRoot: verifyRoot, accessMu: &s.folderAccessMu,
}
if err := fsys.probe(); err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
if current() == nil {
return nil, os.ErrPermission
}
if entry := s.davCache[key]; entry.generation == folder.Generation {
return entry.handler, nil
}
handler := &webdav.Handler{Prefix: prefix, FileSystem: fsys, LockSystem: webdav.NewMemLS()}
s.davCache[key] = davCacheEntry{
handler: handler, root: folder.RootPath, readOnly: !folder.Writable, generation: folder.Generation,
}
return handler, nil
}