Check if a socket is writable before writing to it

This commit is contained in:
Sander Declerck 2025-10-08 19:32:25 +02:00
parent cfce641053
commit 219a189993
No known key found for this signature in database

View file

@ -35,7 +35,9 @@ function tunnelRequestToDestination(req, clientSocket, head) {
ui.writeError( ui.writeError(
`Safe-chain: error connecting to ${hostname}:${port} - ${err.message}` `Safe-chain: error connecting to ${hostname}:${port} - ${err.message}`
); );
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n"); if (clientSocket.writable) {
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
}
}); });
} }
@ -76,8 +78,12 @@ function tunnelRequestViaProxy(req, clientSocket, head, proxyUrl) {
ui.writeError( ui.writeError(
`Safe-chain: proxy CONNECT failed: ${response.split("\r\n")[0]}` `Safe-chain: proxy CONNECT failed: ${response.split("\r\n")[0]}`
); );
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n"); if (clientSocket.writable) {
proxySocket.end(); clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
}
if (proxySocket.writable) {
proxySocket.end();
}
} }
}); });
@ -88,11 +94,15 @@ function tunnelRequestViaProxy(req, clientSocket, head, proxyUrl) {
proxy.port || 8080 proxy.port || 8080
} - ${err.message}` } - ${err.message}`
); );
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n"); if (clientSocket.writable) {
clientSocket.end("HTTP/1.1 502 Bad Gateway\r\n\r\n");
}
} }
}); });
clientSocket.on("error", () => { clientSocket.on("error", () => {
proxySocket.end(); if (proxySocket.writable) {
proxySocket.end();
}
}); });
} }