From fc6426ccc4b4cb73076356fb6dbf46a28953af01 Mon Sep 17 00:00:00 2001 From: Antoine du Hamel Date: Fri, 12 Feb 2021 12:10:57 +0100 Subject: [PATCH] http: refactor to avoid unsafe array iteration PR-URL: https://github.com/nodejs/node/pull/37654 Reviewed-By: Darshan Sen Reviewed-By: Zijian Liu --- lib/_http_agent.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/_http_agent.js b/lib/_http_agent.js index 53f6ade00ce524..8bc74c9cd43327 100644 --- a/lib/_http_agent.js +++ b/lib/_http_agent.js @@ -27,6 +27,7 @@ const { ArrayPrototypePop, ArrayPrototypePush, ArrayPrototypeShift, + ArrayPrototypeSome, ArrayPrototypeSplice, FunctionPrototypeCall, NumberIsNaN, @@ -392,10 +393,10 @@ function installListeners(agent, s, options) { // Destroy if in free list. // TODO(ronag): Always destroy, even if not in free list. const sockets = agent.freeSockets; - for (const name of ObjectKeys(sockets)) { - if (ArrayPrototypeIncludes(sockets[name], s)) { - return s.destroy(); - } + if (ArrayPrototypeSome(ObjectKeys(sockets), (name) => + ArrayPrototypeIncludes(sockets[name], s) + )) { + return s.destroy(); } } s.on('timeout', onTimeout); @@ -451,7 +452,9 @@ Agent.prototype.removeSocket = function removeSocket(s, options) { // There might be older requests in a different origin, but // if the origin which releases the socket has pending requests // that will be prioritized. - for (const prop of ObjectKeys(this.requests)) { + const keys = ObjectKeys(this.requests); + for (let i = 0; i < keys.length; i++) { + const prop = keys[i]; // Check whether this specific origin is already at maxSockets if (this.sockets[prop] && this.sockets[prop].length) break; debug('removeSocket, have a request with different origin,' +