GeezerVison is showing github.com — http: ensure agent data guard works without I/O · nodejs/node@96c3ccb
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: lib/_http_agent.js +25Lines changed: 25 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -138,6 +138,18 @@ function installFreeSocketDataGuard(socket) { | 138 | 138 | } | 139 | 139 | } | 140 | 140 |
| | 141 | +// The data guard only runs when the event loop polls for I/O. Data that | | 142 | +// reached the OS socket buffer after the last poll has not been seen by it | | 143 | +// yet, so check for it directly before handing an idle socket to a request. | | 144 | +function hasPendingRead(socket) { | | 145 | + // A socket that is still connecting has nothing to read yet, and a pending | | 146 | + // connect error must be reported to the request rather than swallowed here. | | 147 | + if (socket.connecting) return false; | | 148 | + const handle = socket._handle; | | 149 | + return typeof handle?.hasPendingRead === 'function' && | | 150 | + handle.hasPendingRead() === true; | | 151 | +} | | 152 | + | 141 | 153 | function removeFreeSocketDataGuard(socket) { | 142 | 154 | if (socket[kFreeSocketDataGuard]) { | 143 | 155 | socket.removeListener('connect', socket[kFreeSocketDataGuard]); | @@ -214,6 +226,12 @@ function Agent(options) { | 214 | 226 |
| 215 | 227 | const requests = this.requests[name]; | 216 | 228 | if (requests?.length) { | | 229 | + if (hasPendingRead(socket)) { | | 230 | + // onClose() will create a new socket for the pending request. | | 231 | + debug('PENDING DATA on released socket - destroying'); | | 232 | + socket.destroy(); | | 233 | + return; | | 234 | + } | 217 | 235 | const req = requests.shift(); | 218 | 236 | const reqAsyncRes = req[kRequestAsyncResource]; | 219 | 237 | if (reqAsyncRes) { | @@ -391,6 +409,13 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, | 391 | 409 | socket = this.scheduling === 'fifo' ? | 392 | 410 | freeSockets.shift() : | 393 | 411 | freeSockets.pop(); | | 412 | + while (socket && hasPendingRead(socket)) { | | 413 | + debug('PENDING DATA on FREE socket - destroying poisoned socket'); | | 414 | + socket.destroy(); | | 415 | + socket = this.scheduling === 'fifo' ? | | 416 | + freeSockets.shift() : | | 417 | + freeSockets.pop(); | | 418 | + } | 394 | 419 | if (!freeSockets.length) | 395 | 420 | delete this.freeSockets[name]; | 396 | 421 | } | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/tls/wrap.js +1-1Lines changed: 1 addition & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -733,7 +733,7 @@ exports.TLSSocket = TLSSocket; | 733 | 733 | const proxiedMethods = [ | 734 | 734 | 'ref', 'unref', 'open', 'bind', 'listen', 'connect', 'bind6', | 735 | 735 | 'connect6', 'getsockname', 'getpeername', 'setNoDelay', 'setKeepAlive', | 736 | | - 'setSimultaneousAccepts', 'setBlocking', | | 736 | + 'setSimultaneousAccepts', 'setBlocking', 'hasPendingRead', | 737 | 737 |
| 738 | 738 | // PipeWrap | 739 | 739 | 'setPendingInstances', | |
Collapse file Copy file name to clipboardExpand all lines: src/stream_wrap.cc +65-2Lines changed: 65 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 33 | 33 | #include "udp_wrap.h" | 34 | 34 | #include "util-inl.h" | 35 | 35 |
| 36 | | -#include <cstring> // memcpy() | | 36 | +#include <cerrno> // errno | 37 | 37 | #include <climits> // INT_MAX | 38 | | - | | 38 | +#include <cstring> // memcpy() | 39 | 39 |
| 40 | 40 | namespace node { | 41 | 41 |
| @@ -130,6 +130,7 @@ void LibuvStreamWrap::RegisterExternalReferences( | 130 | 130 | registry->Register(IsConstructCallCallback); | 131 | 131 | registry->Register(GetWriteQueueSize); | 132 | 132 | registry->Register(SetBlocking); | | 133 | + registry->Register(HasPendingRead); | 133 | 134 | StreamBase::RegisterExternalReferences(registry); | 134 | 135 | } | 135 | 136 |
| @@ -168,6 +169,7 @@ Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate( | 168 | 169 | Local<FunctionTemplate>(), | 169 | 170 | static_cast<PropertyAttribute>(ReadOnly | DontDelete)); | 170 | 171 | SetProtoMethod(isolate, tmpl, "setBlocking", SetBlocking); | | 172 | + SetProtoMethod(isolate, tmpl, "hasPendingRead", HasPendingRead); | 171 | 173 | StreamBase::AddMethods(env, tmpl); | 172 | 174 | env->set_libuv_stream_wrap_ctor_template(tmpl); | 173 | 175 | } | @@ -335,6 +337,67 @@ void LibuvStreamWrap::SetBlocking(const FunctionCallbackInfo<Value>& args) { | 335 | 337 | args.GetReturnValue().Set(uv_stream_set_blocking(wrap->stream(), enable)); | 336 | 338 | } | 337 | 339 |
| | 340 | +// Returns true if a read on the underlying socket would complete right now, | | 341 | +// i.e. the OS has data, EOF, or a socket error queued that libuv has not | | 342 | +// delivered yet because the event loop has not polled for I/O since it | | 343 | +// arrived. Nothing is consumed. Returns false when there is nothing pending | | 344 | +// or when the handle type does not support the check. | | 345 | +void LibuvStreamWrap::HasPendingRead(const FunctionCallbackInfo<Value>& args) { | | 346 | + LibuvStreamWrap* wrap; | | 347 | + ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); | | 348 | + args.GetReturnValue().Set(false); | | 349 | + | | 350 | + if (!wrap->IsAlive() || wrap->IsClosing()) return; | | 351 | + | | 352 | +#ifdef _WIN32 | | 353 | + // Only TCP sockets can be probed with recv() on Windows. | | 354 | + if (!wrap->is_tcp()) return; | | 355 | +#else | | 356 | + if (!wrap->is_tcp() && !wrap->is_named_pipe()) return; | | 357 | +#endif | | 358 | + | | 359 | + uv_os_fd_t fd; | | 360 | + if (uv_fileno(reinterpret_cast<uv_handle_t*>(wrap->stream()), &fd) != 0) | | 361 | + return; | | 362 | + | | 363 | + char c; | | 364 | +#ifdef _WIN32 | | 365 | + // libuv puts TCP sockets in non-blocking mode and reads with zero-byte | | 366 | + // overlapped reads, so unread data stays in the kernel buffer. | | 367 | + int r = recv(reinterpret_cast<SOCKET>(fd), &c, 1, MSG_PEEK); | | 368 | + if (r == SOCKET_ERROR) { | | 369 | + switch (WSAGetLastError()) { | | 370 | + case WSAEWOULDBLOCK: | | 371 | + case WSAENOTCONN: | | 372 | + case WSAENOTSOCK: | | 373 | + return; | | 374 | + } | | 375 | + } | | 376 | +#else | | 377 | + int flags = MSG_PEEK; | | 378 | +#ifdef MSG_DONTWAIT | | 379 | + flags |= MSG_DONTWAIT; | | 380 | +#endif | | 381 | + ssize_t r; | | 382 | + do { | | 383 | + r = recv(fd, &c, 1, flags); | | 384 | + } while (r == -1 && errno == EINTR); | | 385 | + if (r == -1) { | | 386 | + switch (errno) { | | 387 | + case EAGAIN: | | 388 | +#if EWOULDBLOCK != EAGAIN | | 389 | + case EWOULDBLOCK: | | 390 | +#endif | | 391 | + case ENOTCONN: | | 392 | + case ENOTSOCK: | | 393 | + return; | | 394 | + } | | 395 | + } | | 396 | +#endif | | 397 | + | | 398 | + args.GetReturnValue().Set(true); | | 399 | +} | | 400 | + | 338 | 401 | typedef SimpleShutdownWrap<ReqWrap<uv_shutdown_t>> LibuvShutdownWrap; | 339 | 402 | typedef SimpleWriteWrap<ReqWrap<uv_write_t>> LibuvWriteWrap; | 340 | 403 |
| |
Collapse file Copy file name to clipboardExpand all lines: src/stream_wrap.h +1Lines changed: 1 addition & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -108,6 +108,7 @@ class LibuvStreamWrap : public HandleWrap, public StreamBase { | 108 | 108 | static void GetWriteQueueSize( | 109 | 109 | const v8::FunctionCallbackInfo<v8::Value>& info); | 110 | 110 | static void SetBlocking(const v8::FunctionCallbackInfo<v8::Value>& args); | | 111 | + static void HasPendingRead(const v8::FunctionCallbackInfo<v8::Value>& args); | 111 | 112 |
| 112 | 113 | // Callbacks for libuv | 113 | 114 | void OnUvAlloc(size_t suggested_size, uv_buf_t* buf); | |
Collapse file Copy file name to clipboard +121Lines changed: 121 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | + | | 3 | +// The free socket data guard in http.Agent only runs when the event loop | | 4 | +// polls for I/O. If data reaches an idle socket's OS buffer and a request | | 5 | +// takes that socket before the loop has polled, the guard never sees the data | | 6 | +// and it would be parsed as the response to that request. The Agent must | | 7 | +// check for pending data before handing a kept-alive socket to a request. | | 8 | + | | 9 | +const common = require('../common'); | | 10 | +const assert = require('assert'); | | 11 | +const http = require('http'); | | 12 | + | | 13 | +const poison = | | 14 | + 'HTTP/1.1 200 OK\r\n' + | | 15 | + 'X-Poisoned: true\r\n' + | | 16 | + 'Connection: keep-alive\r\n' + | | 17 | + 'Content-Length: 0\r\n' + | | 18 | + '\r\n'; | | 19 | + | | 20 | +// Keep the event loop from polling until the bytes are in the client's | | 21 | +// socket buffer, so libuv cannot deliver them to the data guard first. | | 22 | +function waitForPendingRead(socket) { | | 23 | + const deadline = Date.now() + common.platformTimeout(5000); | | 24 | + while (!socket._handle.hasPendingRead()) { | | 25 | + assert.ok(Date.now() < deadline, 'timed out waiting for pending data'); | | 26 | + } | | 27 | +} | | 28 | + | | 29 | +function checkResponse(req, expectedBody, cb) { | | 30 | + req.on('response', common.mustCall((res) => { | | 31 | + let body = ''; | | 32 | + res.setEncoding('utf8'); | | 33 | + res.on('data', (chunk) => { body += chunk; }); | | 34 | + res.on('end', common.mustCall(() => { | | 35 | + assert.strictEqual(res.headers['x-poisoned'], undefined); | | 36 | + assert.strictEqual(body, expectedBody); | | 37 | + cb?.(res); | | 38 | + })); | | 39 | + })); | | 40 | +} | | 41 | + | | 42 | +// A socket taken from the free pool. | | 43 | +{ | | 44 | + let serverSocket; | | 45 | + const server = http.createServer(common.mustCall((req, res) => { | | 46 | + serverSocket ||= req.socket; | | 47 | + res.end(req.url); | | 48 | + }, 2)); | | 49 | + | | 50 | + server.listen(0, common.mustCall(() => { | | 51 | + const agent = new http.Agent({ keepAlive: true }); | | 52 | + const options = { host: '127.0.0.1', port: server.address().port, agent }; | | 53 | + const name = agent.getName(options); | | 54 | + | | 55 | + const request1 = http.request({ ...options, path: '/request1' }); | | 56 | + request1.end(); | | 57 | + checkResponse(request1, '/request1'); | | 58 | + | | 59 | + request1.on('close', common.mustCall(() => { | | 60 | + process.nextTick(common.mustCall(() => { | | 61 | + assert.strictEqual(agent.freeSockets[name]?.length, 1); | | 62 | + const freeSocket = agent.freeSockets[name][0]; | | 63 | + | | 64 | + serverSocket.write(poison); | | 65 | + waitForPendingRead(freeSocket); | | 66 | + | | 67 | + // Same tick: the loop has not polled since the data arrived. | | 68 | + const request2 = http.request({ ...options, path: '/request2' }); | | 69 | + request2.end(); | | 70 | + | | 71 | + assert.strictEqual(freeSocket.destroyed, true); | | 72 | + assert.strictEqual(request2.reusedSocket, false); | | 73 | + | | 74 | + checkResponse(request2, '/request2', common.mustCall(() => { | | 75 | + agent.destroy(); | | 76 | + server.close(); | | 77 | + })); | | 78 | + })); | | 79 | + })); | | 80 | + })); | | 81 | +} | | 82 | + | | 83 | +// A released socket handed directly to a queued request. | | 84 | +{ | | 85 | + let serverSocket; | | 86 | + const server = http.createServer(common.mustCall((req, res) => { | | 87 | + serverSocket ||= req.socket; | | 88 | + res.end(req.url); | | 89 | + }, 2)); | | 90 | + | | 91 | + server.listen(0, common.mustCall(() => { | | 92 | + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); | | 93 | + const options = { host: '127.0.0.1', port: server.address().port, agent }; | | 94 | + const name = agent.getName(options); | | 95 | + | | 96 | + const request1 = http.request({ ...options, path: '/request1' }); | | 97 | + request1.end(); | | 98 | + const request2 = http.request({ ...options, path: '/request2' }); | | 99 | + request2.end(); | | 100 | + assert.strictEqual(agent.requests[name]?.length, 1); | | 101 | + | | 102 | + let socket1; | | 103 | + request1.on('socket', common.mustCall((socket) => { | | 104 | + socket1 = socket; | | 105 | + })); | | 106 | + | | 107 | + // The socket is released to the queued request on the next tick after | | 108 | + // 'end', so the loop does not poll in between. | | 109 | + checkResponse(request1, '/request1', common.mustCall(() => { | | 110 | + serverSocket.write(poison); | | 111 | + waitForPendingRead(socket1); | | 112 | + })); | | 113 | + | | 114 | + checkResponse(request2, '/request2', common.mustCall(() => { | | 115 | + assert.strictEqual(socket1.destroyed, true); | | 116 | + assert.strictEqual(request2.reusedSocket, false); | | 117 | + agent.destroy(); | | 118 | + server.close(); | | 119 | + })); | | 120 | + })); | | 121 | +} |
|