0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-21 21:19:50 +01:00
nodejs/test/parallel/test-socket-writes-before-passed-to-tls-socket.js
rogertyang 556b1ca900 tls: fix bugs of double TLS
Fixs two issues in `TLSWrap`, one of them is reported in
https://github.com/nodejs/node/issues/30896.

1. `TLSWrap` has exactly one `StreamListener`, however,
that `StreamListener` can be replaced. We have not been
rigorous enough here: if an active write has not been
finished before the transition, the finish callback of it
will be wrongly fired the successor `StreamListener`.

2. A `TLSWrap` does not allow more than one active write,
as checked in the assertion about current_write in
`TLSWrap::DoWrite()`.

However, when users make use of an existing `tls.TLSSocket`
to establish double TLS, by
either
  tls.connect({socket: tlssock})
or
  tlsServer.emit('connection', tlssock)
we have both of the user provided `tls.TLSSocket`, tlssock and
a brand new created `TLSWrap` writing to the `TLSWrap` bound to
tlssock, which easily violates the constranint because two writers
have no idea of each other.

The design of the fix is:
when a `TLSWrap` is created on top of a user provided socket,
do not send any data to the socket until all existing writes
of the socket are done and ensure registered callbacks of
those writes can be fired.

PR-URL: https://github.com/nodejs/node/pull/48969
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
2023-08-04 10:14:18 -04:00

43 lines
1.3 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
if (!common.hasCrypto) common.skip('missing crypto');
const tls = require('tls');
const net = require('net');
const HEAD = Buffer.alloc(1024 * 1024, 0);
const server = net.createServer((serverSock) => {
let recvLen = 0;
const recv = [];
serverSock.on('data', common.mustCallAtLeast((chunk) => {
recv.push(chunk);
recvLen += chunk.length;
// Check that HEAD is followed by a client hello
if (recvLen > HEAD.length) {
const clientHelloFstByte = Buffer.concat(recv).subarray(HEAD.length, HEAD.length + 1);
assert.strictEqual(clientHelloFstByte.toString('hex'), '16');
process.exit(0);
}
}, 1));
})
.listen(client);
function client() {
const socket = net.createConnection({
host: '127.0.0.1',
port: server.address().port,
});
socket.write(HEAD.subarray(0, HEAD.length / 2), common.mustSucceed());
// This write will be queued by streams.Writable, the super class of net.Socket,
// which will dequeue this write when it gets notified about the finish of the first write.
// We had a bug that it wouldn't get notified. This test verifies the bug is fixed.
socket.write(HEAD.subarray(HEAD.length / 2), common.mustSucceed());
tls.connect({
socket,
});
}