From 870ef5a73f6f104724e177d96eef9b3339e8792a Mon Sep 17 00:00:00 2001 From: theanarkh Date: Tue, 27 Feb 2024 21:46:45 +0800 Subject: [PATCH] net: fix connect crash when call destroy in lookup handler PR-URL: https://github.com/nodejs/node/pull/51826 Fixes: https://github.com/nodejs/node/issues/50841 Reviewed-By: Paolo Insogna Reviewed-By: Luigi Pinca Reviewed-By: Matteo Collina Reviewed-By: Jiawen Geng --- lib/net.js | 5 ++++- test/parallel/test-destroy-socket-in-lookup.js | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 test/parallel/test-destroy-socket-in-lookup.js diff --git a/lib/net.js b/lib/net.js index 4cd8864a534c0d..cf8be1601c30d7 100644 --- a/lib/net.js +++ b/lib/net.js @@ -1435,7 +1435,10 @@ function lookupAndConnectMultiple( const address = addresses[i]; const { address: ip, family: addressType } = address; self.emit('lookup', err, ip, addressType, host); - + // It's possible we were destroyed while looking this up. + if (!self.connecting) { + return; + } if (isIP(ip) && (addressType === 4 || addressType === 6)) { if (!destinations) { destinations = addressType === 6 ? { 6: 0, 4: 1 } : { 4: 0, 6: 1 }; diff --git a/test/parallel/test-destroy-socket-in-lookup.js b/test/parallel/test-destroy-socket-in-lookup.js new file mode 100644 index 00000000000000..4f45622cc792fe --- /dev/null +++ b/test/parallel/test-destroy-socket-in-lookup.js @@ -0,0 +1,16 @@ +'use strict'; +const common = require('../common'); +const net = require('net'); + +// Test that the process does not crash. +const socket = net.connect({ + port: 12345, + host: 'localhost', + // Make sure autoSelectFamily is true + // so that lookupAndConnectMultiple is called. + autoSelectFamily: true, +}); +// DNS resolution fails or succeeds +socket.on('lookup', common.mustCall(() => { + socket.destroy(); +}));