Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/internal/http/agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -739,4 +739,5 @@ function asyncResetHandle(socket) {
module.exports = {
Agent,
globalAgent: getGlobalAgent(getOptionValue('--use-env-proxy') ? process.env : undefined, Agent),
hasPendingRead,
};
2 changes: 2 additions & 0 deletions lib/internal/http/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
20 changes: 15 additions & 5 deletions src/stream_wrap.cc
Original file line number Diff line number Diff line change
Expand Up @@ -357,17 +357,27 @@ void LibuvStreamWrap::HasPendingRead(const FunctionCallbackInfo<Value>& 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<uv_handle_t*>(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
Expand Down
110 changes: 110 additions & 0 deletions test/parallel/test-http-agent-free-socket-reuse-data-guard.js
Original file line number Diff line number Diff line change
@@ -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());
}
41 changes: 41 additions & 0 deletions test/parallel/test-http-agent-pending-read-before-flush.js
Original file line number Diff line number Diff line change
@@ -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();
}));
}));
}));
}));
41 changes: 41 additions & 0 deletions test/parallel/test-net-socket-has-pending-read-pipe.js
Original file line number Diff line number Diff line change
@@ -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();
}));
}
}));
Loading