Skip to content

Commit

Permalink
http: don't write error to socket
Browse files Browse the repository at this point in the history
The state of the connection is unknown at this point and
writing to it can corrupt client state before it is aware
of an error.

PR-URL: #34465
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
ronag authored and MylesBorins committed Jul 27, 2020
1 parent cc279db commit 9b91467
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 3 deletions.
4 changes: 2 additions & 2 deletions doc/api/http.md
Expand Up @@ -1071,8 +1071,8 @@ type other than {net.Socket}.

Default behavior is to try close the socket with a HTTP '400 Bad Request',
or a HTTP '431 Request Header Fields Too Large' in the case of a
[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable it is
immediately destroyed.
[`HPE_HEADER_OVERFLOW`][] error. If the socket is not writable or has already
written data it is immediately destroyed.

`socket` is the [`net.Socket`][] object that the error originated from.

Expand Down
2 changes: 1 addition & 1 deletion lib/_http_server.js
Expand Up @@ -599,7 +599,7 @@ function socketOnError(e) {
this.on('error', noop);

if (!this.server.emit('clientError', e, this)) {
if (this.writable) {
if (this.writable && this.bytesWritten === 0) {
const response = e.code === 'HPE_HEADER_OVERFLOW' ?
requestHeaderFieldsTooLargeResponse : badRequestResponse;
this.write(response);
Expand Down
31 changes: 31 additions & 0 deletions test/parallel/test-http-header-badrequest.js
@@ -0,0 +1,31 @@
'use strict';
const { mustCall } = require('../common');
const assert = require('assert');
const { createServer } = require('http');
const { createConnection } = require('net');

const server = createServer();

server.on('request', mustCall((req, res) => {
res.write('asd', () => {
res.socket.emit('error', new Error('kaboom'));
});
}));

server.listen(0, mustCall(() => {
const c = createConnection(server.address().port);
let received = '';

c.on('connect', mustCall(() => {
c.write('GET /blah HTTP/1.1\r\n\r\n');
}));
c.on('data', mustCall((data) => {
received += data.toString();
}));
c.on('end', mustCall(() => {
// Should not include anything else after asd.
assert.strictEqual(received.indexOf('asd\r\n'), received.length - 5);
c.end();
}));
c.on('close', mustCall(() => server.close()));
}));

0 comments on commit 9b91467

Please sign in to comment.