Skip to content

Commit

Permalink
Do not force content length to 0 if already set. Closes #564
Browse files Browse the repository at this point in the history
  • Loading branch information
rdeago committed Jun 14, 2022
1 parent 5883e52 commit 4fcea64
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions src/EmbedIO/Net/Internal/HttpListenerResponse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -194,25 +194,37 @@ internal MemoryStream SendHeaders(bool closing)
Headers.Add(HttpHeaderNames.Date, HttpDate.Format(DateTime.UtcNow));
}

if (closing)
// HTTP did not support chunked transfer encoding before version 1.1;
// besides, there's no point in setting transfer encoding at all without a request body.
if (closing || ProtocolVersion < HttpVersion.Version11)
{
Headers[HttpHeaderNames.ContentLength] = "0";
_chunked = false;
}
else

// Was content length set to a valid value, AND chunked encoding not set?
// Note that this does not mean that a response body _will_ be sent
// as this could be the response to a HEAD request.
var haveContentLength = !_chunked
&& Headers.ContainsKey(HttpHeaderNames.ContentLength)
&& long.TryParse(Headers[HttpHeaderNames.ContentLength], NumberStyles.None, CultureInfo.InvariantCulture, out var contentLength)
&& contentLength >= 0L;

if (!haveContentLength)
{
if (ProtocolVersion < HttpVersion.Version11)
// Content length could have been set to an invalid value (e.g. "-1")
// so we must either force it to 0, or remove the header completely.
if (closing)
{
_chunked = false;
// Content length was not explicitly set to a valid value,
// and there is no request body.
Headers[HttpHeaderNames.ContentLength] = "0";
}

var haveContentLength = !_chunked
&& Headers.ContainsKey(HttpHeaderNames.ContentLength)
&& long.TryParse(Headers[HttpHeaderNames.ContentLength], out var contentLength)
&& contentLength >= 0L;

if (!haveContentLength)
else
{
// Content length was not explicitly set to a valid value,
// and we're going to send a request body.
// - Remove possibly invalid Content-Length header
// - Enable chunked transfer encoding for HTTP 1.1
Headers.Remove(HttpHeaderNames.ContentLength);
if (ProtocolVersion >= HttpVersion.Version11)
{
Expand Down

0 comments on commit 4fcea64

Please sign in to comment.