From f96d78be14c542cfee866fc35805985108135ddf Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 07:37:44 +0800 Subject: [PATCH 1/3] fix(guesttools): propagate fallback sync deletions --- .gitattributes | 1 + frontend/src/components/VMPage.tsx | 4 +- frontend/wailsjs/go/models.ts | 2 + internal/app/stats_flow.go | 11 +- internal/guesttools/clipboard_agent_test.go | 8 +- internal/guesttools/file_sync.go | 378 ++++++++++++++++++++ internal/guesttools/file_sync.sh | 213 +++++++++++ internal/guesttools/file_sync_test.go | 101 ++++++ internal/guesttools/image.go | 73 +--- internal/guesttools/server.go | 209 +---------- 10 files changed, 723 insertions(+), 277 deletions(-) create mode 100644 internal/guesttools/file_sync.go create mode 100644 internal/guesttools/file_sync.sh create mode 100644 internal/guesttools/file_sync_test.go diff --git a/.gitattributes b/.gitattributes index 8083b67..3ab406d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ *.patch -text *.diff -text +internal/guesttools/file_sync.sh text eol=lf diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index e8b60ea..c14b3c5 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -853,7 +853,9 @@ export const VMPage: React.FC = ({ const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || '' const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false - const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3 + const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0 + const minimumAgentVersion = gtMountMode === 'sync' ? 7 : 3 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < minimumAgentVersion // Plugin switched off: show the state and hide controls that would only fail. const gtOff = !!detail.guest_tools_disabled diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 9883e88..c0d44a9 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -411,6 +411,7 @@ export namespace app { uptime_seconds: number; guest_tools_connected: boolean; guest_tools_mount_mode?: string; + guest_tools_agent_version?: number; guest_tools_sleep_guard: boolean; static createFrom(source: any = {}) { @@ -435,6 +436,7 @@ export namespace app { this.uptime_seconds = source["uptime_seconds"]; this.guest_tools_connected = source["guest_tools_connected"]; this.guest_tools_mount_mode = source["guest_tools_mount_mode"]; + this.guest_tools_agent_version = source["guest_tools_agent_version"]; this.guest_tools_sleep_guard = source["guest_tools_sleep_guard"]; } } diff --git a/internal/app/stats_flow.go b/internal/app/stats_flow.go index 66be5f5..4192d6a 100644 --- a/internal/app/stats_flow.go +++ b/internal/app/stats_flow.go @@ -27,9 +27,11 @@ type VMStats struct { DiskBackingBroken bool `json:"disk_backing_broken,omitempty"` DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"` UptimeSeconds int64 `json:"uptime_seconds"` - GuestToolsConnected bool `json:"guest_tools_connected"` - GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` - GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` + + GuestToolsConnected bool `json:"guest_tools_connected"` + GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"` + GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"` + GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"` } func resolveVMDiskPath(d reims.VMDetail) string { @@ -53,7 +55,7 @@ func resolveVMDiskPath(d reims.VMDetail) string { } // GetVMStats samples QEMU CPU/memory usage (when running), disk actual vs -// virtual capacity, and live Guest Tools 2.0 connection state. +// virtual capacity, and live Guest Tools status. func (a *App) GetVMStats(name string) (VMStats, error) { stats := VMStats{Name: name} c, err := a.client() @@ -114,6 +116,7 @@ func (a *App) GetVMStats(name string) (VMStats, error) { st := srv.Status(name, 15*time.Second) stats.GuestToolsConnected = st.Connected stats.GuestToolsMountMode = st.MountMode + stats.GuestToolsAgentVersion = st.AgentVersion stats.GuestToolsSleepGuard = st.SleepActive } return stats, nil diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 666e80c..cf5fd8f 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -4,6 +4,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "strings" "testing" ) @@ -19,8 +20,11 @@ func TestGuestAgentClipboardScript(t *testing.T) { agent := string(GuestAgentScript()) start := strings.Index(agent, "read_local_clipboard() {") end := strings.Index(agent, "sync_files() {") - if start < 0 || end <= start || !strings.Contains(agent, "agent_version\\\":6") { - t.Fatal("missing generated clipboard code or agent version 6") + if start < 0 || end <= start { + t.Fatal("missing generated clipboard code") + } + if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)\}`).MatchString(agent) { + t.Fatal("clipboard sync requires agent version 6 or newer") } if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) { t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u") diff --git a/internal/guesttools/file_sync.go b/internal/guesttools/file_sync.go new file mode 100644 index 0000000..76ba4d8 --- /dev/null +++ b/internal/guesttools/file_sync.go @@ -0,0 +1,378 @@ +package guesttools + +import ( + "crypto/sha256" + "errors" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" +) + +const ( + syncScopeHeader = "X-Reims-Sync-Scope" + syncDigestHeader = "X-Reims-File-SHA256" +) + +func syncFileScope(token, root string) string { + return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root))) +} + +func syncFileTag(info fs.FileInfo) string { + return fmt.Sprintf("\"%d-%d\"", info.ModTime().UnixNano(), info.Size()) +} + +func isIgnoredSharedName(name string) bool { + return name == "" || strings.HasPrefix(name, ".") +} + +func validSyncFileName(name string) bool { + return strings.TrimSpace(name) == name && !strings.ContainsAny(name, "\t\r\n") +} + +// sharedFilePath returns the one relative path used by both the legacy copy +// endpoints and the versioned sync operations. +func sharedFilePath(name string) (string, error) { + name = strings.TrimSpace(name) + parts := strings.FieldsFunc(name, func(r rune) bool { return r == '/' }) + if len(parts) == 0 || len(parts) > MaxSharedDepth || strings.HasPrefix(name, "/") { + return "", errors.New("invalid relative path") + } + for _, part := range parts { + if isIgnoredSharedName(part) || strings.ContainsAny(part, "\x00:\\<>|\"?*") { + return "", errors.New("invalid path segment") + } + } + rel := strings.Join(parts, "/") + if !filepath.IsLocal(filepath.FromSlash(rel)) { + return "", errors.New("invalid relative path") + } + return rel, nil +} + +func (s *Server) handleListFiles(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 + } + versioned := r.URL.Query().Get("sync") == "1" + if vm.sharedDir == "" { + if versioned { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + } + return + } + root, 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 { + http.Error(w, err.Error(), http.StatusInternalServerError) + 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 + } + return err + } + if err != nil { + return nil + } + if isIgnoredSharedName(d.Name()) || d.Type()&os.ModeSymlink != 0 { + if d.IsDir() { + return filepath.SkipDir + } + 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 + } + return nil + } + if d.IsDir() || (versioned && !validSyncFileName(name)) { + return nil + } + info, err := d.Info() + if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes { + return nil + } + if len(files) == MaxSharedFiles { + return fs.SkipAll + } + files = append(files, entry{name, info}) + return nil + }) + if versioned { + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) + return + } + w.Header().Set(syncScopeHeader, syncFileScope(vm.token, root)) + } + 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") + for _, file := range files { + _, _ = fmt.Fprintf(w, "%d\t%d\t", file.info.ModTime().Unix(), file.info.Size()) + if versioned { + _, _ = fmt.Fprintf(w, "%s\t", syncFileTag(file.info)) + } + _, _ = fmt.Fprintln(w, file.name) + } +} + +func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + rawName := r.URL.Query().Get("path") + name, err := sharedFilePath(rawName) + if err != nil || vm.sharedDir == "" { + http.Error(w, "invalid shared file path", http.StatusBadRequest) + return + } + dir, err := filepath.Abs(vm.sharedDir) + if err != nil { + http.Error(w, "shared directory unavailable", http.StatusInternalServerError) + 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 + } + 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 != "") + default: + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + } +} + +func matchSyncFile(r *http.Request, info fs.FileInfo) bool { + if tag := r.Header.Get("If-Match"); tag != "" { + return info != nil && info.Mode().IsRegular() && syncFileTag(info) == tag + } + return r.Header.Get("If-None-Match") != "*" || info == nil +} + +// A path replaced by a symlink or directory is a conflict rather than a +// missing file. Missing files are the only ones that propagate a deletion. +func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) { + for i, ch := range name { + if ch != '/' { + continue + } + info, err := root.Lstat(name[:i]) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, fs.ErrInvalid + } + } + info, err := root.Lstat(name) + if err == nil && !info.Mode().IsRegular() { + return nil, fs.ErrInvalid + } + return info, err +} + +func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, dir, name string, versioned bool) { + deleting := r.Method == http.MethodDelete + expectedDigest := r.Header.Get(syncDigestHeader) + if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") { + http.Error(w, "file revision required", http.StatusPreconditionRequired) + 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): + http.NotFound(w, r) + return + case errors.Is(err, fs.ErrInvalid): + status := http.StatusBadRequest + if versioned { + status = http.StatusConflict + } + http.Error(w, "path is not a regular file", status) + return + case err != nil: + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + case versioned && !matchSyncFile(r, info): + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + + tag := syncFileTag(info) + if !deleting { + w.Header().Set("ETag", tag) + } + head := r.Method == http.MethodHead + if head && r.URL.Query().Get("sha256") != "1" { + return + } + if (head || deleting) && info.Size() > MaxUploadBytes { + http.Error(w, "file exceeds sync size limit", http.StatusRequestEntityTooLarge) + return + } + file, err := root.Open(name) + if err != nil { + http.Error(w, "file unavailable", http.StatusInternalServerError) + return + } + opened, err := file.Stat() + if err != nil || !opened.Mode().IsRegular() || syncFileTag(opened) != tag { + _ = file.Close() + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + if r.Method == http.MethodGet { + defer file.Close() + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10)) + w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) + _, _ = io.Copy(w, file) + return + } + + h := sha256.New() + n, err := io.Copy(h, io.LimitReader(file, info.Size()+1)) + _ = file.Close() + if err != nil || n != info.Size() { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + digest := fmt.Sprintf("%x", h.Sum(nil)) + if head { + w.Header().Set(syncDigestHeader, digest) + return + } + s.fileMu.Lock() + defer s.fileMu.Unlock() + current, err := statSharedFile(root, name) + if digest != expectedDigest || err != nil || !os.SameFile(opened, current) || !matchSyncFile(r, current) { + http.Error(w, "file changed", http.StatusPreconditionFailed) + return + } + if r.Context().Err() == nil { + if err := root.Remove(name); err != nil { + http.Error(w, "file deletion failed", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusNoContent) + } +} + +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) + return + } + tmp, err := os.CreateTemp(dir, ".reims-upload-*") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer os.Remove(tmp.Name()) + h := sha256.New() + var dst io.Writer = tmp + if versioned { + dst = io.MultiWriter(tmp, h) + } + n, copyErr := io.Copy(dst, io.LimitReader(r.Body, MaxUploadBytes+1)) + closeErr := tmp.Close() + switch { + case n > MaxUploadBytes: + http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge) + return + case copyErr != nil || closeErr != nil: + http.Error(w, "write failed", http.StatusInternalServerError) + return + } + 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) + } + s.fileMu.Lock() + defer s.fileMu.Unlock() + 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()) + 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) + return + } + if versioned { + w.Header().Set("ETag", uploadedTag) + w.Header().Set(syncDigestHeader, fmt.Sprintf("%x", h.Sum(nil))) + } + w.WriteHeader(http.StatusOK) +} diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh new file mode 100644 index 0000000..f6ecf65 --- /dev/null +++ b/internal/guesttools/file_sync.sh @@ -0,0 +1,213 @@ +# Keep confirmed pairs outside the share, scoped to the VM and host directory. +sync_files() { + [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 + [ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] || return 0 + + sync_remote="$TMP_DIR/sync-remote.tsv" + sync_local="$TMP_DIR/sync-local.tsv" + sync_headers="$TMP_DIR/sync-headers" + sync_plan="$TMP_DIR/sync-plan.tsv" + sync_delta="$TMP_DIR/sync-delta.tsv" + sync_state=/dev/null + if ! sync_request -fsS -m 5 -D "$sync_headers" -o "$sync_remote" "$REIMS_HOST_URL/v1/files?sync=1" 2>/dev/null; then + return 0 + fi + sync_scope=$(sync_header X-Reims-Sync-Scope) + case "$sync_scope" in + "") ;; + *[!0-9a-f]*) return 0 ;; + *) sync_state="$APP_DIR/file-sync-$sync_scope.tsv" ;; + esac + sync_previous="$sync_state" + [ -f "$sync_state" ] || sync_previous=/dev/null + + if ! find "$SHARE_SYNC"/. -name '.*' ! -name . -prune -o -type f -exec /bin/sh -c ' + root=$1 + tab=$2 + shift 2 + newline=$(printf "\nx") + newline=${newline%x} + cr=$(printf "\r") + for file do + rel=${file#"$root"/./} + case "$rel" in *"$tab"*|*"$newline"*|*"$cr"*) continue ;; esac + row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || exit 1 + printf "%s\t%s\n" "$row" "$rel" + done + ' sh "$SHARE_SYNC" "$TAB" {} + > "$sync_local" 2>/dev/null; then + return 0 + fi + + # A missing path is a deletion only after a confirmed pair has existed. + # If the remaining copy changed, preserve it using the usual copy rules. + awk -F '\t' -v extended="$sync_scope" ' + BEGIN { OFS = FS } + FILENAME == ARGV[1] { + previousLocal[$4] = $1; previousRemote[$4] = $2; state[$4] = $3; paths[$4] = 1 + } + FILENAME == ARGV[2] { + p = extended == "" ? $3 : $4 + if (p != "") { + remoteTime[p] = $1; remoteSize[p] = $2; remote[p] = extended == "" ? "-" : $3; paths[p] = 1 + } + } + FILENAME == ARGV[3] && $4 != "" { + localTime[$4] = $1; localSize[$4] = $2; local[$4] = $3; paths[$4] = 1 + } + END { + for (p in paths) { + l = p in local; r = p in remote + paired = state[p] != "" && state[p] != "different" + op = "" + if (l && r) { + if (remoteTime[p] + 0 > localTime[p] + 2) op = "download" + else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload" + else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] && + (local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify" + } else if (r) { + op = paired && remote[p] == previousRemote[p] ? "delete-host" : "download" + } else if (l) { + if (paired && local[p] == previousLocal[p]) op = "delete-guest" + else if (localSize[p] <= 268435456) op = "upload" + } else { + op = "forget" + } + if (op != "") { + localRevision = l ? local[p] : "-" + remoteRevision = r ? remote[p] : "-" + localMtime = l ? localTime[p] : "-" + digest = state[p] != "" ? state[p] : "-" + print op, localRevision, remoteRevision, localMtime, digest, p + } + } + } + ' "$sync_previous" "$sync_remote" "$sync_local" > "$sync_plan" || return 0 + + : > "$sync_delta" || return 0 + sync_verify_left=8 + while IFS="$TAB" read -r sync_op sync_guest_rev sync_host_rev sync_guest_time sync_digest sync_rel; do + sync_apply_file + done < "$sync_plan" + if [ "$sync_state" != /dev/null ]; then + awk -F '\t' ' + $1 == "-" { delete rows[$4]; next } + { rows[$4] = $0 } + END { for (p in rows) print rows[p] } + ' "$sync_previous" "$sync_delta" > "$TMP_DIR/sync-state.next" && + mv -f "$TMP_DIR/sync-state.next" "$sync_state" + fi +} + +sync_request() { + curl -H "Authorization: Bearer $REIMS_TOKEN" "$@" +} + +sync_header() { + awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers" +} + +sync_guest_revision() { + sync_check=$1 + while [ "$sync_check" != "$SHARE_SYNC" ]; do + [ ! -L "$sync_check" ] || return 1 + sync_check=${sync_check%/*} + done + if [ -f "$1" ]; then + stat -f '%Fm:%Fc:%i:%z' "$1" 2>/dev/null + elif [ ! -e "$1" ]; then + printf '%s\n' '-' + fi +} + +sync_record() { + [ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ] || return 0 + printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$sync_rel" >> "$sync_delta" +} + +sync_apply_file() { + case "/$sync_rel/" in //*|*/../*|*/./*|*//*) return ;; esac + sync_target="$SHARE_SYNC/$sync_rel" + [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0 + + sync_url="$REIMS_HOST_URL/v1/file?path=$(urlencode "$sync_rel")" + if [ -n "$sync_scope" ]; then + set -- -H "X-Reims-Sync-Scope: $sync_scope" + if [ "$sync_host_rev" != - ]; then + set -- "$@" -H "If-Match: $sync_host_rev" + fi + else + set -- + fi + + case "$sync_op" in + delete-host) + sync_status=$(sync_request -sS -m 60 "$@" -H "X-Reims-File-SHA256: $sync_digest" -X DELETE \ + -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0 + case "$sync_status" in + 204) sync_record - - -; return ;; + 412) sync_op=download ;; + *) return 0 ;; + esac + ;; + delete-guest|forget) + # A partial host listing cannot confirm that a file was deleted. + sync_status=$(sync_request -sS -m 10 "$@" -I -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0 + [ "$sync_status" = 404 ] || return 0 + if [ "$sync_op" = "forget" ]; then + sync_record - - - + return + fi + sync_actual=$(hash_file "$sync_target") + [ -n "$sync_actual" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0 + if [ "$sync_actual" = "$sync_digest" ]; then + rm "$sync_target" && sync_record - - - + return + fi + sync_op=upload + ;; + esac + + case "$sync_op" in + download) + sync_part="$TMP_DIR/sync-download.part" + if sync_request -fsS -m 60 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then + sync_download_digest="" + if [ -n "$sync_scope" ]; then + sync_download_digest=$(hash_file "$sync_part") + fi + if sync_stamp=$(TZ=UTC date -r "$(sync_header X-File-Mtime)" '+%Y%m%d%H%M.%S' 2>/dev/null); then + TZ=UTC touch -t "$sync_stamp" "$sync_part" 2>/dev/null || true + fi + if [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] && + mkdir -p "$(dirname "$sync_target")" && mv -f "$sync_part" "$sync_target"; then + sync_record "$(sync_guest_revision "$sync_target")" "$(sync_header ETag)" "$sync_download_digest" + fi + fi + rm -f "$sync_part" + ;; + upload) + if [ -n "$sync_scope" ] && [ "$sync_host_rev" = - ]; then + set -- "$@" -H 'If-None-Match: *' + fi + if sync_request -fsS -m 60 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \ + "$sync_url&mtime=$sync_guest_time" 2>/dev/null && + [ -n "$sync_scope" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then + sync_record "$sync_guest_rev" "$(sync_header ETag)" "$(sync_header X-Reims-File-SHA256)" + fi + ;; + verify) + # Bound initial migration work when adopting pre-existing copies. + [ "$sync_verify_left" -gt 0 ] || return 0 + sync_verify_left=$((sync_verify_left - 1)) + if sync_request -fsS -m 15 "$@" -I -D "$sync_headers" -o /dev/null "$sync_url&sha256=1" 2>/dev/null; then + sync_host_hash=$(sync_header X-Reims-File-SHA256) + sync_guest_hash=$(hash_file "$sync_target") + if [ -n "$sync_host_hash" ] && [ -n "$sync_guest_hash" ] && + [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then + [ "$sync_host_hash" = "$sync_guest_hash" ] || sync_host_hash=different + sync_record "$sync_guest_rev" "$sync_host_rev" "$sync_host_hash" + fi + fi + ;; + esac +} diff --git a/internal/guesttools/file_sync_test.go b/internal/guesttools/file_sync_test.go new file mode 100644 index 0000000..99b79e1 --- /dev/null +++ b/internal/guesttools/file_sync_test.go @@ -0,0 +1,101 @@ +package guesttools + +import ( + "context" + "crypto/sha256" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) { + root := t.TempDir() + shared := filepath.Join(root, "share") + srv := NewTransportServer(&memClipboard{}) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + cfg, err := LoadOrCreateVMConfig(root, "sync-test", shared, port) + if err != nil { + t.Fatal(err) + } + srv.RegisterVM(cfg) + + request := func(method, path, body string, headers http.Header, want int) (http.Header, string) { + t.Helper() + req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + if headers != nil { + req.Header = headers.Clone() + } + req.Header.Set("Authorization", "Bearer "+cfg.Token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + b, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != want { + t.Fatalf("%s %s: status=%d, want=%d, body=%q, read error=%v", method, path, resp.StatusCode, want, b, err) + } + return resp.Header, string(b) + } + + const fileURL = "/v1/file?path=entry.txt" + const contents = "original" + digest := fmt.Sprintf("%x", sha256.Sum256([]byte(contents))) + list, _ := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + scope := list.Get(syncScopeHeader) + if scope == "" { + t.Fatal("missing sync scope") + } + conditions := make(http.Header) + conditions.Set(syncScopeHeader, scope) + conditions.Set("If-None-Match", "*") + created, _ := request(http.MethodPut, fileURL+"&mtime=1700000000", contents, conditions, http.StatusOK) + tag := created.Get("ETag") + if tag == "" || created.Get(syncDigestHeader) != digest { + t.Fatalf("upload revision or digest missing: %v", created) + } + _, legacyList := request(http.MethodGet, "/v1/files", "", nil, http.StatusOK) + _, versionedList := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK) + if legacyList != "1700000000\t8\tentry.txt\n" || + versionedList != "1700000000\t8\t"+tag+"\tentry.txt\n" { + t.Fatalf("unexpected file listings: legacy=%q, versioned=%q", legacyList, versionedList) + } + + request(http.MethodPut, fileURL, "overwritten", conditions, http.StatusPreconditionFailed) + conditions.Del("If-None-Match") + conditions.Set("If-Match", tag) + probed, _ := request(http.MethodHead, fileURL+"&sha256=1", "", conditions, http.StatusOK) + if probed.Get(syncDigestHeader) != digest { + t.Fatalf("unexpected digest: %v", probed) + } + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionRequired) + conditions.Set(syncDigestHeader, digest) + conditions.Set("If-Match", "\"stale-revision\"") + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed) + conditions.Set("If-Match", tag) + request(http.MethodPut, fileURL+"&mtime=1700000000", "modified", nil, http.StatusOK) + request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed) + _, got := request(http.MethodGet, fileURL, "", nil, http.StatusOK) + if got != "modified" { + t.Fatalf("modified copy was lost: %q", got) + } + 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 { + t.Fatal(err) + } + request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable) + request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable) +} diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 2cc945d..0a16051 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -2,6 +2,7 @@ package guesttools import ( "bytes" + _ "embed" "fmt" "io" "os" @@ -15,8 +16,11 @@ const ( InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command" ) +//go:embed file_sync.sh +var guestFileSync string + // BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS") -// containing the per-VM Bearer token config, Guest Tools 4 POSIX agent script +// containing the per-VM Bearer token config, Guest Tools POSIX agent script // (text + PNG image clipboard with long-poll, WebDAV live mount with fallback // sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts. func BuildToolsDiskImage(outPath string, cfg VMConfig) error { @@ -65,7 +69,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) } -// GuestAgentScript returns the Guest Tools 4 stock-macOS POSIX shell daemon +// GuestAgentScript returns the Guest Tools stock-macOS POSIX shell daemon // (no Xcode or Python required): // - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling // - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback @@ -73,7 +77,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { // - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required) func GuestAgentScript() []byte { return []byte(`#!/bin/sh -# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep. +# Reims Guest Tools: clipboard, WebDAV share, read-only Windows drives, prevent-sleep. set -u # Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified @@ -309,7 +313,7 @@ report_status() { curl -fsS -m 3 -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":6}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":7}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -484,62 +488,7 @@ sync_clipboard() { esac } -sync_files() { - [ "$mount_mode" = "webdav" ] && return 0 - [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 - remote_list="$TMP_DIR/remote_files.tsv" - if ! curl -fsS -m 5 \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then - return 0 - fi - - # 1. Host -> Guest (download new or strictly newer files) - while IFS="$TAB" read -r rmtime rsize rrel; do - [ -n "$rrel" ] || continue - local_path="$SHARE_SYNC/$rrel" - need_dl=0 - if [ ! -f "$local_path" ]; then - need_dl=1 - else - lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0) - if [ "$rmtime" -gt $((lmtime + 2)) ]; then - need_dl=1 - fi - fi - if [ "$need_dl" -eq 1 ]; then - mkdir -p "$(dirname "$local_path")" - enc=$(urlencode "$rrel") - dl_tmp="$TMP_DIR/dl.part" - if curl -fsS -m 60 \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - "$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then - mv -f "$dl_tmp" "$local_path" - touch -d "@$rmtime" "$local_path" 2>/dev/null || true - else - rm -f "$dl_tmp" - fi - fi - done <"$remote_list" - - # 2. Guest -> Host (upload new or strictly newer files) - find "$SHARE_SYNC" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do - rel=${fpath#"$SHARE_SYNC/"} - [ -n "$rel" ] || continue - lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0) - lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0) - [ "$lsize" -le 268435456 ] || continue - rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list") - [ -n "$rmtime" ] || rmtime=0 - if [ "$lmtime" -gt $((rmtime + 2)) ]; then - enc=$(urlencode "$rel") - curl -fsS -m 60 -X PUT \ - -H "Authorization: Bearer $REIMS_TOKEN" \ - --data-binary "@$fpath" \ - "$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true - fi - done -} +` + guestFileSync + ` text_input_loop() { hdr="$TMP_DIR/txt_hdr" @@ -668,12 +617,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST # Verify host bridge connectivity immediately. . "$APP_DIR/config" if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then - echo "Reims Guest Tools 4 installed and connected!" + echo "Reims Guest Tools installed and connected!" echo "Clipboard: UTF-8 text + PNG screenshots (two-way)" echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)" echo "Prevent-sleep: controlled live from Reims-Go host UI" else - echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." + echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." fi `) } diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 0d62b2f..bb5aacb 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -11,13 +11,10 @@ import ( "errors" "fmt" "io" - "io/fs" "net" "net/http" "os" - "path" "path/filepath" - "sort" "strconv" "strings" "sync" @@ -199,6 +196,7 @@ type registeredVM struct { // (reachable from QEMU SLIRP guests as http://10.0.2.2:). type Server struct { mu sync.RWMutex + fileMu sync.Mutex clipWriteMu sync.Mutex clip Clipboard vms map[string]*registeredVM // keyed by VM name @@ -1163,208 +1161,3 @@ func (s *Server) handleHostText(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusAccepted) } - -func isIgnoredSharedName(name string) bool { - return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._") -} - -// resolveSharedPath validates a relative slash path and ensures the resulting -// path stays strictly inside rootDir (no .., absolute paths, drive letters, or -// symlink escapes). -func resolveSharedPath(rootDir, rel string) (string, error) { - if rootDir == "" { - return "", errors.New("shared directory not configured") - } - if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) { - return "", errors.New("invalid path") - } - trimmed := strings.TrimSpace(rel) - if trimmed == "" || strings.HasPrefix(trimmed, "/") { - return "", errors.New("invalid relative path") - } - for _, rawSeg := range strings.Split(trimmed, "/") { - if rawSeg == ".." || rawSeg == "." { - return "", errors.New("path traversal not allowed") - } - } - clean := path.Clean("/" + trimmed) - clean = strings.TrimPrefix(clean, "/") - if clean == "" || clean == "." || strings.HasPrefix(clean, "..") { - return "", errors.New("invalid relative path") - } - parts := strings.Split(clean, "/") - if len(parts) > MaxSharedDepth { - return "", errors.New("path too deep") - } - for _, seg := range parts { - if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) { - return "", errors.New("invalid path segment") - } - } - rootAbs, err := filepath.Abs(rootDir) - if err != nil { - return "", err - } - full := filepath.Join(append([]string{rootAbs}, parts...)...) - relBack, err := filepath.Rel(rootAbs, full) - if err != nil || relBack == "." || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) { - return "", errors.New("path escapes shared root") - } - return full, nil -} - -func (s *Server) handleListFiles(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 - } - if vm.sharedDir == "" { - w.WriteHeader(http.StatusOK) - return - } - if err := os.MkdirAll(vm.sharedDir, 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - rootAbs, err := filepath.Abs(vm.sharedDir) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - type entry struct { - mtime int64 - size int64 - rel string - } - var list []entry - _ = filepath.WalkDir(rootAbs, func(p string, d fs.DirEntry, err error) error { - if err != nil { - return nil - } - if p == rootAbs { - return nil - } - name := d.Name() - if isIgnoredSharedName(name) { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if d.Type()&os.ModeSymlink != 0 { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - rel, err := filepath.Rel(rootAbs, p) - if err != nil { - return nil - } - slash := filepath.ToSlash(rel) - if strings.Count(slash, "/")+1 > MaxSharedDepth { - if d.IsDir() { - return filepath.SkipDir - } - return nil - } - if d.IsDir() { - return nil - } - info, err := d.Info() - if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes { - return nil - } - if len(list) >= MaxSharedFiles { - return fs.SkipAll - } - list = append(list, entry{mtime: info.ModTime().Unix(), size: info.Size(), rel: slash}) - return nil - }) - sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel }) - w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8") - for _, e := range list { - _, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel) - } -} - -func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) { - vm := s.authenticate(r) - if vm == nil { - http.Error(w, "unauthorized", http.StatusUnauthorized) - return - } - rel := r.URL.Query().Get("path") - full, err := resolveSharedPath(vm.sharedDir, rel) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - switch r.Method { - case http.MethodGet: - info, err := os.Lstat(full) - if err != nil { - if os.IsNotExist(err) { - http.NotFound(w, r) - return - } - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - if !info.Mode().IsRegular() { - http.Error(w, "not a regular file", http.StatusBadRequest) - return - } - f, err := os.Open(full) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - defer f.Close() - w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10)) - w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10)) - w.Header().Set("Content-Type", "application/octet-stream") - _, _ = io.Copy(w, f) - case http.MethodPut, http.MethodPost: - if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - tmp, err := os.CreateTemp(filepath.Dir(full), ".reims-upload-*") - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - tmpName := tmp.Name() - n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1)) - closeErr := tmp.Close() - if copyErr != nil || closeErr != nil || n > MaxUploadBytes { - _ = os.Remove(tmpName) - if n > MaxUploadBytes { - http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge) - return - } - http.Error(w, "write failed", http.StatusInternalServerError) - return - } - if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" { - if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 { - t := time.Unix(ts, 0) - _ = os.Chtimes(tmpName, t, t) - } - } - if err := os.Rename(tmpName, full); err != nil { - _ = os.Remove(tmpName) - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - w.WriteHeader(http.StatusOK) - default: - http.Error(w, "method not allowed", http.StatusMethodNotAllowed) - } -} From 552d6e4cada0822749577053343b88296f42f41f Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:06:43 +0800 Subject: [PATCH 2/3] fix(guesttools): confine sync to the current shared folders --- internal/guesttools/file_sync.go | 164 ++++++++++++------ internal/guesttools/file_sync.sh | 12 +- .../guesttools/file_sync_identity_other.go | 12 ++ .../guesttools/file_sync_identity_unix.go | 18 ++ .../guesttools/file_sync_identity_windows.go | 16 ++ internal/guesttools/file_sync_test.go | 59 ++++++- 6 files changed, 223 insertions(+), 58 deletions(-) create mode 100644 internal/guesttools/file_sync_identity_other.go create mode 100644 internal/guesttools/file_sync_identity_unix.go create mode 100644 internal/guesttools/file_sync_identity_windows.go diff --git a/internal/guesttools/file_sync.go b/internal/guesttools/file_sync.go index 76ba4d8..ad6733d 100644 --- a/internal/guesttools/file_sync.go +++ b/internal/guesttools/file_sync.go @@ -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 { diff --git a/internal/guesttools/file_sync.sh b/internal/guesttools/file_sync.sh index f6ecf65..58397ca 100644 --- a/internal/guesttools/file_sync.sh +++ b/internal/guesttools/file_sync.sh @@ -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 diff --git a/internal/guesttools/file_sync_identity_other.go b/internal/guesttools/file_sync_identity_other.go new file mode 100644 index 0000000..4c0ec4e --- /dev/null +++ b/internal/guesttools/file_sync_identity_other.go @@ -0,0 +1,12 @@ +//go:build !windows && !unix + +package guesttools + +import ( + "errors" + "os" +) + +func sharedDirectoryID(*os.File) (string, error) { + return "", errors.ErrUnsupported +} diff --git a/internal/guesttools/file_sync_identity_unix.go b/internal/guesttools/file_sync_identity_unix.go new file mode 100644 index 0000000..fa2d0b5 --- /dev/null +++ b/internal/guesttools/file_sync_identity_unix.go @@ -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 +} diff --git a/internal/guesttools/file_sync_identity_windows.go b/internal/guesttools/file_sync_identity_windows.go new file mode 100644 index 0000000..5545b15 --- /dev/null +++ b/internal/guesttools/file_sync_identity_windows.go @@ -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 +} diff --git a/internal/guesttools/file_sync_test.go b/internal/guesttools/file_sync_test.go index 99b79e1..b6ba2a8 100644 --- a/internal/guesttools/file_sync_test.go +++ b/internal/guesttools/file_sync_test.go @@ -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) + } + } } From 790a42912e68d7c66583fd27a4edadad24031c47 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Tue, 1 Dec 2026 08:22:58 +0800 Subject: [PATCH 3/3] fix(installer): expand home paths from reims-ctl show --- internal/config/config.go | 16 ++++++++++++++ internal/driver/reims/reims.go | 5 +++-- internal/driver/reims/reims_test.go | 21 +++++++++++++++++++ internal/installguide/progress.go | 6 +++++- internal/installguide/session_windows_test.go | 15 +++++++++++++ 5 files changed, 60 insertions(+), 3 deletions(-) diff --git a/internal/config/config.go b/internal/config/config.go index 347ea29..fbaae72 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "runtime" + "strings" "github.com/Nwflower/reims-go/internal/i18n" ) @@ -53,6 +54,21 @@ func DefaultDataRoot() string { return filepath.Join(home, "reims-go-data") } +// ExpandHomePath resolves a leading ~ for the current user. +func ExpandHomePath(path string) string { + if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) { + return path + } + home, err := os.UserHomeDir() + if err != nil { + return path + } + if path == "~" { + return home + } + return filepath.Join(home, path[2:]) +} + // CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the // folder chosen at first launch (LocationPath), else DefaultDataRoot. func CurrentDataRoot() string { diff --git a/internal/driver/reims/reims.go b/internal/driver/reims/reims.go index 17dcc5d..4785cac 100644 --- a/internal/driver/reims/reims.go +++ b/internal/driver/reims/reims.go @@ -548,6 +548,7 @@ func parseDisplayCount(v string) int { } // ParseShow parses the text output of `reims-ctl show ` while redacting MAC addresses. +// Paths under the user's home are abbreviated upstream (3731afd, cli.rs:1117,1189-1192). func ParseShow(name, text string) VMDetail { d := VMDetail{ Name: name, @@ -577,7 +578,7 @@ func ParseShow(name, text string) VMDetail { case "kind": d.Kind = v case "directory": - d.Directory = v + d.Directory = config.ExpandHomePath(v) case "cpus": d.CPUs, _ = strconv.Atoi(v) case "memory": @@ -622,7 +623,7 @@ func ParseShow(name, text string) VMDetail { d.HasOpenCore = v != "" case "installer": d.HasInstaller = v != "" && !strings.EqualFold(v, "none") - d.InstallerPath = v + d.InstallerPath = config.ExpandHomePath(v) case "cpu model": d.CPUModel = v case "audio": diff --git a/internal/driver/reims/reims_test.go b/internal/driver/reims/reims_test.go index 3f11d31..e399834 100644 --- a/internal/driver/reims/reims_test.go +++ b/internal/driver/reims/reims_test.go @@ -1,6 +1,7 @@ package reims import ( + "path/filepath" "reflect" "strings" "testing" @@ -63,6 +64,26 @@ func TestParseShowRedactsMACAndDetectsInstaller(t *testing.T) { } } +func TestParseShowExpandsHomeRelativePaths(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + vm := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "vms", "macos-15") + image := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "installers", "macOS-Sequoia-15.7-offline-installer.img") + tilde := "~" + string(filepath.Separator) + d := ParseShow("macos-15", " directory "+tilde+vm+"\n installer "+tilde+image+"\n") + if want := filepath.Join(home, vm); d.Directory != want { + t.Errorf("VM directory = %q, want %q", d.Directory, want) + } + if want := filepath.Join(home, image); !d.HasInstaller || d.InstallerPath != want { + t.Errorf("installer attached = %t, path = %q, want attached at %q", d.HasInstaller, d.InstallerPath, want) + } + d = ParseShow("macos-15", " directory ~\n installer none\n") + if d.Directory != home || d.HasInstaller { + t.Errorf("VM directory = %q, want %q, installer attached = %t, want false", d.Directory, home, d.HasInstaller) + } +} + func TestOfflineCreateTurnsNetworkOff(t *testing.T) { args, err := BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true}) if err != nil { diff --git a/internal/installguide/progress.go b/internal/installguide/progress.go index f03ff4e..ca44f8f 100644 --- a/internal/installguide/progress.go +++ b/internal/installguide/progress.go @@ -6,6 +6,8 @@ import ( "os" "path/filepath" "strings" + + "github.com/Nwflower/reims-go/internal/config" ) const progressFile = ".reims-go-install-guide.json" @@ -55,7 +57,9 @@ func (g *Guide) Resume(dir, media string, recovery bool) bool { return recovery } if recovery { - if cp.Kind == g.Kind && strings.EqualFold(cp.Media, media) && cp.Step.recoveryStep(g.Kind) { + // Older checkpoints may contain the abbreviated installer path from show. + sameMedia := strings.EqualFold(config.ExpandHomePath(cp.Media), media) + if cp.Kind == g.Kind && sameMedia && cp.Step.recoveryStep(g.Kind) { g.initial = cp.Step } return true diff --git a/internal/installguide/session_windows_test.go b/internal/installguide/session_windows_test.go index 4e9edef..b6040ff 100644 --- a/internal/installguide/session_windows_test.go +++ b/internal/installguide/session_windows_test.go @@ -2,6 +2,7 @@ package installguide import ( "errors" + "path/filepath" "testing" "time" ) @@ -148,3 +149,17 @@ func TestGuideKeepsMediaAndVMProgressSeparate(t *testing.T) { t.Fatal("clone inherited source disk preparation") } } + +func TestGuideResumesWithExpandedInstallerPath(t *testing.T) { + home := t.TempDir() + t.Setenv("USERPROFILE", home) + dir := t.TempDir() + g := Guide{Name: "macos-15", Kind: Offline, PID: 33} + g.Resume(dir, `~\macOS-15-offline-installer.img`, true) + if err := g.save(command, 0); err != nil { + t.Fatal(err) + } + if !g.Resume(dir, filepath.Join(home, "macOS-15-offline-installer.img"), true) || g.initial != command { + t.Fatalf("guide resumed at %s, want %s", g.initial, command) + } +}