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

435 lines
12 KiB
Go

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 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 {
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
}
dir, err := filepath.Abs(vm.sharedDir)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
return
}
if !versioned {
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 = fs.WalkDir(root.FS(), ".", 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 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, 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)
}
}
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)
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
}
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 != "")
}
}
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, 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 || !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, 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
}
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, "upload file unavailable", http.StatusInternalServerError)
return
}
defer root.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)
_ = 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 {
if !matchSyncFile(r, info) {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
uploaded, err := root.Stat(tmpName)
if err != nil {
http.Error(w, "uploaded file unavailable", http.StatusInternalServerError)
return
}
uploadedTag = syncFileTag(uploaded)
}
if err := root.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)
}