diff --git a/lib/internal/stream_base_commons.js b/lib/internal/stream_base_commons.js index 7bf3a2bab638..1c5d935ff6a6 100644 --- a/lib/internal/stream_base_commons.js +++ b/lib/internal/stream_base_commons.js @@ -2,6 +2,7 @@ const { Array, + ArrayBufferPrototypeGetDetached, Symbol, } = primordials; @@ -188,6 +189,15 @@ function onStreamRead(arrayBuffer) { if (isUint8Array(nextBuf)) stream[kBuffer] = ret = nextBuf; } + // If the buffer that will be reused for the next read was detached during + // the callback (e.g. by transferring a view into a byte `ReadableStream`), + // it can no longer be safely written to. Stop reading instead of handing + // the stale address back to the native read path. + const reusableBuf = stream[kBuffer]; + if (isUint8Array(reusableBuf) && + ArrayBufferPrototypeGetDetached(reusableBuf.buffer)) { + result = false; + } } else { const offset = streamBaseState[kArrayBufferOffset]; const buf = new FastBuffer(arrayBuffer, offset, nread); diff --git a/src/stream_base.cc b/src/stream_base.cc index a73a39513fb0..786d23399b0e 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -163,7 +163,9 @@ int StreamBase::UseUserBuffer(const FunctionCallbackInfo& args) { CHECK(Buffer::HasInstance(args[0])); uv_buf_t buf = uv_buf_init(Buffer::Data(args[0]), Buffer::Length(args[0])); - PushStreamListener(new CustomBufferJSListener(buf)); + Local array_buffer = args[0].As()->Buffer(); + PushStreamListener( + new CustomBufferJSListener(array_buffer->GetBackingStore(), buf)); return 0; } @@ -795,8 +797,11 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { StreamBase::SKIP_NREAD_CHECKS); Local next_buf_v; if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) { + Local array_buffer = + next_buf_v.As()->Buffer(); buffer_.base = Buffer::Data(next_buf_v); buffer_.len = Buffer::Length(next_buf_v); + backing_store_ = array_buffer->GetBackingStore(); } } diff --git a/src/stream_base.h b/src/stream_base.h index 450205a1b863..146047439b58 100644 --- a/src/stream_base.h +++ b/src/stream_base.h @@ -211,9 +211,17 @@ class CustomBufferJSListener : public ReportWritesToJSStreamListener { void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override; void OnStreamDestroy() override { delete this; } - explicit CustomBufferJSListener(uv_buf_t buffer) : buffer_(buffer) {} + explicit CustomBufferJSListener( + std::shared_ptr backing_store, uv_buf_t buffer) + : backing_store_(std::move(backing_store)), buffer_(buffer) {} private: + // Retain the backing store for the lifetime of the listener. The raw address + // in `buffer_` is derived from it, so retaining the backing store guarantees + // the address does not dangle even if application code later transfers (and + // thereby detaches) the buffer, e.g. by enqueuing a view into a byte + // `ReadableStream`. + std::shared_ptr backing_store_; uv_buf_t buffer_; }; diff --git a/test/parallel/test-net-onread-buffer-detached.js b/test/parallel/test-net-onread-buffer-detached.js new file mode 100644 index 000000000000..41bebe5e1f91 --- /dev/null +++ b/test/parallel/test-net-onread-buffer-detached.js @@ -0,0 +1,77 @@ +'use strict'; + +const common = require('../common'); +const net = require('net'); +const assert = require('assert'); + +// Regression test. +// +// When an `onread` callback transfers a view of the reusable buffer into a byte +// `ReadableStream`, the transfer detaches the buffer's backing store. The socket +// must not keep writing subsequent peer data into the detached backing store, +// otherwise it corrupts the chunk the application has retained. + +let controller; +const stream = new ReadableStream({ + type: 'bytes', + start(c) { + controller = c; + }, +}); +const reader = stream.getReader(); + +const server = net.createServer(common.mustCall((socket) => { + socket.setNoDelay(true); + socket.write('first'); + // Send more data shortly after the client transfers the first chunk. + const timer = setTimeout(() => { + socket.write('Z'.repeat(1024)); + }, 50); + socket.on('close', () => clearTimeout(timer)); + socket.on('error', common.mustNotCall()); +})); + +server.listen(0, common.mustCall(() => { + const port = server.address().port; + + let transferred = false; + + const client = net.createConnection({ + host: '127.0.0.1', + port, + onread: { + buffer: Buffer.alloc(4096), + callback(nread, buf) { + // Enqueueing a view transfers (and thereby detaches) the underlying + // ArrayBuffer. An affected binary then keeps writing later peer data + // over this chunk's memory. + if (transferred) return; + transferred = true; + const view = new Uint8Array(buf.buffer, buf.byteOffset, nread); + controller.enqueue(view); + }, + }, + }); + + client.on('error', common.mustNotCall()); + + (async () => { + const { value: chunk, done } = await reader.read(); + assert.strictEqual(done, false); + + // The first peer write ("first", 5 bytes) is delivered intact. + assert.strictEqual(chunk[0], 0x66); // 'f' + assert.strictEqual(Buffer.from(chunk).toString(), 'first'); + + // Give the second peer write time to reach the client. Reading has stopped, + // so the retained chunk must not be overwritten. + await new Promise((resolve) => setTimeout(resolve, 200)); + + assert.strictEqual(chunk[0], 0x66, + `retained chunk was corrupted: 0x${chunk[0].toString(16)}`); + assert.strictEqual(Buffer.from(chunk).toString(), 'first'); + + client.end(); + server.close(); + })().then(common.mustCall()); +}));