Skip to content

Commit

Permalink
tls: reduce TLS 'close' event listener warnings
Browse files Browse the repository at this point in the history
Without this, some heavy usage of TLS sockets can result in
MaxListenersExceededWarning firing, from the 'this.on('close', ...)'
line here.

These appear to come from reinitializeHandle, which calls _wrapHandle
repeatedly on the same socket instance.

PR-URL: #50136
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
  • Loading branch information
pimterry authored and targos committed Nov 11, 2023
1 parent f3296d2 commit d2def15
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/_tls_wrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,12 @@ TLSSocket.prototype._wrapHandle = function(wrap, handle, wrapHasActiveWriteFromP
this[kRes] = res;
defineHandleReading(this, handle);

this.on('close', onSocketCloseDestroySSL);
// Guard against adding multiple listeners, as this method may be called
// repeatedly on the same socket by reinitializeHandle
if (this.listenerCount('close', onSocketCloseDestroySSL) === 0) {
this.on('close', onSocketCloseDestroySSL);
}

if (wrap) {
wrap.on('close', () => this.destroy());
}
Expand Down
42 changes: 42 additions & 0 deletions test/parallel/test-tls-reinitialize-listeners.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Flags: --expose-internals
'use strict';

const common = require('../common');

if (!common.hasCrypto) {
common.skip('missing crypto');
}

const events = require('events');
const fixtures = require('../common/fixtures');
const tls = require('tls');
const { kReinitializeHandle } = require('internal/net');

// Test that repeated calls to kReinitializeHandle() do not result in repeatedly
// adding new listeners on the socket (i.e. no MaxListenersExceededWarnings)

process.on('warning', common.mustNotCall());

const server = tls.createServer({
key: fixtures.readKey('agent1-key.pem'),
cert: fixtures.readKey('agent1-cert.pem')
});

server.listen(0, common.mustCall(function() {
const socket = tls.connect({
port: this.address().port,
rejectUnauthorized: false
});

socket.on('secureConnect', common.mustCall(function() {
for (let i = 0; i < events.defaultMaxListeners + 1; i++) {
socket[kReinitializeHandle]();
}

socket.destroy();
}));

socket.on('close', function() {
server.close();
});
}));

0 comments on commit d2def15

Please sign in to comment.