fix(guesttools): confine sync to the current shared folders

This commit is contained in:
YXC0915 committed 2026-12-01 08:06:43 +08:00
1 parent f96d78be14
commit 552d6e4cad
6 files changed
+223 -58

No files matched your search

+110 -54
View File
@@ -1,6 +1,7 @@
package guesttools
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
@@ -8,6 +9,7 @@ import (
"io/fs"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strconv"
@@ -20,8 +22,38 @@ const (
syncDigestHeader = "X-Reims-File-SHA256"
)
func syncFileScope(token, root string) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root)))
func syncFileScope(token string, root *os.Root) (string, error) {
// A replacement directory at the same path must start fresh sync history.
dir, err := root.Open(".")
if err != nil {
return "", err
}
defer dir.Close()
id, err := sharedDirectoryID(dir)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root.Name()+"\n"+id))), nil
}
func openSharedRoot(dir string) (*os.Root, error) {
info, err := os.Lstat(dir)
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, fs.ErrInvalid
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, err
}
opened, err := root.Stat(".")
if err != nil || !os.SameFile(info, opened) {
_ = root.Close()
return nil, errors.New("shared directory changed")
}
return root, nil
}
func syncFileTag(info fs.FileInfo) string {
@@ -73,27 +105,38 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
}
return
}
root, err := filepath.Abs(vm.sharedDir)
dir, err := filepath.Abs(vm.sharedDir)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
return
}
if !versioned {
if err := os.MkdirAll(root, 0o755); err != nil {
if err := os.MkdirAll(dir, 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
root, err := openSharedRoot(dir)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
defer root.Close()
var scope string
if versioned {
scope, err = syncFileScope(vm.token, root)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
}
type entry struct {
name string
info fs.FileInfo
}
var files []entry
err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if p == root {
if versioned && err == nil && !d.IsDir() {
return fs.ErrInvalid
}
err = fs.WalkDir(root.FS(), ".", func(name string, d fs.DirEntry, err error) error {
if name == "." {
return err
}
if err != nil {
@@ -105,11 +148,6 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
}
return nil
}
rel, err := filepath.Rel(root, p)
if err != nil {
return nil
}
name := filepath.ToSlash(rel)
if strings.Count(name, "/")+1 > MaxSharedDepth {
if d.IsDir() {
return filepath.SkipDir
@@ -134,7 +172,7 @@ func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set(syncScopeHeader, syncFileScope(vm.token, root))
w.Header().Set(syncScopeHeader, scope)
}
sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name })
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
@@ -165,23 +203,49 @@ func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
return
}
scope := r.Header.Get(syncScopeHeader)
if scope != "" && (!validSyncFileName(rawName) || scope != syncFileScope(vm.token, dir)) {
http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed)
return
}
writing := r.Method == http.MethodPut || r.Method == http.MethodPost
switch r.Method {
case http.MethodHead, http.MethodDelete:
if scope == "" {
http.Error(w, "sync scope required", http.StatusPreconditionRequired)
return
}
fallthrough
case http.MethodGet:
s.readSharedFile(w, r, dir, name, scope != "")
case http.MethodPut, http.MethodPost:
s.writeSharedFile(w, r, filepath.Join(dir, filepath.FromSlash(name)), scope != "")
case http.MethodGet, http.MethodPut, http.MethodPost:
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if scope == "" && writing {
if err := os.MkdirAll(dir, 0o755); err != nil {
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
return
}
}
root, err := openSharedRoot(dir)
if err != nil {
if scope == "" && !writing && errors.Is(err, fs.ErrNotExist) {
http.NotFound(w, r)
} else {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
}
return
}
defer root.Close()
if scope != "" {
current, err := syncFileScope(vm.token, root)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
if !validSyncFileName(rawName) || scope != current {
http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed)
return
}
}
if writing {
s.writeSharedFile(w, r, root, name, scope != "")
} else {
s.readSharedFile(w, r, root, name, scope != "")
}
}
@@ -214,7 +278,7 @@ func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) {
return info, err
}
func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, name string, versioned bool) {
func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) {
deleting := r.Method == http.MethodDelete
expectedDigest := r.Header.Get(syncDigestHeader)
if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") {
@@ -222,19 +286,6 @@ func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, nam
return
}
root, err := os.OpenRoot(dir)
if err != nil {
switch {
case versioned:
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
case errors.Is(err, fs.ErrNotExist):
http.NotFound(w, r)
default:
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
}
return
}
defer root.Close()
info, err := statSharedFile(root, name)
switch {
case errors.Is(err, fs.ErrNotExist):
@@ -315,18 +366,19 @@ func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, nam
}
}
func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full string, versioned bool) {
dir := filepath.Dir(full)
if err := os.MkdirAll(dir, 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) {
dir := path.Dir(name)
if err := root.MkdirAll(dir, 0o755); err != nil {
http.Error(w, "upload directory unavailable", http.StatusInternalServerError)
return
}
tmp, err := os.CreateTemp(dir, ".reims-upload-*")
tmpName := path.Join(dir, ".reims-upload-"+rand.Text())
tmp, err := root.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
http.Error(w, "upload file unavailable", http.StatusInternalServerError)
return
}
defer os.Remove(tmp.Name())
defer root.Remove(tmpName)
h := sha256.New()
var dst io.Writer = tmp
if versioned {
@@ -344,30 +396,34 @@ func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, full st
}
if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 {
t := time.Unix(ts, 0)
_ = os.Chtimes(tmp.Name(), t, t)
_ = root.Chtimes(tmpName, t, t)
}
s.fileMu.Lock()
defer s.fileMu.Unlock()
info, err := statSharedFile(root, name)
if errors.Is(err, fs.ErrInvalid) {
http.Error(w, "path is not a regular file", http.StatusConflict)
return
}
if err != nil && !errors.Is(err, fs.ErrNotExist) {
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
}
var uploadedTag string
if versioned {
info, err := os.Lstat(full)
if err != nil && !errors.Is(err, fs.ErrNotExist) {
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
}
if !matchSyncFile(r, info) {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
uploaded, err := os.Stat(tmp.Name())
uploaded, err := root.Stat(tmpName)
if err != nil {
http.Error(w, "uploaded file unavailable", http.StatusInternalServerError)
return
}
uploadedTag = syncFileTag(uploaded)
}
if err := os.Rename(tmp.Name(), full); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
if err := root.Rename(tmpName, name); err != nil {
http.Error(w, "publish uploaded file failed", http.StatusInternalServerError)
return
}
if versioned {
+9 -3
View File
@@ -1,7 +1,7 @@
# Keep confirmed pairs outside the share, scoped to the VM and host directory.
# Keep confirmed pairs scoped to the current shared directories on both sides.
sync_files() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
[ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] || return 0
sync_guest_root=$(sync_guest_root_id) || return 0
sync_remote="$TMP_DIR/sync-remote.tsv"
sync_local="$TMP_DIR/sync-local.tsv"
@@ -16,7 +16,7 @@ sync_files() {
case "$sync_scope" in
"") ;;
*[!0-9a-f]*) return 0 ;;
*) sync_state="$APP_DIR/file-sync-$sync_scope.tsv" ;;
*) sync_state="$APP_DIR/file-sync-$sync_scope-$sync_guest_root.tsv" ;;
esac
sync_previous="$sync_state"
[ -f "$sync_state" ] || sync_previous=/dev/null
@@ -106,7 +106,13 @@ sync_header() {
awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers"
}
sync_guest_root_id() {
[ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] &&
stat -f '%d-%i-%B' "$SHARE_SYNC" 2>/dev/null
}
sync_guest_revision() {
[ "$(sync_guest_root_id)" = "$sync_guest_root" ] || return 1
sync_check=$1
while [ "$sync_check" != "$SHARE_SYNC" ]; do
[ ! -L "$sync_check" ] || return 1
@@ -0,0 +1,12 @@
//go:build !windows && !unix
package guesttools
import (
"errors"
"os"
)
func sharedDirectoryID(*os.File) (string, error) {
return "", errors.ErrUnsupported
}
@@ -0,0 +1,18 @@
//go:build unix
package guesttools
import (
"fmt"
"os"
"syscall"
)
func sharedDirectoryID(dir *os.File) (string, error) {
info, err := dir.Stat()
if err != nil {
return "", err
}
stat := info.Sys().(*syscall.Stat_t)
return fmt.Sprintf("%x:%x", stat.Dev, stat.Ino), nil
}
@@ -0,0 +1,16 @@
package guesttools
import (
"fmt"
"os"
"syscall"
)
func sharedDirectoryID(dir *os.File) (string, error) {
var info syscall.ByHandleFileInformation
if err := syscall.GetFileInformationByHandle(syscall.Handle(dir.Fd()), &info); err != nil {
return "", err
}
return fmt.Sprintf("%x:%08x%08x:%x", info.VolumeSerialNumber, info.FileIndexHigh,
info.FileIndexLow, info.CreationTime.Nanoseconds()), nil
}
+58 -1
View File
@@ -3,11 +3,15 @@ package guesttools
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
@@ -93,9 +97,62 @@ func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) {
conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got))))
request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent)
request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound)
if err := os.Remove(shared); err != nil {
if err := os.Rename(shared, filepath.Join(root, "old-share")); err != nil {
t.Fatal(err)
}
request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable)
request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable)
srv.RegisterVM(cfg)
list, _ = request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
newScope := list.Get(syncScopeHeader)
if newScope == "" || newScope == scope {
t.Fatalf("recreated share must have a new scope: %q", newScope)
}
request(http.MethodHead, fileURL, "", conditions, http.StatusPreconditionFailed)
request(http.MethodPut, fileURL, "stale upload", conditions, http.StatusPreconditionFailed)
conditions = http.Header{syncScopeHeader: {newScope}}
request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound)
request(http.MethodPut, "/v1/file?path=nested/file.txt", contents, conditions, http.StatusOK)
_, got = request(http.MethodGet, "/v1/file?path=nested/file.txt", "", conditions, http.StatusOK)
if got != contents {
t.Fatalf("nested file contents: %q", got)
}
}
func TestFileSyncConfinesUploadToShare(t *testing.T) {
shared, outside := t.TempDir(), t.TempDir()
link := filepath.Join(shared, "linked")
if err := os.Symlink(outside, link); err != nil {
if runtime.GOOS != "windows" {
t.Skipf("directory symlink unavailable: %v", err)
}
output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput()
if err != nil {
t.Fatalf("create test junction: %v: %s", err, output)
}
}
srv := NewTransportServer(&memClipboard{})
token := strings.Repeat("a", 64)
srv.RegisterVM(VMConfig{VMName: "sync-test", Token: token, SharedDir: shared})
list := httptest.NewRequest(http.MethodGet, "/v1/files?sync=1", nil)
list.Header.Set("Authorization", "Bearer "+token)
listed := httptest.NewRecorder()
srv.handleListFiles(listed, list)
scope := listed.Header().Get(syncScopeHeader)
if listed.Code != http.StatusOK || scope == "" {
t.Fatalf("listing failed: %d: %s", listed.Code, listed.Body)
}
for _, version := range []string{"", scope} {
req := httptest.NewRequest(http.MethodPut, "/v1/file?path=linked/upload.txt", strings.NewReader("test upload"))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set(syncScopeHeader, version)
res := httptest.NewRecorder()
srv.handleFile(res, req)
if res.Code < http.StatusBadRequest {
t.Fatalf("upload through an out-of-share link succeeded: %d", res.Code)
}
if _, err := os.Stat(filepath.Join(outside, "upload.txt")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("upload escaped share: %v", err)
}
}
}