diff --git a/lib/internal/http/agent.js b/lib/internal/http/agent.js index 013be05d1f9f..49f4ecb463a4 100644 --- a/lib/internal/http/agent.js +++ b/lib/internal/http/agent.js @@ -739,4 +739,5 @@ function asyncResetHandle(socket) { module.exports = { Agent, globalAgent: getGlobalAgent(getOptionValue('--use-env-proxy') ? process.env : undefined, Agent), + hasPendingRead, }; diff --git a/lib/internal/http/client.js b/lib/internal/http/client.js index 4e7479d3377a..887552127b1a 100644 --- a/lib/internal/http/client.js +++ b/lib/internal/http/client.js @@ -1234,6 +1234,8 @@ function onSocketNT(req, socket, err) { } _destroy(req, err || req[kError]); + } else if (Agent.hasPendingRead(socket)) { + onSocketNT(req, socket, new ConnResetException('socket hang up')); } else { tickOnSocket(req, socket); req._flush(); diff --git a/src/stream_wrap.cc b/src/stream_wrap.cc index a1416b18d466..b21a1f1a174e 100644 --- a/src/stream_wrap.cc +++ b/src/stream_wrap.cc @@ -357,17 +357,27 @@ void LibuvStreamWrap::HasPendingRead(const FunctionCallbackInfo& args) { if (!wrap->IsAlive() || wrap->IsClosing()) return; -#ifdef _WIN32 - // Only TCP sockets can be probed with recv() on Windows. - if (!wrap->is_tcp()) return; -#else if (!wrap->is_tcp() && !wrap->is_named_pipe()) return; -#endif uv_os_fd_t fd; if (uv_fileno(reinterpret_cast(wrap->stream()), &fd) != 0) return; +#ifdef _WIN32 + if (wrap->is_named_pipe()) { + // Named pipes cannot be probed with recv(): ask the pipe how many bytes + // are waiting. A failing probe (e.g. a broken pipe) counts as pending so + // the socket is not reused. + DWORD bytes_available = 0; + if (!PeekNamedPipe(fd, nullptr, 0, nullptr, &bytes_available, nullptr)) { + args.GetReturnValue().Set(true); + return; + } + args.GetReturnValue().Set(bytes_available > 0); + return; + } +#endif + char c; #ifdef _WIN32 // libuv puts TCP sockets in non-blocking mode and reads with zero-byte diff --git a/test/parallel/test-http-agent-free-socket-reuse-data-guard.js b/test/parallel/test-http-agent-free-socket-reuse-data-guard.js new file mode 100644 index 000000000000..e85e4ad1cb13 --- /dev/null +++ b/test/parallel/test-http-agent-free-socket-reuse-data-guard.js @@ -0,0 +1,110 @@ +'use strict'; + +// A reused keep-alive socket must reject unsolicited bytes that arrive after +// the previous response parser is detached but before the next request starts. + +const common = require('../common'); +const assert = require('assert'); +const { fork } = require('child_process'); +const http = require('http'); +const net = require('net'); + +if (process.argv[2] === 'server') { + const server = net.createServer((socket) => { + let buffered = ''; + + socket.on('error', () => socket.destroy()); + socket.on('data', (chunk) => { + buffered += chunk.toString('latin1'); + + while (buffered.includes('\r\n\r\n')) { + const end = buffered.indexOf('\r\n\r\n') + 4; + const request = buffered.slice(0, end); + buffered = buffered.slice(end); + + const requestLine = request.split('\r\n', 1)[0]; + + if (requestLine.startsWith('GET /first ')) { + socket.write( + 'HTTP/1.1 200 OK\r\n' + + 'Content-Length: 3\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + + 'one' + ); + + setTimeout(() => { + socket.write( + 'HTTP/1.1 200 OK\r\n' + + 'X-Unsolicited: yes\r\n' + + 'Content-Length: 6\r\n' + + 'Connection: keep-alive\r\n' + + '\r\n' + + 'EXTRA!' + ); + }, common.platformTimeout(20)); + } else if (requestLine.startsWith('GET /second ')) { + socket.write( + 'HTTP/1.1 200 OK\r\n' + + 'Content-Length: 3\r\n' + + 'Connection: close\r\n' + + '\r\n' + + 'two' + ); + } + } + }); + }); + + server.listen(0, '127.0.0.1', () => { + process.send({ event: 'listening', port: server.address().port }); + }); + return; +} + +function blockEventLoop(ms) { + const array = new Int32Array(new SharedArrayBuffer(4)); + Atomics.wait(array, 0, 0, ms); +} + +const child = fork(__filename, ['server'], { + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], +}); + +child.on('message', common.mustCall((message) => { + assert.strictEqual(message.event, 'listening'); + runClient(message.port); +}, 1)); + +function cleanup(agent) { + agent.destroy(); + child.kill(); +} + +function runClient(port) { + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + const options = { host: '127.0.0.1', port, agent }; + + http.get({ ...options, path: '/first' }, common.mustCall((res) => { + res.resume(); + res.on('end', common.mustCall(() => { + blockEventLoop(common.platformTimeout(120)); + process.nextTick(() => requestSecond(options, agent)); + })); + })); +} + +function requestSecond(options, agent) { + const req = http.get({ ...options, path: '/second' }, common.mustCall((res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { body += chunk; }); + res.on('end', common.mustCall(() => { + assert.strictEqual(res.headers['x-unsolicited'], undefined); + assert.strictEqual(body, 'two'); + cleanup(agent); + })); + })); + + req.on('error', common.mustNotCall()); +} diff --git a/test/parallel/test-http-agent-pending-read-before-flush.js b/test/parallel/test-http-agent-pending-read-before-flush.js new file mode 100644 index 000000000000..65c5615b6e96 --- /dev/null +++ b/test/parallel/test-http-agent-pending-read-before-flush.js @@ -0,0 +1,41 @@ +// Flags: --expose-internals +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const Agent = require('internal/http/agent'); + +const server = http.createServer(common.mustCall((req, res) => { + res.end(); +}, 1)); + +server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true }); + const options = { + host: '127.0.0.1', + port: server.address().port, + agent, + }; + const name = agent.getName(options); + const request1 = http.get(options, common.mustCall((response) => { + response.resume(); + })); + + request1.on('close', common.mustCall(() => { + process.nextTick(common.mustCall(() => { + assert.strictEqual(agent.freeSockets[name]?.length, 1); + + // The Agent has already selected a clean socket. Simulate data arriving + // before the client installs its parser and flushes the next request. + Agent.hasPendingRead = common.mustCall(() => true); + + const request2 = http.get(options, common.mustNotCall()); + request2.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ECONNRESET'); + agent.destroy(); + server.close(); + })); + })); + })); +})); diff --git a/test/parallel/test-net-socket-has-pending-read-pipe.js b/test/parallel/test-net-socket-has-pending-read-pipe.js new file mode 100644 index 000000000000..76055e433eb6 --- /dev/null +++ b/test/parallel/test-net-socket-has-pending-read-pipe.js @@ -0,0 +1,41 @@ +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { fork } = require('child_process'); +const net = require('net'); +const tmpdir = require('../common/tmpdir'); + +if (process.argv[2] === 'server') { + const server = net.createServer(common.mustCall((socket) => { + process.on('message', common.mustCall((message) => { + assert.strictEqual(message, 'write'); + socket.write('pending', () => process.send('written')); + })); + })); + + server.listen(process.argv[3], () => process.send('listening')); + return; +} + +tmpdir.refresh(); + +const child = fork(__filename, ['server', common.PIPE], { + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], +}); + +child.on('message', common.mustCallAtLeast((message) => { + if (message === 'listening') { + const socket = net.connect(common.PIPE, () => { + socket.pause(); + child.send('write'); + }); + + child.once('message', common.mustCall((message) => { + assert.strictEqual(message, 'written'); + assert.strictEqual(socket._handle.hasPendingRead(), true); + socket.destroy(); + child.kill(); + })); + } +}));