Skip to content

Commit bc34680

Browse files
zanetteaZanette Arrigo
authored andcommitted
net: reduce likelihood of race conditions on keep-alive timeout calculation between http1.1 servers and clients
Fixes: #47130 Fixes: #52649
1 parent e617573 commit bc34680

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

lib/_http_agent.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,7 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
488488
socket.unref();
489489

490490
let agentTimeout = this.options.timeout || 0;
491+
let canKeepSocketAlive = true;
491492

492493
if (socket._httpMessage?.res) {
493494
const keepAliveHint = socket._httpMessage.res.headers['keep-alive'];
@@ -498,11 +499,15 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
498499
if (hint) {
499500
// Let the timer expires before the announced timeout to reduce
500501
// the likelihood of ECONNRESET errors
501-
let serverHintTimeout = ( NumberParseInt(hint) * 1000 ) - 1000;
502+
let serverHintTimeout = (NumberParseInt(hint) * 1000) - 1000;
502503
serverHintTimeout = serverHintTimeout > 0 ? serverHintTimeout : 0;
503-
504-
if (serverHintTimeout < agentTimeout) {
505-
agentTimeout = serverHintTimeout;
504+
if (serverHintTimeout === 0) {
505+
// cannot safely reuse the socket because the server timeout is too short
506+
canKeepSocketAlive = false;
507+
} else {
508+
if (serverHintTimeout < agentTimeout) {
509+
agentTimeout = serverHintTimeout;
510+
}
506511
}
507512
}
508513
}
@@ -512,7 +517,7 @@ Agent.prototype.keepSocketAlive = function keepSocketAlive(socket) {
512517
socket.setTimeout(agentTimeout);
513518
}
514519

515-
return true;
520+
return canKeepSocketAlive;
516521
};
517522

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

0 commit comments

Comments
 (0)