From 4fcea64805e4bfa6256996177ec363a5820a9b49 Mon Sep 17 00:00:00 2001 From: Riccardo De Agostini Date: Thu, 9 Jun 2022 17:26:31 +0200 Subject: [PATCH] Do not force content length to 0 if already set. Closes #564 --- .../Net/Internal/HttpListenerResponse.cs | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/EmbedIO/Net/Internal/HttpListenerResponse.cs b/src/EmbedIO/Net/Internal/HttpListenerResponse.cs index ff029103..e9730083 100644 --- a/src/EmbedIO/Net/Internal/HttpListenerResponse.cs +++ b/src/EmbedIO/Net/Internal/HttpListenerResponse.cs @@ -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) {