Say I started writing to the response body, but there was some error, and I need to indicate that it's an HTTP 500 even if an HTTP 200 OK header was already written as a header... How can I write something to the body of the response that's guaranteed to be malformed so that the response is interpreted as some sort of error by the client?
1 Answers
In general, this is impossible. Some clients only care about the response header, and may stop paying attention to what you send after the header.
But with certain clients, in certain cases, this may be possible.
I assume HTTP/1.1 here. HTTP/2 probably gives even more opportunities, because there’s more to screw up in the protocol, and the implementations are often stricter. Conversely, HTTP/1.0 is dumber and laxer, so harder to break.
Close the connection before the end of response, as indicated by your framing. If your response is framed with
Content-Length: 100
, close before you’ve sent the 100th byte of payload. If your response is framed withTransfer-Encoding: chunked
, close before you’ve sent the final empty chunk. If the client expects to receive the entire payload, it may (and should) treat this as an error. But some won’t, including very popular client libraries.If the payload is in a structured format, like JSON or XML, then do the same as 1, but before closing, send something that would disrupt that format. For example, no valid JSON text can end with
{
. Even if the client doesn’t recognize the incomplete payload as an error, it might then fail on trying to parse it.Same as 1, but instead of closing the connection, just stop sending data. The client will “hang” until its receive operation times out, which it may treat as an error. This may be a bad idea if the client is operated by someone who is not prepared for such extravagant timeouts.
Only with
Transfer-Encoding: chunked
: Same as 3, but instead of hanging, send bogus very long chunks and/or keep sending chunks indefinitely, until the client gives up or crashes. Probably a very bad idea, bordering on malicious.

- 1
- 1

- 11,840
- 2
- 38
- 49
-
using a plain socket connection on barebones Node.js server, how can I close the socket? Is it `socket.destroy()`? – May 12 '18 at 00:53