From 91cbe499cb4aab6ae6827025ee793cfdbc8ed0c4 Mon Sep 17 00:00:00 2001 From: avwo Date: Sat, 30 Jun 2018 07:50:30 +0800 Subject: [PATCH] feat: auto reduce to http request --- lib/https/index.js | 13 +++++++++++-- lib/inspectors/res.js | 3 +-- lib/util/index.js | 7 ++++++- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/lib/https/index.js b/lib/https/index.js index a96b6acfc..a55cf34ed 100644 --- a/lib/https/index.js +++ b/lib/https/index.js @@ -304,7 +304,7 @@ function _handleWebsocket(socket, clientIp, clientPort, callback, wss) { } } - function connectServer(hostIp, hostPort) { + function connectServer(hostIp, hostPort, err) { getServerIp(fullUrl, function(ip, port) { var isWss = options.protocol === 'wss:'; socket.hostIp = resData.ip = port ? ip + ':' + port : ip; @@ -316,7 +316,16 @@ function _handleWebsocket(socket, clientIp, clientPort, callback, wss) { port: port, servername: options.hostname }, pipeData); - abortIfUnavailable(reqSocket); + if (err) { + abortIfUnavailable(reqSocket); + } else { + reqSocket.on('error', function(e) { + if (util.checkTlsHandUp(socket, ip, e)) { + options.protocol = null; + } + connectServer(hostIp, hostPort, e); + }); + } }, hostIp, hostPort); } diff --git a/lib/inspectors/res.js b/lib/inspectors/res.js index 1b7c17e97..9c59a4f55 100644 --- a/lib/inspectors/res.js +++ b/lib/inspectors/res.js @@ -273,8 +273,7 @@ module.exports = function(req, res, next) { }); return; } - } else if (isHttps && !req.disable.auto2http && (req.enable.auto2http - || resRules.host || util.isLocalAddress(ip)) && util.checkSslError(err)) { + } else if (util.checkTlsHandUp(req, ip, err)) { isHttps = false; ++maxRetryCount; setAgent(); diff --git a/lib/util/index.js b/lib/util/index.js index 7c0c33a5d..71cabed02 100644 --- a/lib/util/index.js +++ b/lib/util/index.js @@ -1975,7 +1975,7 @@ exports.escapeRegExp = function (str) { return str.replace(/[|\\{}()[\]^$+?.]/g, '\\$&'); }; -exports.checkSslError = function(err) { +function checkTlsError(err) { var code = err && err.code; if (!code) { return false; @@ -1988,4 +1988,9 @@ exports.checkSslError = function(err) { return false; } return stack.indexOf('at TLSSocket.onHangUp') !== -1; +} + +exports.checkTlsHandUp = function(req, ip, err) { + return req.isHttps && !req.disable.auto2http && (req.enable.auto2http + || req.rules.host || isLocalAddress(ip)) && checkTlsError(err); };