Skip to content

Commit

Permalink
net: reduce likelihood of race conditions on keep-alive timeout calcu…
Browse files Browse the repository at this point in the history
…lation between http1.1 servers and clients

Fixes: nodejs#47130
Fixes: nodejs#52649
  • Loading branch information
zanettea authored and Zanette Arrigo committed Apr 24, 2024
1 parent e617573 commit 8407fd7
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions lib/_http_agent.js
Expand Up @@ -488,6 +488,7 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
socket.unref();

let agentTimeout = this.options.timeout || 0;
let canKeepSocketAlive = true;

if (socket._httpMessage?.res) {
const keepAliveHint = socket._httpMessage.res.headers['keep-alive'];
Expand All @@ -498,11 +499,15 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
if (hint) {
// Let the timer expires before the announced timeout to reduce
// the likelihood of ECONNRESET errors
let serverHintTimeout = ( NumberParseInt(hint) * 1000 ) - 1000;
let serverHintTimeout = (NumberParseInt(hint) * 1000) - 1000;
serverHintTimeout = serverHintTimeout > 0 ? serverHintTimeout : 0;

if (serverHintTimeout < agentTimeout) {
agentTimeout = serverHintTimeout;
if (serverHintTimeout === 0) {
// cannot safely reuse the socket because the server timeout is too short

Check failure on line 505 in lib/_http_agent.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Comments should not begin with a lowercase character
canKeepSocketAlive = false;
} else {
if (serverHintTimeout < agentTimeout) {

Check failure on line 508 in lib/_http_agent.js

View workflow job for this annotation

GitHub Actions / lint-js-and-md

Unexpected if as the only statement in an else block
agentTimeout = serverHintTimeout;
}
}
}
}
Expand All @@ -512,7 +517,7 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
socket.setTimeout(agentTimeout);
}

return true;
return canKeepSocketAlive;
};

Agent.prototype.reuseSocket = function reuseSocket(socket, req) {
Expand Down

0 comments on commit 8407fd7

Please sign in to comment.