smartproxy/ts/smartproxy.portproxy.ts

74 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-07-28 22:49:46 +00:00
import * as plugins from './smartproxy.plugins.js';
2019-08-22 13:09:48 +00:00
import * as net from 'net';
2020-02-07 12:43:37 +00:00
let netServer: plugins.net.Server;
2020-02-23 19:03:25 +00:00
let httpServer: plugins.http.Server;
2019-08-22 13:09:48 +00:00
2022-07-28 22:49:46 +00:00
export class PortProxy {
fromPort: number;
toPort: number;
constructor(fromPortArg: number, toPortArg: number) {
this.fromPort = fromPortArg;
2022-07-28 23:52:34 +00:00
this.toPort = toPortArg;
2022-07-28 22:49:46 +00:00
}
2022-07-28 23:52:34 +00:00
public async start() {
2021-02-02 21:59:24 +00:00
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => {
from.end();
to.end();
from.removeAllListeners();
2021-02-02 21:59:54 +00:00
to.removeAllListeners();
2021-02-02 21:59:24 +00:00
from.unpipe();
to.unpipe();
2021-02-03 00:13:29 +00:00
from.destroy();
to.destroy();
2022-07-28 23:52:34 +00:00
};
2020-02-07 12:43:37 +00:00
netServer = net
2021-02-02 15:55:25 +00:00
.createServer((from) => {
2020-02-07 13:04:11 +00:00
const to = net.createConnection({
host: 'localhost',
2022-07-28 22:49:46 +00:00
port: this.toPort,
2021-02-02 15:55:25 +00:00
});
2021-02-03 00:16:11 +00:00
from.setTimeout(120000);
2021-02-02 15:55:25 +00:00
from.pipe(to);
to.pipe(from);
from.on('error', () => {
2021-02-02 21:59:24 +00:00
cleanUpSockets(from, to);
2021-02-02 15:55:25 +00:00
});
to.on('error', () => {
2021-02-02 21:59:24 +00:00
cleanUpSockets(from, to);
2020-02-07 13:04:11 +00:00
});
2021-02-02 00:53:57 +00:00
from.on('close', () => {
2021-02-02 21:59:24 +00:00
cleanUpSockets(from, to);
2021-02-02 15:55:25 +00:00
});
2021-02-02 21:59:24 +00:00
to.on('close', () => {
cleanUpSockets(from, to);
});
from.on('timeout', () => {
cleanUpSockets(from, to);
});
to.on('timeout', () => {
cleanUpSockets(from, to);
});
from.on('end', () => {
cleanUpSockets(from, to);
2022-07-28 23:52:34 +00:00
});
2021-02-02 21:59:24 +00:00
to.on('end', () => {
cleanUpSockets(from, to);
2022-07-28 23:52:34 +00:00
});
2020-02-07 13:04:11 +00:00
})
2022-07-28 22:49:46 +00:00
.listen(this.fromPort);
console.log(`PortProxy -> OK: Now listening on port ${this.fromPort}`);
}
public async stop() {
2019-08-22 13:09:48 +00:00
const done = plugins.smartpromise.defer();
2020-02-23 19:03:25 +00:00
httpServer.close(() => {
netServer.close(() => {
done.resolve();
});
2019-08-22 13:09:48 +00:00
});
await done.promise;
2022-07-28 22:49:46 +00:00
}
2022-07-28 23:52:34 +00:00
}