|
'use strict'; |
|
|
|
|
|
|
|
|
|
|
|
const net = require('net'); |
|
const tls = require('tls'); |
|
const urllib = require('url'); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) { |
|
let proxy = urllib.parse(proxyUrl); |
|
|
|
|
|
let options; |
|
let connect; |
|
let socket; |
|
|
|
options = { |
|
host: proxy.hostname, |
|
port: Number(proxy.port) ? Number(proxy.port) : proxy.protocol === 'https:' ? 443 : 80 |
|
}; |
|
|
|
if (proxy.protocol === 'https:') { |
|
|
|
options.rejectUnauthorized = false; |
|
connect = tls.connect.bind(tls); |
|
} else { |
|
connect = net.connect.bind(net); |
|
} |
|
|
|
|
|
|
|
let finished = false; |
|
let tempSocketErr = function (err) { |
|
if (finished) { |
|
return; |
|
} |
|
finished = true; |
|
try { |
|
socket.destroy(); |
|
} catch (E) { |
|
|
|
} |
|
callback(err); |
|
}; |
|
|
|
socket = connect(options, () => { |
|
if (finished) { |
|
return; |
|
} |
|
|
|
let reqHeaders = { |
|
Host: destinationHost + ':' + destinationPort, |
|
Connection: 'close' |
|
}; |
|
if (proxy.auth) { |
|
reqHeaders['Proxy-Authorization'] = 'Basic ' + Buffer.from(proxy.auth).toString('base64'); |
|
} |
|
|
|
socket.write( |
|
|
|
'CONNECT ' + |
|
destinationHost + |
|
':' + |
|
destinationPort + |
|
' HTTP/1.1\r\n' + |
|
|
|
Object.keys(reqHeaders) |
|
.map(key => key + ': ' + reqHeaders[key]) |
|
.join('\r\n') + |
|
|
|
'\r\n\r\n' |
|
); |
|
|
|
let headers = ''; |
|
let onSocketData = chunk => { |
|
let match; |
|
let remainder; |
|
|
|
if (finished) { |
|
return; |
|
} |
|
|
|
headers += chunk.toString('binary'); |
|
if ((match = headers.match(/\r\n\r\n/))) { |
|
socket.removeListener('data', onSocketData); |
|
|
|
remainder = headers.substr(match.index + match[0].length); |
|
headers = headers.substr(0, match.index); |
|
if (remainder) { |
|
socket.unshift(Buffer.from(remainder, 'binary')); |
|
} |
|
|
|
|
|
finished = true; |
|
|
|
|
|
match = headers.match(/^HTTP\/\d+\.\d+ (\d+)/i); |
|
if (!match || (match[1] || '').charAt(0) !== '2') { |
|
try { |
|
socket.destroy(); |
|
} catch (E) { |
|
|
|
} |
|
return callback(new Error('Invalid response from proxy' + ((match && ': ' + match[1]) || ''))); |
|
} |
|
|
|
socket.removeListener('error', tempSocketErr); |
|
return callback(null, socket); |
|
} |
|
}; |
|
socket.on('data', onSocketData); |
|
}); |
|
|
|
socket.once('error', tempSocketErr); |
|
} |
|
|
|
module.exports = httpProxyClient; |
|
|