package guesttools import ( "crypto/rand" "crypto/sha256" "errors" "fmt" "io" "io/fs" "net/http" "os" "path" "path/filepath" "sort" "strconv" "strings" "time" ) const ( syncScopeHeader = "X-Reims-Sync-Scope" syncDigestHeader = "X-Reims-File-SHA256" ) 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 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 } unavailable := http.StatusInternalServerError if versioned { unavailable = http.StatusServiceUnavailable } root, err := openSharedRoot(vm.sharedRoot, !versioned) if err != nil { http.Error(w, "shared directory unavailable", unavailable) return } defer root.Close() var scope string if versioned { scope, err = syncFileScope(vm.token, root) if err != nil { http.Error(w, "shared directory unavailable", unavailable) return } } files, err := listSharedFiles(root.FS(), func(name string) (os.FileInfo, error) { return statDAVEntry(root, name) }, versioned) if err != nil { http.Error(w, "shared directory unavailable", unavailable) return } if versioned { 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") 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) } } type sharedFileEntry struct { name string info fs.FileInfo } func listSharedFiles(fsys fs.FS, stat func(string) (os.FileInfo, error), versioned bool) ([]sharedFileEntry, error) { var files []sharedFileEntry err := fs.WalkDir(fsys, ".", func(name string, d fs.DirEntry, err error) error { if name == "." { return err } if err != nil { return nil } if isIgnoredSharedName(d.Name()) || d.Type()&os.ModeSymlink != 0 { if d.IsDir() { return filepath.SkipDir } return nil } if strings.Count(name, "/")+1 > MaxSharedDepth { if d.IsDir() { return filepath.SkipDir } return nil } if versioned && !validSyncFileName(name) { if d.IsDir() { return fs.SkipDir } return nil } info, err := stat(name) if err != nil && d.IsDir() { return fs.SkipDir } if err != nil || !isSharedRegularFile(info.Mode()) || info.Size() > MaxUploadBytes { return nil } if len(files) == MaxSharedFiles { return fs.SkipAll } files = append(files, sharedFileEntry{name, info}) return nil }) return files, err } 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 } scope := r.Header.Get(syncScopeHeader) 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 } case http.MethodGet, http.MethodPut, http.MethodPost: default: http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } root, err := openSharedRoot(vm.sharedRoot, scope == "" && writing) if err != nil { switch { case scope != "": http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable) case !writing && errors.Is(err, fs.ErrNotExist): http.NotFound(w, r) default: http.Error(w, "shared directory unavailable", http.StatusInternalServerError) } 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 != "") } } func matchSyncFile(r *http.Request, info fs.FileInfo) bool { if tag := r.Header.Get("If-Match"); tag != "" { return info != nil && isSharedRegularFile(info.Mode()) && 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 checkSharedFileParents(root *os.Root, name string) error { for i, ch := range name { if ch != '/' { continue } info, err := statDAVEntry(root, name[:i]) if err == os.ErrPermission || (err == nil && !info.IsDir()) { return fs.ErrInvalid } if err != nil { return err } } return nil } func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) { if err := checkSharedFileParents(root, name); err != nil { return nil, err } info, err := statDAVEntry(root, name) if err == os.ErrPermission || (err == nil && !isSharedRegularFile(info.Mode())) { return nil, fs.ErrInvalid } return info, err } 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 == "") { http.Error(w, "file revision required", http.StatusPreconditionRequired) return } 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 || !isSharedRegularFile(opened.Mode()) || !os.SameFile(info, opened) || 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, root *os.Root, name string, versioned bool) { if err := checkSharedFileParents(root, name); err != nil && !errors.Is(err, fs.ErrNotExist) { http.Error(w, "upload directory unavailable", http.StatusConflict) return } dir := path.Dir(name) if err := root.MkdirAll(dir, 0o755); err != nil { http.Error(w, "upload directory unavailable", http.StatusInternalServerError) return } parent, err := root.OpenRoot(dir) if err != nil { http.Error(w, "upload directory unavailable", http.StatusInternalServerError) return } defer parent.Close() tmpName := ".reims-upload-" + rand.Text() tmp, err := parent.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if err != nil { http.Error(w, "upload file unavailable", http.StatusInternalServerError) return } defer parent.Remove(tmpName) 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) _ = parent.Chtimes(tmpName, t, t) } s.fileMu.Lock() defer s.fileMu.Unlock() currentParent, err := statDAVEntry(root, dir) openedParent, openErr := parent.Stat(".") if err != nil || openErr != nil || !os.SameFile(currentParent, openedParent) || checkSharedFileParents(root, name) != nil { http.Error(w, "upload directory changed", http.StatusConflict) return } name = path.Base(name) info, err := statSharedFile(parent, 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 { if !matchSyncFile(r, info) { http.Error(w, "file changed", http.StatusPreconditionFailed) return } uploaded, err := parent.Stat(tmpName) if err != nil { http.Error(w, "uploaded file unavailable", http.StatusInternalServerError) return } uploadedTag = syncFileTag(uploaded) } if err := parent.Rename(tmpName, name); err != nil { http.Error(w, "publish uploaded file failed", http.StatusInternalServerError) return } if versioned { w.Header().Set("ETag", uploadedTag) w.Header().Set(syncDigestHeader, fmt.Sprintf("%x", h.Sum(nil))) } w.WriteHeader(http.StatusOK) }