Created
May 28, 2018 10:49
-
-
Save Dviejopomata/a07cf523f6a7417a6122d9ebf75646d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import net = require("net") | |
import sni = require("sni") | |
const TCP_PORT = 443 | |
const PORT = "8444" | |
const CERT_PORT = "8445" | |
const remotehost = "localhost" | |
const remoteport = parseInt(PORT, 10) | |
const remoteCertHost = "localhost" | |
const remoteCertPort = parseInt(CERT_PORT, 10) | |
const log = (...str) => { | |
console.log(...str) | |
// do nothing | |
} | |
const tcpServer = net.createServer(localSocket => { | |
const remotesocket = new net.Socket() | |
localSocket.once("data", data => { | |
const host = sni(data) | |
if (host.includes("cert")) { | |
remotesocket.connect(remoteCertPort, remoteCertHost) | |
} else { | |
remotesocket.connect(remoteport, remotehost) | |
} | |
}) | |
localSocket.on("data", data => { | |
if (remotesocket.writable) { | |
const flushed = remotesocket.write(data) | |
if (!flushed) { | |
log(" remote not flushed; pausing local") | |
localSocket.pause() | |
} | |
} | |
}) | |
remotesocket.on("data", data => { | |
const flushed = localSocket.write(data) | |
if (!flushed) { | |
log(" local not flushed; pausing remote") | |
remotesocket.pause() | |
} | |
}) | |
localSocket.on("drain", () => { | |
remotesocket.resume() | |
}) | |
remotesocket.on("drain", () => { | |
localSocket.resume() | |
}) | |
localSocket.on("close", had_error => { | |
remotesocket.end() | |
}) | |
localSocket.on("error", err => { | |
console.log("localSocket", err) | |
localSocket.end() | |
}) | |
remotesocket.on("error", err => { | |
console.log("remotesocket", err) | |
remotesocket.end() | |
}) | |
remotesocket.on("close", had_error => { | |
localSocket.end() | |
}) | |
}) | |
const tcpInstance = tcpServer.listen(TCP_PORT, () => { | |
const { address, port } = tcpInstance.address() as net.AddressInfo | |
log(`Tcp server listening on ${address}${port}`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment