diff --git a/weed/server/filer_server_handlers.go b/weed/server/filer_server_handlers.go index 95d46f1707..bc4a8c4643 100644 --- a/weed/server/filer_server_handlers.go +++ b/weed/server/filer_server_handlers.go @@ -148,13 +148,12 @@ const ( // -maxMB, as requestChunkSize resolves it, and the filer default when neither is // positive, so the charge never collapses to 0. // -// A POST stored inside the filer entry (?saveInside=true, or under /etc) is -// read into memory whole (doPostAutoChunk), so with a limit set it is charged +// A POST or PUT stored inside the filer entry (?saveInside=true, or under /etc) +// is read into memory whole (saveInsideEntry), so with a limit set it is charged // its whole declared length, at most the whole budget, and an unknown length is // charged the whole budget: it then runs only on an idle filer, the one place a -// body of any size can be buffered without overshooting. A PUT there still goes -// through the chunk loop and is charged by chunks. With no limit the charge -// only feeds the gauge, so the chunk-based one is kept. +// body of any size can be buffered without overshooting. With no limit the +// charge only feeds the gauge, so the chunk-based one is kept. func (fs *FilerServer) uploadCharge(r *http.Request) int64 { limit := fs.option.ConcurrentUploadLimit query := r.URL.Query() @@ -163,7 +162,7 @@ func (fs *FilerServer) uploadCharge(r *http.Request) int64 { chunk = filerDefaultChunkSizeMB << 20 } chunk = min(chunk, filerMaxChunkSizeMB<<20) - if limit > 0 && r.Method == http.MethodPost && (query.Get("saveInside") == "true" || strings.HasPrefix(r.URL.Path, "/etc")) { + if limit > 0 && (r.Method == http.MethodPost || r.Method == http.MethodPut) && (query.Get("saveInside") == "true" || util.IsEqualOrUnder(r.URL.Path, filer.DirectoryEtcRoot)) { if r.ContentLength >= 0 { return min(r.ContentLength, limit) } diff --git a/weed/server/filer_server_handlers_extract.go b/weed/server/filer_server_handlers_extract.go index 97057ee3fc..33cf366535 100644 --- a/weed/server/filer_server_handlers_extract.go +++ b/weed/server/filer_server_handlers_extract.go @@ -126,7 +126,7 @@ func (fs *FilerServer) extractZipArchive(ctx context.Context, w http.ResponseWri if memberSO.DiskType == "" { memberSO.DiskType = fs.option.DiskType } - if strings.HasPrefix(writePath, "/etc") { + if util.IsEqualOrUnder(writePath, filer.DirectoryEtcRoot) { memberSO.SaveInside = true } return memberSO, nil @@ -266,7 +266,7 @@ func (fs *FilerServer) saveExtractedEntry(ctx context.Context, destPath string, // multipart upload; the declared size keeps a corrupt archive from // buffering more than it advertised. if so.SaveInside { - if memberSize < 0 || memberSize > filer.ZipExtractMaxBytes { + if memberSize < 0 || memberSize > saveInsideMaxBytes { return nil, fmt.Errorf("zip member %s size %d out of bounds", fileName, memberSize) } var buf bytes.Buffer diff --git a/weed/server/filer_server_handlers_extract_test.go b/weed/server/filer_server_handlers_extract_test.go index 3040a9ad4a..779ac34a5d 100644 --- a/weed/server/filer_server_handlers_extract_test.go +++ b/weed/server/filer_server_handlers_extract_test.go @@ -4,13 +4,16 @@ import ( "archive/zip" "bytes" "encoding/json" + "errors" "mime/multipart" "net/http" "net/http/httptest" + "strings" "testing" "time" "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" "github.com/seaweedfs/seaweedfs/weed/util" ) @@ -316,3 +319,35 @@ func multipartWriter(t *testing.T, buf *bytes.Buffer, fileName string, data []by } return mw.FormDataContentType() } + +// A member kept inline under /etc/ is held in memory whole, so it gets the +// same bound as an upload saved inside the entry. +func TestExtractZipArchiveInlineMemberIsBounded(t *testing.T) { + fs, f := newExtractTestServer(t) + zipBytes := buildTestZip(t, map[string]string{ + "big.json": strings.Repeat("z", saveInsideMaxBytes+1), + "small.json": "{}", + }, nil, nil) + + r := httptest.NewRequest(http.MethodPut, "/etc/pack.zip?extract=zip", bytes.NewReader(zipBytes)) + w := httptest.NewRecorder() + fs.PostHandler(w, r, int64(len(zipBytes))) + + if w.Code != http.StatusCreated { + t.Fatalf("status = %d, body: %s", w.Code, w.Body.String()) + } + var result FilerExtractResult + if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil { + t.Fatalf("decode result: %v", err) + } + if len(result.Errors) != 1 || !strings.Contains(result.Errors[0], "big.json") { + t.Fatalf("member errors = %v, want big.json refused", result.Errors) + } + if _, err := f.FindEntry(r.Context(), "/etc/big.json"); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("oversized member stored: %v", err) + } + small, err := f.FindEntry(r.Context(), "/etc/small.json") + if err != nil || string(small.Content) != "{}" || len(small.GetChunks()) != 0 { + t.Fatalf("small member: %v, want inline {}", err) + } +} diff --git a/weed/server/filer_server_handlers_upload_slot_test.go b/weed/server/filer_server_handlers_upload_slot_test.go index 418876b877..a786b18bb4 100644 --- a/weed/server/filer_server_handlers_upload_slot_test.go +++ b/weed/server/filer_server_handlers_upload_slot_test.go @@ -195,10 +195,16 @@ func TestFilerUploadChargeFollowsRequestMaxMB(t *testing.T) { // side by side. func TestFilerUploadChargeCoversInlineUploads(t *testing.T) { const limit = 64 << 20 - for _, target := range []string{"/dir/file?saveInside=true", "/etc/config.toml"} { - t.Run(target, func(t *testing.T) { + for _, tc := range []struct{ method, target string }{ + {http.MethodPost, "/dir/file?saveInside=true"}, + {http.MethodPost, "/etc/config.toml"}, + {http.MethodPut, "/dir/file?saveInside=true"}, + {http.MethodPut, "/etc/config.toml"}, + } { + method, target := tc.method, tc.target + t.Run(method+" "+target, func(t *testing.T) { fs := newLimitedFiler(limit, 0) - req := httptest.NewRequest(http.MethodPost, target, strings.NewReader("data")) + req := httptest.NewRequest(method, target, strings.NewReader("data")) req.ContentLength = 80 << 20 // The whole body, capped at the whole budget: over the budget it // runs only on an idle filer either way. @@ -214,7 +220,7 @@ func TestFilerUploadChargeCoversInlineUploads(t *testing.T) { if !fs.waitForUploadSlot(httptest.NewRecorder(), req, fs.uploadCharge(req)) { t.Fatal("an oversized inline upload was refused on an idle filer") } - second := httptest.NewRequest(http.MethodPost, target, strings.NewReader("data")) + second := httptest.NewRequest(method, target, strings.NewReader("data")) second.ContentLength = 80 << 20 if fs.waitForUploadSlot(httptest.NewRecorder(), second, fs.uploadCharge(second)) { t.Fatal("a second 80 MiB inline upload was admitted beside the first") @@ -233,14 +239,3 @@ func TestFilerUploadChargeCoversInlineUploads(t *testing.T) { }) } } - -// A PUT to an inline path still goes through the chunk loop, so it is charged by -// chunks: charged its whole body it would only run on an idle filer. -func TestFilerUploadChargeKeepsChunksForInlinePut(t *testing.T) { - fs := newLimitedFiler(64<<20, 0) - req := httptest.NewRequest(http.MethodPut, "/etc/config.toml", strings.NewReader("data")) - req.ContentLength = 1 << 30 - if got := fs.uploadCharge(req); got != 4*4<<20 { - t.Fatalf("1 GiB PUT under /etc: charge %d, want four 4 MiB chunks", got) - } -} diff --git a/weed/server/filer_server_handlers_write.go b/weed/server/filer_server_handlers_write.go index 8c73bb0e4d..324e0518c0 100644 --- a/weed/server/filer_server_handlers_write.go +++ b/weed/server/filer_server_handlers_write.go @@ -138,7 +138,7 @@ func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request, conte so.DiskType = fs.option.DiskType } - if strings.HasPrefix(r.URL.Path, "/etc") { + if util.IsEqualOrUnder(r.URL.Path, filer.DirectoryEtcRoot) { so.SaveInside = true } diff --git a/weed/server/filer_server_handlers_write_autochunk.go b/weed/server/filer_server_handlers_write_autochunk.go index cd3c7211c4..b6574e98d4 100644 --- a/weed/server/filer_server_handlers_write_autochunk.go +++ b/weed/server/filer_server_handlers_write_autochunk.go @@ -60,7 +60,10 @@ func (fs *FilerServer) autoChunk(ctx context.Context, w http.ResponseWriter, r * writeJsonError(w, r, util.HttpStatusCancelled, err) case strings.HasSuffix(errStr, "is a file") || strings.HasSuffix(errStr, "already exists"): writeJsonError(w, r, http.StatusConflict, err) - case errStr == constants.ErrMsgBadDigest, + case strings.HasPrefix(errStr, constants.ErrMsgSaveInsideTooLarge): + writeJsonError(w, r, http.StatusRequestEntityTooLarge, err) + case strings.HasPrefix(errStr, constants.ErrMsgInvalidOffset), + errStr == constants.ErrMsgBadDigest, errStr == constants.ErrMsgAppendSaveInsideChunked, errStr == constants.ErrMsgAppendInlineMode, errStr == constants.ErrMsgOffsetWriteInline, @@ -103,20 +106,7 @@ func (fs *FilerServer) doPostAutoChunk(ctx context.Context, w http.ResponseWrite } if so.SaveInside { - buf := bufPool.Get().(*bytes.Buffer) - buf.Reset() - if _, err := buf.ReadFrom(part1); err != nil { - bufPool.Put(buf) - return nil, nil, fmt.Errorf("read input: %w", err) - } - md5bytes = util.Md5(buf.Bytes()) - if contentMd5Mismatch(util.BodyMd5Of(md5bytes, buf.Bytes()), r.Header.Get("Content-Md5")) { - bufPool.Put(buf) - return nil, nil, errors.New(constants.ErrMsgBadDigest) - } - filerResult, replyerr, _ = fs.saveMetaData(ctx, r, fileName, contentType, so, chunkSize, md5bytes, nil, int64(buf.Len()), buf.Bytes()) - bufPool.Put(buf) - return + return fs.saveInsideEntry(ctx, r, part1, fileName, contentType, so, chunkSize) } fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks(ctx, w, r, part1, chunkSize, fileName, contentType, contentLength, so) @@ -150,6 +140,10 @@ func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter return nil, nil, err } + if so.SaveInside { + return fs.saveInsideEntry(ctx, r, r.Body, fileName, contentType, so, chunkSize) + } + fileChunks, md5Hash, chunkOffset, err, smallContent := fs.uploadRequestToChunks(ctx, w, r, r.Body, chunkSize, fileName, contentType, contentLength, so) if err != nil { @@ -170,6 +164,50 @@ func (fs *FilerServer) doPutAutoChunk(ctx context.Context, w http.ResponseWriter return } +// saveInsideMaxBytes bounds a body stored as inline content, which is held in +// memory whole; config files are far smaller. +const saveInsideMaxBytes = 16 << 20 + +// saveInsideEntry stores the whole body as the entry's inline content, as +// /etc files and saveInside=true uploads are kept, with no chunks. +func (fs *FilerServer) saveInsideEntry(ctx context.Context, r *http.Request, body io.Reader, fileName, contentType string, so *operation.StorageOption, chunkSize int32) (filerResult *FilerPostResult, md5bytes []byte, replyerr error) { + // Inline content is always written whole, so an offset into it cannot be honoured. + if offset, err := requestOffset(r); err != nil { + return nil, nil, err + } else if offset > 0 { + return nil, nil, errors.New(constants.ErrMsgOffsetWriteInline) + } + buf := bufPool.Get().(*bytes.Buffer) + buf.Reset() + defer bufPool.Put(buf) + if _, err := buf.ReadFrom(io.LimitReader(body, saveInsideMaxBytes+1)); err != nil { + return nil, nil, fmt.Errorf("read input: %w", err) + } + if buf.Len() > saveInsideMaxBytes { + return nil, nil, fmt.Errorf("%s: over %d bytes", constants.ErrMsgSaveInsideTooLarge, saveInsideMaxBytes) + } + md5bytes = util.Md5(buf.Bytes()) + if contentMd5Mismatch(util.BodyMd5Of(md5bytes, buf.Bytes()), r.Header.Get("Content-Md5")) { + return nil, nil, errors.New(constants.ErrMsgBadDigest) + } + filerResult, replyerr, _ = fs.saveMetaData(ctx, r, fileName, contentType, so, chunkSize, md5bytes, nil, int64(buf.Len()), buf.Bytes()) + return +} + +// requestOffset parses ?offset, which when present must be a non-negative integer. +func requestOffset(r *http.Request) (int64, error) { + query := r.URL.Query() + if !query.Has("offset") { + return 0, nil + } + offset := query.Get("offset") + n, err := strconv.ParseInt(offset, 10, 64) + if err != nil || n < 0 { + return 0, fmt.Errorf("%s: '%s'", constants.ErrMsgInvalidOffset, offset) + } + return n, nil +} + func isAppend(r *http.Request) bool { return r.URL.Query().Get("op") == "append" } diff --git a/weed/server/filer_server_handlers_write_autochunk_save_inside_test.go b/weed/server/filer_server_handlers_write_autochunk_save_inside_test.go new file mode 100644 index 0000000000..dacf546c30 --- /dev/null +++ b/weed/server/filer_server_handlers_write_autochunk_save_inside_test.go @@ -0,0 +1,263 @@ +package weed_server + +import ( + "bytes" + "context" + "crypto/fips140" + "errors" + "net/http" + "net/http/httptest" + "path" + "strings" + "testing" + "time" + + "github.com/seaweedfs/seaweedfs/weed/filer" + "github.com/seaweedfs/seaweedfs/weed/operation" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/seaweedfs/seaweedfs/weed/util/constants" +) + +func TestFilerSaveInsidePutStoresInlineContent(t *testing.T) { + ctx := context.Background() + const filePath = "/etc/targets.json" + content := []byte(`{"targets":[]}`) + f := newRenameTestFiler(t, newRenameTestStore()) + fs, uploaded := newInlineAppendUploadServer(t, f, 0, 1) + + // GODEBUG=fips140=only refuses MD5, so the server neither checks nor reports one. + md5Checked := !fips140.Enforced() + wantMD5 := util.Md5(content) + r := httptest.NewRequest(http.MethodPut, filePath, bytes.NewReader(content)) + if md5Checked { + r.Header.Set("Content-Md5", util.Base64Encode(wantMD5)) + } + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true}) + if recorder.Code != http.StatusCreated { + t.Fatalf("PUT status = %d, body %s", recorder.Code, recorder.Body.String()) + } + if got := recorder.Header().Get("Content-MD5"); md5Checked && got != util.Base64Encode(wantMD5) { + t.Fatalf("Content-MD5 = %q, want %q", got, util.Base64Encode(wantMD5)) + } + if uploaded.count() != 0 { + t.Fatalf("saveInside PUT uploaded %d chunks", uploaded.count()) + } + saved, err := f.FindEntry(ctx, filePath) + if err != nil { + t.Fatalf("find saved entry: %v", err) + } + if !bytes.Equal(saved.Content, content) || len(saved.GetChunks()) != 0 || saved.FileSize != uint64(len(content)) { + t.Fatalf("saved entry: content=%q chunks=%d size=%d, want inline %q", saved.Content, len(saved.GetChunks()), saved.FileSize, content) + } + if md5Checked && !bytes.Equal(saved.Md5, wantMD5) { + t.Fatalf("saved MD5 = %x, want %x", saved.Md5, wantMD5) + } +} + +func TestFilerPutOutsideSaveInsideStillChunks(t *testing.T) { + ctx := context.Background() + const filePath = "/data/targets.json" + content := []byte(`{"targets":[]}`) + f := newRenameTestFiler(t, newRenameTestStore()) + fs, uploaded := newInlineAppendUploadServer(t, f, 0, 1) + + r := httptest.NewRequest(http.MethodPut, filePath, bytes.NewReader(content)) + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{}) + if recorder.Code != http.StatusCreated { + t.Fatalf("PUT status = %d, body %s", recorder.Code, recorder.Body.String()) + } + saved, err := f.FindEntry(ctx, filePath) + if err != nil { + t.Fatalf("find saved entry: %v", err) + } + if len(saved.Content) != 0 || len(saved.GetChunks()) != 1 || uploaded.count() != 1 { + t.Fatalf("saved entry: content=%q chunks=%d uploaded=%d, want one chunk", saved.Content, len(saved.GetChunks()), uploaded.count()) + } +} + +func TestFilerSaveInsidePutRejectsBadDigest(t *testing.T) { + if fips140.Enforced() { + t.Skip("GODEBUG=fips140=only refuses MD5") + } + ctx := context.Background() + const filePath = "/etc/targets.json" + f := newRenameTestFiler(t, newRenameTestStore()) + fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}} + + r := httptest.NewRequest(http.MethodPut, filePath, bytes.NewReader([]byte(`{"targets":[]}`))) + r.Header.Set("Content-Md5", util.Base64Encode([]byte("not the digest"))) + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true}) + if recorder.Code != http.StatusBadRequest { + t.Fatalf("bad digest status = %d, want %d", recorder.Code, http.StatusBadRequest) + } + if _, err := f.FindEntry(ctx, filePath); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("bad digest still saved the entry: %v", err) + } +} + +// A saveInside PUT rejects what a saveInside POST rejects: appending to a +// chunked file, and an offset into content that is always written whole. +func TestFilerSaveInsidePutPartialWritesRejected(t *testing.T) { + ctx := context.Background() + const filePath = "/etc/chunked.json" + store := newRenameTestStore() + f := newRenameTestFiler(t, store) + if err := store.InsertEntry(ctx, &filer.Entry{ + FullPath: util.FullPath(filePath), + Attr: filer.Attr{Mtime: time.Unix(1, 0), Crtime: time.Unix(1, 0), FileSize: 4}, + Chunks: []*filer_pb.FileChunk{{FileId: "1,00000001", Offset: 0, Size: 4}}, + }); err != nil { + t.Fatalf("insert chunk-backed entry: %v", err) + } + fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}} + + for _, query := range []string{"?op=append", "?offset=2"} { + r := httptest.NewRequest(http.MethodPut, filePath+query, bytes.NewReader([]byte("new"))) + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true}) + if recorder.Code != http.StatusBadRequest { + t.Fatalf("%s status = %d, want %d: %s", query, recorder.Code, http.StatusBadRequest, recorder.Body.String()) + } + unchanged, err := f.FindEntry(ctx, filePath) + if err != nil { + t.Fatalf("find entry: %v", err) + } + if unchanged.FileSize != 4 || len(unchanged.GetChunks()) != 1 || len(unchanged.Content) != 0 { + t.Fatalf("%s changed the entry: size=%d chunks=%d content=%q", query, unchanged.FileSize, len(unchanged.GetChunks()), unchanged.Content) + } + } +} + +// A malformed ?offset is the client's mistake on both the inline and the chunk +// path, answered 400 before anything is read or stored. +func TestFilerPutInvalidOffsetIsBadRequest(t *testing.T) { + ctx := context.Background() + f := newRenameTestFiler(t, newRenameTestStore()) + fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}} + + cases := []struct { + target string + saveInside bool + }{ + {"/etc/a.json?offset=-1", true}, + {"/etc/a.json?offset=abc", true}, + {"/etc/a.json?offset=99999999999999999999", true}, + {"/etc/a.json?offset=", true}, + {"/data/a.bin?offset=-1", false}, + {"/data/a.bin?offset=abc", false}, + {"/data/a.bin?offset=99999999999999999999", false}, + {"/data/a.bin?op=append&offset=5", false}, + } + for _, tc := range cases { + r := httptest.NewRequest(http.MethodPut, tc.target, bytes.NewReader([]byte("x"))) + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: tc.saveInside}) + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), constants.ErrMsgInvalidOffset) { + t.Fatalf("%s: status %d body %s, want 400 invalid offset", tc.target, recorder.Code, recorder.Body.String()) + } + } + + r := httptest.NewRequest(http.MethodPut, "/etc/a.json?offset=0", bytes.NewReader([]byte("x"))) + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true}) + if recorder.Code != http.StatusCreated { + t.Fatalf("offset=0: status %d body %s, want 201", recorder.Code, recorder.Body.String()) + } + saved, err := f.FindEntry(ctx, "/etc/a.json") + if err != nil || !bytes.Equal(saved.Content, []byte("x")) { + t.Fatalf("offset=0 entry = %v, %v; want inline content", saved, err) + } +} + +// A body stored inline is held in memory whole, so it is bounded: at the bound +// it is stored, one byte over it is refused with 413 whether or not its length +// was declared, and nothing is stored. +func TestFilerSaveInsideBodyIsBounded(t *testing.T) { + ctx := context.Background() + f := newRenameTestFiler(t, newRenameTestStore()) + fs := &FilerServer{filer: f, option: &FilerOption{MaxMB: 1}} + atLimit := bytes.Repeat([]byte("a"), saveInsideMaxBytes) + overLimit := append(atLimit, 'b') + + r := httptest.NewRequest(http.MethodPut, "/etc/at-limit.json", bytes.NewReader(atLimit)) + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true}) + if recorder.Code != http.StatusCreated { + t.Fatalf("PUT at the bound: status %d, want 201", recorder.Code) + } + if saved, err := f.FindEntry(ctx, "/etc/at-limit.json"); err != nil || len(saved.Content) != saveInsideMaxBytes || len(saved.GetChunks()) != 0 { + t.Fatalf("PUT at the bound was not stored inline: %v", err) + } + + for _, tc := range []struct { + name string + request func() *http.Request + }{ + {"declared length", func() *http.Request { + return httptest.NewRequest(http.MethodPut, "/etc/over.json", bytes.NewReader(overLimit)) + }}, + {"unknown length", func() *http.Request { + r := httptest.NewRequest(http.MethodPut, "/etc/over.json", bytes.NewReader(overLimit)) + r.ContentLength = -1 + return r + }}, + {"multipart POST", func() *http.Request { + return saveInsideMultipartRequest(t, "/etc/", "over.json", overLimit) + }}, + } { + r := tc.request() + recorder := httptest.NewRecorder() + fs.autoChunk(ctx, recorder, r, r.ContentLength, &operation.StorageOption{SaveInside: true}) + if recorder.Code != http.StatusRequestEntityTooLarge || !strings.Contains(recorder.Body.String(), constants.ErrMsgSaveInsideTooLarge) { + t.Fatalf("%s over the bound: status %d body %.200s, want 413", tc.name, recorder.Code, recorder.Body.String()) + } + if _, err := f.FindEntry(ctx, "/etc/over.json"); !errors.Is(err, filer_pb.ErrNotFound) { + t.Fatalf("%s over the bound stored an entry: %v", tc.name, err) + } + } +} + +// Only entries in /etc are kept inline: a sibling such as /etcd-backup/ holds +// ordinary data and keeps the chunk path, while a multipart POST to the /etc +// directory itself lands a file inside it. +func TestFilerPutUnderEtcSiblingStillChunks(t *testing.T) { + ctx := context.Background() + content := []byte("snapshot") + f := newRenameTestFiler(t, newRenameTestStore()) + fs, uploaded := newInlineAppendUploadServer(t, f, 0, 1) + for _, tc := range []struct { + target, saved string + inline bool + }{ + {"/etc/targets.json", "/etc/targets.json", true}, + {"/etc", "/etc/posted.json", true}, + {"/etcd-backup/snap.db", "/etcd-backup/snap.db", false}, + {"/etcetera", "/etcetera", false}, + } { + before := uploaded.count() + r := httptest.NewRequest(http.MethodPut, tc.target, bytes.NewReader(content)) + if tc.target != tc.saved { + r = saveInsideMultipartRequest(t, tc.target, path.Base(tc.saved), content) + } + recorder := httptest.NewRecorder() + fs.PostHandler(recorder, r, r.ContentLength) + if recorder.Code != http.StatusCreated { + t.Fatalf("%s %s status = %d, body %s", r.Method, tc.target, recorder.Code, recorder.Body.String()) + } + saved, err := f.FindEntry(ctx, util.FullPath(tc.saved)) + if err != nil { + t.Fatalf("find %s: %v", tc.saved, err) + } + chunks := uploaded.count() - before + if tc.inline && (!bytes.Equal(saved.Content, content) || len(saved.GetChunks()) != 0 || chunks != 0) { + t.Fatalf("%s %s: content=%q chunks=%d uploaded=%d, want inline", r.Method, tc.target, saved.Content, len(saved.GetChunks()), chunks) + } + if !tc.inline && (len(saved.Content) != 0 || len(saved.GetChunks()) != 1 || chunks != 1) { + t.Fatalf("%s %s: content=%q chunks=%d uploaded=%d, want one chunk", r.Method, tc.target, saved.Content, len(saved.GetChunks()), chunks) + } + } +} diff --git a/weed/server/filer_server_handlers_write_upload.go b/weed/server/filer_server_handlers_write_upload.go index bdd74ce8e2..d1361a43b8 100644 --- a/weed/server/filer_server_handlers_write_upload.go +++ b/weed/server/filer_server_handlers_write_upload.go @@ -9,7 +9,6 @@ import ( "hash" "io" "net/http" - "strconv" "sync" "time" @@ -21,6 +20,7 @@ import ( "github.com/seaweedfs/seaweedfs/weed/security" "github.com/seaweedfs/seaweedfs/weed/stats" "github.com/seaweedfs/seaweedfs/weed/util" + "github.com/seaweedfs/seaweedfs/weed/util/constants" ) var bufPool = sync.Pool{ @@ -30,22 +30,15 @@ var bufPool = sync.Pool{ } func (fs *FilerServer) uploadRequestToChunks(ctx context.Context, w http.ResponseWriter, r *http.Request, reader io.Reader, chunkSize int32, fileName, contentType string, contentLength int64, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) { - query := r.URL.Query() - isAppend := isAppend(r) - if query.Has("offset") { - offset := query.Get("offset") - offsetInt, err := strconv.ParseInt(offset, 10, 64) - if err != nil || offsetInt < 0 { - err = fmt.Errorf("invalid 'offset': '%s'", offset) - return nil, nil, 0, err, nil - } - if isAppend && offsetInt > 0 { - err = fmt.Errorf("cannot set offset when op=append") - return nil, nil, 0, err, nil - } - chunkOffset = offsetInt + offset, err := requestOffset(r) + if err != nil { + return nil, nil, 0, err, nil } + if isAppend && offset > 0 { + return nil, nil, 0, fmt.Errorf("%s: cannot set offset when op=append", constants.ErrMsgInvalidOffset), nil + } + chunkOffset = offset if isAppend && !so.SaveInside { fullPath := fs.fixFilePath(ctx, r, fileName) diff --git a/weed/util/constants/filer.go b/weed/util/constants/filer.go index e550f95fa8..144717096f 100644 --- a/weed/util/constants/filer.go +++ b/weed/util/constants/filer.go @@ -12,6 +12,10 @@ const ( ErrMsgAppendInlineMode = "append to inline content with this storage mode is not supported" ErrMsgOffsetWriteInline = "offset write to inline small file is not supported yet" ErrMsgPartialWriteRemoteOnly = "append or offset write to a remote-only entry is not supported; cache it first" + // Prefix of the error for a malformed or disallowed ?offset. + ErrMsgInvalidOffset = "invalid 'offset'" + // Prefix of the error for a saveInside body over the inline size bound. + ErrMsgSaveInsideTooLarge = "content saved inside the entry is too large" // Suffix appended to a path, e.g. "/buckets/b/foo/bar is a file" ErrMsgIsAFile = " is a file" // Prefix + suffix, e.g. "existing /buckets/b/foo is a directory"