1
0
mirror of https://github.com/golang/go synced 2024-11-17 12:24:51 -07:00

net/http: ignore ranges if the content is empty in serveContent

Fixes #54794

Change-Id: I6f2b7b86b82ea27b9d53cf989daa21cb8ace13da
Reviewed-on: https://go-review.googlesource.com/c/go/+/427195
Run-TryBot: Damien Neil <dneil@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
This commit is contained in:
Jorropo 2022-08-31 22:25:51 +02:00 committed by Damien Neil
parent 7ddbadb397
commit edfe078349
2 changed files with 100 additions and 65 deletions

View File

@ -254,19 +254,34 @@ func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time,
Error(w, err.Error(), StatusInternalServerError)
return
}
if size < 0 {
// Should never happen but just to be sure
Error(w, "negative content size computed", StatusInternalServerError)
return
}
// handle Content-Range header.
sendSize := size
var sendContent io.Reader = content
if size >= 0 {
ranges, err := parseRange(rangeReq, size)
if err != nil {
if err == errNoOverlap {
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
switch err {
case nil:
case errNoOverlap:
if size == 0 {
// Some clients add a Range header to all requests to
// limit the size of the response. If the file is empty,
// ignore the range header and respond with a 200 rather
// than a 416.
ranges = nil
break
}
w.Header().Set("Content-Range", fmt.Sprintf("bytes */%d", size))
fallthrough
default:
Error(w, err.Error(), StatusRequestedRangeNotSatisfiable)
return
}
if sumRangesSize(ranges) > size {
// The total number of bytes in all the ranges
// is larger than the size of the file by
@ -329,7 +344,6 @@ func serveContent(w ResponseWriter, r *Request, name string, modtime time.Time,
if w.Header().Get("Content-Encoding") == "" {
w.Header().Set("Content-Length", strconv.FormatInt(sendSize, 10))
}
}
w.WriteHeader(code)

View File

@ -218,6 +218,27 @@ func TestServeFileDirPanicEmptyPath(t *testing.T) {
}
}
// Tests that ranges are ignored with serving empty content. (Issue 54794)
func TestServeContentWithEmptyContentIgnoreRanges(t *testing.T) {
for _, r := range []string{
"bytes=0-128",
"bytes=1-",
} {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("Range", r)
ServeContent(rec, req, "nothing", time.Now(), bytes.NewReader(nil))
res := rec.Result()
if res.StatusCode != 200 {
t.Errorf("code = %v; want 200", res.Status)
}
bodyLen := rec.Body.Len()
if bodyLen != 0 {
t.Errorf("body.Len() = %v; want 0", res.Status)
}
}
}
var fsRedirectTestData = []struct {
original, redirect string
}{