Files
seaweedfs/weed/storage/needle/needle_parse_upload.go
T
7c33a8449f volume: check a CRC32C of each chunk upload, in every digest mode (#12999)
* volume: check a CRC32C of each chunk upload, in every digest mode

In sha256 digest mode the uploader sends no Content-MD5, so the volume
server and its replicas store a chunk without checking that its bytes
arrived as sent. The uploader now sends X-Seaweed-Content-Crc32c, the
std-base64 of the big-endian CRC32C of the bytes Content-MD5 is checked
against (the file data after undoing Content-Encoding: gzip; the
ciphertext for ciphered chunks), in both digest modes. Uploads that
forward a stored needle (IsReplication) carry only a value the primary
volume server checked.

The Go and Rust volume servers refuse a mismatch or a malformed value
with 400, as they refuse a wrong Content-MD5, and forward the checked
value to replicas, which check it again. A gzipped upload without
Content-MD5 is checksummed while its size is counted, without holding
the uncompressed bytes. Servers that predate the header ignore it.

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

* volume(rs): keep the first part's headers when no part has a filename

Go's parseUpload falls back to the first multipart part with its
Content-Type, Content-MD5 and Content-Encoding. The Rust fallback dropped
them, so a gzipped part without a filename was stored as plain bytes and
its X-Seaweed-Content-Crc32c was checked against the compressed body.

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

* volume(rs): read the RFC 2231 filename* of a multipart part

Go's uploader names a part with mime.FormatMediaType, which writes
filename*=utf-8''... for a non-ASCII name, and Go's Part.FileName()
decodes it. multer reads only filename, so the Rust volume server missed
the file part and lost its name, gzip encoding and Content-MD5.

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

* volume: send replicas the CRC32C of a rewritten JPEG

Once the orientation fix rewrites a JPEG, the client's CRC32C no longer
covers the bytes the primary forwards, so the replica got no checksum.
Send the CRC32C of the stored bytes instead, in Go and Rust.

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

* volume(rs): read filename* only outside quoted parameter values

A quoted name such as "note; filename*=utf-8''decoy" split at its
semicolon and was taken for the part's filename.

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

* volume(rs): refuse a decoded filename* with control characters

A percent-encoded CR/LF in the name would end the header block of the
part the primary forwards to its replicas.

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

* volume: read the forwarded CRC32C with the replica response in the test

A failing assertion left the CRC32C in the one-slot channel, so the next
subtest's replica blocked instead of the test reporting the failure.

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

* volume(rs): use naïve for the non-ASCII filename test data

codespell reads the ASCII part of café as a misspelling of calf.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-25 12:53:04 -08:00

360 lines
10 KiB
Go

package needle
import (
"bytes"
"crypto/fips140"
"crypto/md5"
"encoding/base64"
"fmt"
"hash/crc32"
"io"
"mime"
"net/http"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// maxEagerPreGrow caps how many bytes ParseUpload is willing to pre-allocate
// from a request's announced Content-Length. Large enough to skip a few
// rounds of bytes.Buffer.ReadFrom geometric grow on typical small uploads;
// small enough that a misreported Content-Length or a slow/idle client can
// only ever waste this much memory per request. Bigger uploads fall back to
// the standard ReadFrom-grow path for the remainder.
const maxEagerPreGrow = 4 * 1024 * 1024
// eagerPreGrow ensures bytesBuffer has at least min(contentLength, sizeLimit,
// maxEagerPreGrow) bytes of capacity, so the bytes.Buffer.ReadFrom pumps
// inside parseUpload below skip the first round(s) of geometric grow on the
// common upload sizes — see #6541. The cap policy is the load-bearing piece
// here; it's extracted so unit tests can exercise the policy directly
// without spinning a real http upload.
func eagerPreGrow(bytesBuffer *bytes.Buffer, contentLength, sizeLimit int64) {
if contentLength <= 0 || contentLength > sizeLimit {
return
}
grow := contentLength
if grow > maxEagerPreGrow {
grow = maxEagerPreGrow
}
bytesBuffer.Grow(int(grow))
}
type ParsedUpload struct {
FileName string
Data []byte
bytesBuffer *bytes.Buffer
MimeType string
PairMap map[string]string
IsGzipped bool
// IsZstd bool
OriginalDataSize int
ModifiedTime uint64
Ttl *TTL
IsChunkedFile bool
UncompressedData []byte
ContentMd5 string
}
func ParseUpload(r *http.Request, sizeLimit int64, bytesBuffer *bytes.Buffer) (pu *ParsedUpload, e error) {
bytesBuffer.Reset()
eagerPreGrow(bytesBuffer, r.ContentLength, sizeLimit)
pu = &ParsedUpload{bytesBuffer: bytesBuffer}
pu.PairMap = make(map[string]string)
for k, v := range r.Header {
if len(v) > 0 && strings.HasPrefix(k, PairNamePrefix) {
pu.PairMap[k] = v[0]
}
}
// glog.V(4).Infof("ParseUpload: r.URL=%s, Content-MD5 header=%s", r.URL.String(), r.Header.Get("Content-MD5"))
e = parseUpload(r, sizeLimit, pu)
if e != nil {
return
}
pu.ModifiedTime, _ = strconv.ParseUint(r.FormValue("ts"), 10, 64)
pu.Ttl, _ = ReadTTL(r.FormValue("ttl"))
pu.OriginalDataSize = len(pu.Data)
pu.UncompressedData = pu.Data
expectedCrc32c := r.Header.Get(ContentCrc32cHeader)
var streamedCrc32c *CRC
// println("received data", len(pu.Data), "isGzipped", pu.IsGzipped, "mime", pu.MimeType, "name", pu.FileName)
if pu.IsGzipped {
// MD5 check needs the uncompressed bytes; otherwise just count
// the gunzip stream — see #6541.
needMD5 := r.Header.Get("Content-MD5") != "" || pu.ContentMd5 != ""
if needMD5 {
if unzipped, err := util.DecompressData(pu.Data); err == nil {
pu.OriginalDataSize = len(unzipped)
pu.UncompressedData = unzipped
}
} else {
n, crc, err := gunzipCount(pu.Data, expectedCrc32c != "")
if err == nil {
pu.OriginalDataSize = int(n)
streamedCrc32c = crc
}
}
} else if r.FormValue("type") != "replicate" {
// replica writes must keep the source needle's compression state, not re-derive it
ext := filepath.Ext(pu.FileName)
mimeType := pu.MimeType
if mimeType == "" {
mimeType = http.DetectContentType(pu.Data)
}
// println("detected mimetype to", pu.MimeType)
if mimeType == "application/octet-stream" {
mimeType = ""
}
if shouldBeCompressed, iAmSure := util.IsCompressableFileType(ext, mimeType); shouldBeCompressed && iAmSure {
// println("ext", ext, "iAmSure", iAmSure, "shouldBeCompressed", shouldBeCompressed, "mimeType", pu.MimeType)
if compressedData, err := util.GzipData(pu.Data); err == nil {
if len(compressedData)*10 < len(pu.Data)*9 {
pu.Data = compressedData
pu.IsGzipped = true
}
// println("gzipped data size", len(compressedData))
}
}
}
// verify Content-MD5
expectedChecksum := r.Header.Get("Content-MD5")
if expectedChecksum == "" {
expectedChecksum = pu.ContentMd5
}
if expectedChecksum != "" && fips140.Enforced() {
// fips140=only refuses MD5: keep the client's digest unchecked.
pu.ContentMd5 = expectedChecksum
} else if expectedChecksum != "" {
h := md5.New()
h.Write(pu.UncompressedData)
pu.ContentMd5 = base64.StdEncoding.EncodeToString(h.Sum(nil))
if expectedChecksum != pu.ContentMd5 {
e = fmt.Errorf("Content-MD5 did not match md5 of file data expected [%s] received [%s] size %d", expectedChecksum, pu.ContentMd5, len(pu.UncompressedData))
return
}
}
if expectedCrc32c != "" {
var actual CRC
if streamedCrc32c != nil {
actual = *streamedCrc32c
} else {
actual = NewCRC(pu.UncompressedData)
}
e = checkContentCrc32c(expectedCrc32c, actual, pu.OriginalDataSize)
}
return
}
// gunzipCount counts the uncompressed bytes of a gzipped upload without
// holding them, and checksums them on the way when withCrc is set, so a
// ContentCrc32cHeader check costs no allocation (see #6541).
func gunzipCount(data []byte, withCrc bool) (n int64, crc *CRC, err error) {
if !withCrc {
n, err = util.GunzipStream(io.Discard, bytes.NewReader(data))
return
}
h := crc32.New(table)
if n, err = util.GunzipStream(h, bytes.NewReader(data)); err == nil {
sum := CRC(h.Sum32())
crc = &sum
}
return
}
func parseUpload(r *http.Request, sizeLimit int64, pu *ParsedUpload) (e error) {
defer func() {
if e != nil && r.Body != nil {
io.Copy(io.Discard, r.Body)
r.Body.Close()
}
}()
contentType := r.Header.Get("Content-Type")
var dataSize int64
if r.Method == http.MethodPost && (contentType == "" || strings.Contains(contentType, "form-data")) {
if r.Form == nil {
_ = r.ParseForm()
}
form, fe := r.MultipartReader()
if fe != nil {
glog.V(0).Infoln("MultipartReader [ERROR]", fe)
e = fe
return
}
saveControlField := func(name string, data []byte) {
if name != "type" && name != "fsync" {
return
}
if len(r.Form[name]) == 0 {
// Longer values cannot match either control marker.
if len(data) > len("replicate")+1 {
data = data[:len("replicate")+1]
}
r.Form[name] = []string{string(data)}
}
}
// first multi-part item
part, fe := form.NextPart()
if fe != nil {
glog.V(0).Infoln("Reading Multi part [ERROR]", fe)
e = fe
return
}
pu.FileName = part.FileName()
if pu.FileName != "" {
pu.FileName = util.CleanWindowsPathBase(pu.FileName)
}
dataSize, e = pu.bytesBuffer.ReadFrom(io.LimitReader(part, sizeLimit+1))
if e != nil {
glog.V(0).Infoln("Reading Content [ERROR]", e)
return
}
if dataSize == sizeLimit+1 {
e = fmt.Errorf("file over the limited %d bytes", sizeLimit)
return
}
pu.Data = pu.bytesBuffer.Bytes()
if part.FileName() == "" {
saveControlField(part.FormName(), pu.Data)
}
contentType = part.Header.Get("Content-Type")
pu.ContentMd5 = part.Header.Get("Content-MD5")
// Find the first file and retain control fields before or after it.
for {
part2, fe := form.NextPart()
if fe != nil {
break // no more or on error, just safely break
}
fName := part2.FileName()
// found the first <file type> multi-part has filename
if pu.FileName == "" && fName != "" {
pu.bytesBuffer.Reset()
dataSize2, fe2 := pu.bytesBuffer.ReadFrom(io.LimitReader(part2, sizeLimit+1))
if fe2 != nil {
glog.V(0).Infoln("Reading Content [ERROR]", fe2)
e = fe2
return
}
if dataSize2 == sizeLimit+1 {
e = fmt.Errorf("file over the limited %d bytes", sizeLimit)
return
}
// update
pu.Data = pu.bytesBuffer.Bytes()
pu.FileName = util.CleanWindowsPathBase(fName)
contentType = part2.Header.Get("Content-Type")
pu.ContentMd5 = part2.Header.Get("Content-MD5")
part = part2
continue
}
if fName == "" && (part2.FormName() == "type" || part2.FormName() == "fsync") {
value, err := io.ReadAll(io.LimitReader(part2, int64(len("replicate")+1)))
if err != nil {
return err
}
saveControlField(part2.FormName(), value)
}
}
pu.IsGzipped = part.Header.Get("Content-Encoding") == "gzip"
// pu.IsZstd = part.Header.Get("Content-Encoding") == "zstd"
} else {
disposition := r.Header.Get("Content-Disposition")
if strings.Contains(disposition, "name=") {
if !strings.HasPrefix(disposition, "inline") && !strings.HasPrefix(disposition, "attachment") {
disposition = "attachment; " + disposition
}
_, mediaTypeParams, err := mime.ParseMediaType(disposition)
if err == nil {
dpFilename, hasFilename := mediaTypeParams["filename"]
dpName, hasName := mediaTypeParams["name"]
if hasFilename {
pu.FileName = dpFilename
} else if hasName {
pu.FileName = dpName
}
}
} else {
pu.FileName = ""
}
if pu.FileName != "" {
pu.FileName = util.CleanWindowsPathBase(pu.FileName)
} else {
pu.FileName = path.Base(r.URL.Path)
}
dataSize, e = pu.bytesBuffer.ReadFrom(io.LimitReader(r.Body, sizeLimit+1))
if e != nil {
glog.V(0).Infoln("Reading Content [ERROR]", e)
return
}
if dataSize == sizeLimit+1 {
e = fmt.Errorf("file over the limited %d bytes", sizeLimit)
return
}
pu.Data = pu.bytesBuffer.Bytes()
pu.MimeType = contentType
pu.IsGzipped = r.Header.Get("Content-Encoding") == "gzip"
// pu.IsZstd = r.Header.Get("Content-Encoding") == "zstd"
}
pu.IsChunkedFile, _ = strconv.ParseBool(r.FormValue("cm"))
if r.FormValue("type") == "replicate" {
pu.MimeType = contentType
} else if !pu.IsChunkedFile {
dotIndex := strings.LastIndex(pu.FileName, ".")
ext, mtype := "", ""
if dotIndex > 0 {
ext = strings.ToLower(pu.FileName[dotIndex:])
mtype = mime.TypeByExtension(ext)
}
if contentType != "" && contentType != "application/octet-stream" && mtype != contentType {
pu.MimeType = contentType // only return mime type if not deducible
} else if mtype != "" && pu.MimeType == "" && mtype != "application/octet-stream" {
pu.MimeType = mtype
}
}
return
}