webdav: keep X-OC-Mtime and report oc:checksums (#13226)

* webdav: keep X-OC-Mtime and report oc:checksums

ownCloud and Nextcloud sync clients, and rclone's webdav backend in those
vendor modes, send a file's modification time in X-OC-Mtime and read its
hash from the oc:checksums property. Without them every upload gets the
upload time as mtime and clients can only compare sizes, so syncs re-upload
unchanged files.

- PUT stores X-OC-Mtime (Unix seconds, fractions dropped) as the entry's
  mtime, at create and at commit, and answers "X-OC-Mtime: accepted"
- a file created and written front to back stores its content MD5; any
  other write clears it, so no stale MD5 outlives a partial rewrite
- PROPFIND reports oc:checksums ("MD5:<hex>") for files whose MD5 is known;
  PROPPATCH is still refused

Checked with rclone (vendor=owncloud): sync keeps mtimes, md5sum matches
local files, including an 8-chunk file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: only report an inline MD5 for whole inline content; test commits

- contentMd5 hashes inline content only when it is the whole file
  (filer.ETagOfInlineContent): content next to chunks, or shorter than the
  file size, is only part of it and must not be advertised as its checksum
- test a PUT that crosses a buffer flush end to end: the committed entry
  carries the X-OC-Mtime and the MD5 of the whole body
- test that writing into an existing file clears its stored MD5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: ignore a NaN X-OC-Mtime

int64 of NaN is implementation-specific (the most negative value on amd64,
the largest on riscv64), so a NaN header could store an arbitrary mtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* webdav: group the oc test imports

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Denis Maier <denis@dAir.lab>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-12-01 13:16:48 -08:00
1 parent c8cd1a7d77
commit 484e16e30c
3 files changed
+457 -5

No files matched your search

+90
View File
@@ -0,0 +1,90 @@
package weed_server
import (
"encoding/hex"
"encoding/xml"
"net/http"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"golang.org/x/net/webdav"
)
// ownCloud's namespace; ownCloud and Nextcloud clients (and rclone's webdav
// backend in those vendor modes) read file hashes from oc:checksums
const ownCloudNS = "http://owncloud.org/ns"
var ocChecksums = xml.Name{Space: ownCloudNS, Local: "checksums"}
// contentMd5 is the MD5 of the whole content when the filer knows it: stored
// for files written in one pass, or computed from content stored inline. The ETag
// of a chunked file is not a content MD5, so such files report none.
func contentMd5(entry *filer_pb.Entry) []byte {
if entry.IsDirectory {
return nil
}
if entry.Attributes != nil && len(entry.Attributes.Md5) > 0 {
return entry.Attributes.Md5
}
// only when the whole file is inline: content next to chunks, or short
// of the file size, is just part of it
if etag, ok := filer.ETagOfInlineContent(entry); ok {
if sum, err := hex.DecodeString(etag); err == nil {
return sum
}
}
return nil
}
// DeadProps publishes oc:checksums ("MD5:<hex>") for files whose MD5 is
// known, so ownCloud-style clients can verify transfers without downloading.
func (f *WebDavFile) DeadProps() (map[xml.Name]webdav.Property, error) {
if f.info == nil || f.info.isDirectory || len(f.info.md5) == 0 {
return nil, nil
}
return map[xml.Name]webdav.Property{
ocChecksums: {
XMLName: ocChecksums,
InnerXML: []byte(`<checksum xmlns="` + ownCloudNS + `">MD5:` + hex.EncodeToString(f.info.md5) + `</checksum>`),
},
}, nil
}
// Patch refuses every change: the only dead property is computed, and
// PROPPATCH was refused the same way before files held dead properties.
func (f *WebDavFile) Patch(patches []webdav.Proppatch) ([]webdav.Propstat, error) {
pstat := webdav.Propstat{Status: http.StatusForbidden}
for _, patch := range patches {
for _, p := range patch.Props {
pstat.Props = append(pstat.Props, webdav.Property{XMLName: p.XMLName})
}
}
return []webdav.Propstat{pstat}, nil
}
// hashWrite feeds buf to the content hash while the file is being written
// front to back from empty; a write anywhere else gives the hash up
func (f *WebDavFile) hashWrite(buf []byte) {
if !f.created || f.hashBroken {
return
}
if f.off != f.hashed {
f.hashBroken = true
return
}
if f.hasher == nil {
f.hasher = util.NewMd5()
}
f.hasher.Write(buf)
f.hashed += int64(len(buf))
}
// contentMd5 is the MD5 of what this open wrote, when it wrote the whole
// file in order; nil otherwise, so no stale MD5 outlives a partial rewrite
func (f *WebDavFile) contentMd5() []byte {
if !f.created || f.hashBroken || f.hasher == nil || f.hashed != int64(f.entry.Attributes.FileSize) {
return nil
}
return f.hasher.Sum(nil)
}
+315
View File
@@ -0,0 +1,315 @@
package weed_server
import (
"bytes"
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"golang.org/x/net/webdav"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/proto"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestParseOCMtime(t *testing.T) {
for in, want := range map[string]int64{
"": 0,
"1577836800": 1577836800,
" 1577836800.75 ": 1577836800,
"-5": 0,
"0": 0,
"yesterday": 0,
"1e300": 0,
"NaN": 0,
"-Inf": 0,
} {
if got := parseOCMtime(in); got != want {
t.Errorf("parseOCMtime(%q) = %d, want %d", in, got, want)
}
}
}
func newTestDavFS(t *testing.T, impl filer_pb.SeaweedFilerServer) *WebDavFileSystem {
return &WebDavFileSystem{option: &WebDavOption{
Filer: startFakeWebDavFiler(t, impl),
GrpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
}}
}
func davHandler(fs webdav.FileSystem) http.Handler {
return copyMoveGuardHandler{fs: fs, next: &webdav.Handler{FileSystem: fs, LockSystem: webdav.NewMemLS()}}
}
// an empty PUT never writes, so the mtime has to land at create
func TestPutKeepsOCMtime(t *testing.T) {
filer := &createRecordingFiler{dirs: map[string]bool{"/": true}}
h := davHandler(newTestDavFS(t, filer))
req := httptest.NewRequest("PUT", "/f.txt", strings.NewReader(""))
req.Header.Set("X-OC-Mtime", "1577836800")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("PUT = %d, want 201", rec.Code)
}
if got := filer.req.Entry.Attributes.Mtime; got != 1577836800 {
t.Errorf("stored mtime = %d, want 1577836800", got)
}
if got := rec.Header().Get("X-OC-Mtime"); got != "accepted" {
t.Errorf("X-OC-Mtime response = %q, want accepted", got)
}
}
func TestPutWithoutOCMtimeUsesNow(t *testing.T) {
filer := &createRecordingFiler{dirs: map[string]bool{"/": true}}
h := davHandler(newTestDavFS(t, filer))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("PUT", "/f.txt", strings.NewReader("")))
if filer.req.Entry.Attributes.Mtime < 1700000000 {
t.Errorf("stored mtime = %d, want the upload time", filer.req.Entry.Attributes.Mtime)
}
if got := rec.Header().Get("X-OC-Mtime"); got != "" {
t.Errorf("X-OC-Mtime response = %q without a request header", got)
}
}
func TestCloseAppliesOCMtime(t *testing.T) {
outcome := &putOutcome{mtime: 1577836800}
ctx := context.WithValue(context.Background(), putOutcomeKey{}, outcome)
if got := putMtime(ctx); got != 1577836800 {
t.Errorf("putMtime = %d, want the X-OC-Mtime", got)
}
if got := putMtime(context.Background()); got < 1700000000 {
t.Errorf("putMtime without a PUT = %d, want now", got)
}
}
func propfind(t *testing.T, h http.Handler, name, body string) string {
t.Helper()
req := httptest.NewRequest("PROPFIND", name, strings.NewReader(body))
req.Header.Set("Depth", "0")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusMultiStatus {
t.Fatalf("PROPFIND %s = %d, want 207", name, rec.Code)
}
return rec.Body.String()
}
const ocChecksumsPropfind = `<?xml version="1.0"?>
<d:propfind xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:prop><d:getlastmodified/><oc:checksums/></d:prop></d:propfind>`
func TestPropfindReportsOCChecksum(t *testing.T) {
md5 := []byte{0x5d, 0x41, 0x40, 0x2a, 0xbc, 0x4b, 0x2a, 0x76, 0xb9, 0x71, 0x9d, 0x91, 0x10, 0x17, 0xc5, 0x92}
filer := &deleteRecordingFiler{existing: &filer_pb.Entry{
Name: "f.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5, Md5: md5},
Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Size: 5}},
}}
h := davHandler(newTestDavFS(t, filer))
body := propfind(t, h, "/f.txt", ocChecksumsPropfind)
if !strings.Contains(body, "MD5:5d41402abc4b2a76b9719d911017c592") {
t.Errorf("PROPFIND lacks the MD5 checksum:\n%s", body)
}
}
func TestPropfindOmitsUnknownChecksum(t *testing.T) {
// a chunked upload: the filer has no whole-content MD5
filer := &deleteRecordingFiler{existing: &filer_pb.Entry{
Name: "f.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5},
Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Size: 5, ETag: "XUFAKrxLKna5cZ2REBfFkg=="}},
}}
h := davHandler(newTestDavFS(t, filer))
body := propfind(t, h, "/f.txt", ocChecksumsPropfind)
if strings.Contains(body, "MD5:") {
t.Errorf("PROPFIND reports a checksum the filer does not have:\n%s", body)
}
}
func TestProppatchStillForbidden(t *testing.T) {
filer := &deleteRecordingFiler{existing: &filer_pb.Entry{
Name: "f.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0644, Md5: make([]byte, 16)},
}}
h := davHandler(newTestDavFS(t, filer))
req := httptest.NewRequest("PROPPATCH", "/f.txt", strings.NewReader(`<?xml version="1.0"?>
<d:propertyupdate xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns"><d:set><d:prop><oc:checksums>x</oc:checksums></d:prop></d:set></d:propertyupdate>`))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if !strings.Contains(rec.Body.String(), "403") {
t.Errorf("PROPPATCH was not refused:\n%s", rec.Body.String())
}
}
func TestWriteRecordsContentMd5(t *testing.T) {
newFile := func(created bool) *WebDavFile {
return &WebDavFile{created: created, entry: &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}}
}
write := func(f *WebDavFile, off int64, data string) {
f.off = off
f.hashWrite([]byte(data))
f.off += int64(len(data))
if size := uint64(f.off); size > f.entry.Attributes.FileSize {
f.entry.Attributes.FileSize = size
}
}
f := newFile(true)
write(f, 0, "hel")
write(f, 3, "lo")
if got := hex.EncodeToString(f.contentMd5()); got != "5d41402abc4b2a76b9719d911017c592" {
t.Errorf("in-order write MD5 = %q", got)
}
f = newFile(true)
write(f, 3, "lo")
write(f, 0, "hel")
if f.contentMd5() != nil {
t.Error("out-of-order write got an MD5")
}
// a file opened without creating it may already hold other bytes
f = newFile(false)
write(f, 0, "hello")
if f.contentMd5() != nil {
t.Error("write into an existing file got an MD5")
}
}
// uploadFiler stores what WebDAV uploads commit: chunks go to a stand-in
// volume server, and the last UpdateEntry is kept
type uploadFiler struct {
createRecordingFiler
volume string // host:port of the stand-in volume server
existing map[string]*filer_pb.Entry
mu sync.Mutex
updated *filer_pb.Entry
}
func (f *uploadFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
if entry, ok := f.existing[string(util.NewFullPath(req.Directory, req.Name))]; ok {
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
}
return f.createRecordingFiler.LookupDirectoryEntry(ctx, req)
}
func (f *uploadFiler) AssignVolume(context.Context, *filer_pb.AssignVolumeRequest) (*filer_pb.AssignVolumeResponse, error) {
return &filer_pb.AssignVolumeResponse{FileId: "1,0000000100001234", Location: &filer_pb.Location{Url: f.volume}}, nil
}
func (f *uploadFiler) UpdateEntry(_ context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.updated = proto.Clone(req.Entry).(*filer_pb.Entry)
return &filer_pb.UpdateEntryResponse{}, nil
}
func newUploadFiler(t *testing.T) *uploadFiler {
volume := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
n, _ := io.Copy(io.Discard, r.Body)
fmt.Fprintf(w, `{"size":%d}`, n)
}))
t.Cleanup(volume.Close)
return &uploadFiler{
createRecordingFiler: createRecordingFiler{dirs: map[string]bool{"/": true}},
volume: strings.TrimPrefix(volume.URL, "http://"),
}
}
// a PUT larger than the write buffer commits several chunks; the entry it
// commits carries the X-OC-Mtime and the MD5 of the whole body
func TestPutCommitsOCMtimeAndMd5(t *testing.T) {
filer := newUploadFiler(t)
fs := newTestDavFS(t, filer)
fs.option.MaxMB = 1
body := bytes.Repeat([]byte("0123456789abcdef"), 160*1024) // 2.5 MiB
req := httptest.NewRequest("PUT", "/big.bin", bytes.NewReader(body))
req.Header.Set("X-OC-Mtime", "1577836800")
rec := httptest.NewRecorder()
davHandler(fs).ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("PUT = %d, want 201: %s", rec.Code, rec.Body.String())
}
if filer.updated == nil {
t.Fatal("the upload committed no entry")
}
if n := len(filer.updated.GetChunks()); n < 2 {
t.Errorf("committed %d chunks, want the upload to cross a buffer flush", n)
}
if got := filer.updated.Attributes.Mtime; got != 1577836800 {
t.Errorf("committed mtime = %d, want 1577836800", got)
}
want := md5.Sum(body)
if got := filer.updated.Attributes.Md5; !bytes.Equal(got, want[:]) {
t.Errorf("committed MD5 = %x, want %x", got, want)
}
}
// writing into a file this open did not create leaves its content unknown,
// so the MD5 stored for the old content goes
func TestRewriteClearsStoredMd5(t *testing.T) {
filer := newUploadFiler(t)
filer.existing = map[string]*filer_pb.Entry{"/f.txt": {
Name: "f.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0644, FileSize: 5, Md5: []byte("old-md5-old-md5!")},
Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Size: 5}},
}}
fs := newTestDavFS(t, filer)
fs.option.MaxMB = 1
f, err := fs.OpenFile(context.Background(), "/f.txt", os.O_RDWR, 0644)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write([]byte("HE")); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
if filer.updated == nil {
t.Fatal("the write committed no entry")
}
if got := filer.updated.Attributes.Md5; got != nil {
t.Errorf("rewritten file kept MD5 %q", got)
}
}
func TestContentMd5OnlyForWholeInlineContent(t *testing.T) {
hello := []byte("hello")
for name, tc := range map[string]struct {
entry *filer_pb.Entry
want bool
}{
"inline": {&filer_pb.Entry{Content: hello, Attributes: &filer_pb.FuseAttributes{FileSize: 5}}, true},
"empty": {&filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}}, true},
"inline and chunks": {&filer_pb.Entry{Content: hello, Attributes: &filer_pb.FuseAttributes{FileSize: 10}, Chunks: []*filer_pb.FileChunk{{FileId: "1,01", Offset: 5, Size: 5}}}, false},
"short of the size": {&filer_pb.Entry{Content: hello, Attributes: &filer_pb.FuseAttributes{FileSize: 10}}, false},
"directory": {&filer_pb.Entry{IsDirectory: true, Attributes: &filer_pb.FuseAttributes{}}, false},
} {
if got := contentMd5(tc.entry) != nil; got != tc.want {
t.Errorf("%s: has MD5 = %v, want %v", name, got, tc.want)
}
}
}
+52 -5
View File
@@ -4,11 +4,14 @@ import (
"context"
"errors"
"fmt"
"hash"
"io"
"math"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
@@ -120,6 +123,30 @@ type putOutcome struct {
replaced bool
committed bool
etag string
// mtime is the modification time the client sent in X-OC-Mtime (Unix
// seconds), 0 when it sent none; it replaces the upload time
mtime int64
}
// putMtime is the X-OC-Mtime of the PUT behind ctx, or now when there is none
func putMtime(ctx context.Context) int64 {
if outcome, ok := ctx.Value(putOutcomeKey{}).(*putOutcome); ok && outcome.mtime > 0 {
return outcome.mtime
}
return time.Now().Unix()
}
// parseOCMtime reads X-OC-Mtime as ownCloud and Nextcloud clients send it:
// Unix seconds, possibly with a fraction; anything else is ignored
func parseOCMtime(v string) int64 {
if v == "" {
return 0
}
f, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
if err != nil || !(f > 0 && f <= math.MaxInt32*4) {
return 0
}
return int64(f)
}
// putOutcomeWriter turns the 201 of a PUT that replaced a file into 204,
@@ -132,6 +159,11 @@ type putOutcomeWriter struct {
}
func (w *putOutcomeWriter) WriteHeader(code int) {
// the X-OC-Mtime was applied when the entry was created and again when
// its content was committed
if code == http.StatusCreated && w.outcome.mtime > 0 {
w.Header().Set("X-OC-Mtime", "accepted")
}
if code == http.StatusCreated && w.outcome.committed {
if w.outcome.etag != "" {
w.Header().Set("ETag", `"`+w.outcome.etag+`"`)
@@ -287,7 +319,7 @@ func (h copyMoveGuardHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
// always answers 201, so OpenFile reports a replace on the request
// context and the writer rewrites the status it sends
if r.Method == "PUT" {
outcome := &putOutcome{}
outcome := &putOutcome{mtime: parseOCMtime(r.Header.Get("X-OC-Mtime"))}
w = &putOutcomeWriter{ResponseWriter: w, outcome: outcome}
r = r.WithContext(context.WithValue(r.Context(), putOutcomeKey{}, outcome))
}
@@ -377,6 +409,7 @@ type FileInfo struct {
mode os.FileMode
modifiedTime time.Time
etag string
md5 []byte // content MD5 when the filer has it
isDirectory bool
}
@@ -405,8 +438,14 @@ type WebDavFile struct {
reader *filer.ChunkReadAt
bufWriter *buffered_writer.BufferedWriteCloser
ctx context.Context
created bool // this open created or replaced the entry, so a failed upload removes it
createdTsNs int64 // commit stamp of that entry; a version another writer stored is kept
info *FileInfo // what OpenFile found, for DeadProps; nil for created files
created bool // this open created or replaced the entry, so a failed upload removes it
createdTsNs int64 // commit stamp of that entry; a version another writer stored is kept
// a created file written front to back is hashed as it is written, so
// its content MD5 can be stored; any other write leaves the MD5 unknown
hasher hash.Hash
hashed int64
hashBroken bool
}
func NewWebDavFileSystem(option *WebDavOption) (webdav.FileSystem, error) {
@@ -561,7 +600,7 @@ func (fs *WebDavFileSystem) OpenFile(ctx context.Context, fullFilePath string, f
Name: name,
IsDirectory: perm&os.ModeDir > 0,
Attributes: &filer_pb.FuseAttributes{
Mtime: time.Now().Unix(),
Mtime: putMtime(ctx),
Crtime: time.Now().Unix(),
FileMode: uint32(perm),
Uid: fs.option.Uid,
@@ -612,12 +651,14 @@ func (fs *WebDavFileSystem) OpenFile(ctx context.Context, fullFilePath string, f
fullFilePath += "/"
}
info, _ := fi.(*FileInfo)
return &WebDavFile{
fs: fs,
name: fullFilePath,
isDirectory: false,
bufWriter: buffered_writer.NewBufferedWriteCloser(fs.option.MaxMB * 1024 * 1024),
ctx: ctx,
info: info,
}, nil
}
@@ -796,6 +837,7 @@ func toFileInfo(fullpath util.FullPath, entry *filer_pb.Entry) *FileInfo {
mode: os.FileMode(entry.Attributes.FileMode),
modifiedTime: time.Unix(entry.Attributes.Mtime, 0),
etag: contentETag(entry),
md5: contentMd5(entry),
isDirectory: entry.IsDirectory,
}
@@ -892,7 +934,8 @@ func (f *WebDavFile) Write(buf []byte) (int, error) {
return err
}
flushErr := f.fs.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
f.entry.Attributes.Mtime = time.Now().Unix()
f.entry.Attributes.Mtime = putMtime(f.requestContext())
f.entry.Attributes.Md5 = f.contentMd5()
request := &filer_pb.UpdateEntryRequest{
Directory: dir,
@@ -910,7 +953,11 @@ func (f *WebDavFile) Write(buf []byte) (int, error) {
}
}
f.hashWrite(buf)
written, err := f.bufWriter.Write(buf)
if err != nil || written != len(buf) {
f.hashBroken = true
}
if err == nil {
f.entry.Attributes.FileSize = uint64(max(f.off+int64(written), int64(f.entry.Attributes.FileSize)))