Commit 91f81708a1e for nodejs

commit 91f81708a1e4f25ba14f89107ba8552acba24838
Author: Paolo Insogna <paolo@cowtech.it>
Date:   Mon Nov 30 14:37:15 2026 +0100

    http: re-check pending data before flushing on reused sockets

    Re-check a reused socket for unread data immediately before flushing the
    request. Data can arrive between the Agent's selection of the socket and
    the next tick.

    Also probe Windows named pipes with PeekNamedPipe() so they are covered
    like on POSIX.

    Signed-off-by: Paolo Insogna <paolo@cowtech.it>
    Assisted-By: OpenAI:GPT-5.6 Sol <openai/gpt-5.6-sol>
    PR-URL: https://github.com/nodejs/node/pull/67606
    Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
    Reviewed-By: James M Snell <jasnell@gmail.com>

diff --git a/lib/internal/http/agent.js b/lib/internal/http/agent.js
index 20aef9f8376..e3ba81d0927 100644
--- a/lib/internal/http/agent.js
+++ b/lib/internal/http/agent.js
@@ -764,4 +764,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 cc82bc494ae..70a3d915e07 100644
--- a/lib/internal/http/client.js
+++ b/lib/internal/http/client.js
@@ -1240,6 +1240,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 a1416b18d46..b21a1f1a174 100644
--- a/src/stream_wrap.cc
+++ b/src/stream_wrap.cc
@@ -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
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 00000000000..e1fec5318e0
--- /dev/null
+++ b/test/parallel/test-http-agent-free-socket-reuse-data-guard.js
@@ -0,0 +1,103 @@
+'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'
+          );
+
+          process.once('message', () => {
+            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!'
+            );
+          });
+        }
+      }
+    });
+  });
+
+  server.listen(0, '127.0.0.1', () => {
+    process.send({ event: 'listening', port: server.address().port });
+  });
+  return;
+}
+
+function waitForPendingRead(socket) {
+  const deadline = Date.now() + common.platformTimeout(5000);
+  while (!socket._handle.hasPendingRead()) {
+    assert.ok(Date.now() < deadline, 'timed out waiting for pending data');
+  }
+}
+
+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(() => {
+      process.nextTick(() => requestSecond(options, agent));
+    }));
+  }));
+}
+
+function requestSecond(options, agent) {
+  const name = agent.getName(options);
+  assert.strictEqual(agent.freeSockets[name]?.length, 1);
+  const socket = agent.freeSockets[name][0];
+  const req = http.get({ ...options, path: '/second' }, common.mustNotCall());
+
+  req.on('error', common.mustCall((err) => {
+    assert.strictEqual(err.code, 'ECONNRESET');
+    cleanup(agent);
+  }));
+
+  child.send('send-unsolicited');
+  waitForPendingRead(socket);
+}
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 00000000000..65c5615b6e9
--- /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 00000000000..76055e433eb
--- /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();
+    }));
+  }
+}));