From 061dcbb56d318764e294820072b93947f98db5f2 Mon Sep 17 00:00:00 2001 From: theanarkh Date: Thu, 29 Feb 2024 03:01:09 +0800 Subject: [PATCH] lib: return directly if udp socket close before lookup --- lib/dgram.js | 6 +++--- ...t-dgram-bind-socket-close-before-lookup.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 test/parallel/test-dgram-bind-socket-close-before-lookup.js diff --git a/lib/dgram.js b/lib/dgram.js index 8c8da1ad8856b5..969f696b9e50da 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -328,6 +328,9 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { // Resolve address first state.handle.lookup(address, (err, ip) => { + if (!state.handle) + return; // Handle has been closed in the mean time + if (err) { state.bindState = BIND_STATE_UNBOUND; this.emit('error', err); @@ -356,9 +359,6 @@ Socket.prototype.bind = function(port_, address_ /* , callback */) { this.emit('error', ex); }); } else { - if (!state.handle) - return; // Handle has been closed in the mean time - const err = state.handle.bind(ip, port || 0, flags); if (err) { const ex = new ExceptionWithHostPort(err, 'bind', ip, port); diff --git a/test/parallel/test-dgram-bind-socket-close-before-lookup.js b/test/parallel/test-dgram-bind-socket-close-before-lookup.js new file mode 100644 index 00000000000000..96ca71c3deeb4e --- /dev/null +++ b/test/parallel/test-dgram-bind-socket-close-before-lookup.js @@ -0,0 +1,19 @@ +'use strict'; +const common = require('../common'); +const dgram = require('dgram'); + +// Do not emit error event in callback which is called by lookup when socket is closed +const socket = dgram.createSocket({ + type: 'udp4', + lookup: (...args) => { + // Call lookup callback after 1s + setTimeout(() => { + args.at(-1)(new Error('an error')); + }, 1000); + } +}); + +socket.on('error', common.mustNotCall()); +socket.bind(12345, 'localhost'); +// Close the socket before calling DNS lookup callback +socket.close();