fix(socks proxy): destroy sockets on close to avoid hanging (#17349)

This commit is contained in:
Dmitry Gozman 2022-09-14 21:15:46 -07:00 committed by GitHub
parent 016883602d
commit e1a2f7a168
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -294,6 +294,8 @@ export class SocksProxy extends EventEmitter implements SocksConnectionClient {
private _server: net.Server; private _server: net.Server;
private _connections = new Map<string, SocksConnection>(); private _connections = new Map<string, SocksConnection>();
private _sockets = new Set<net.Socket>();
private _closed = false;
constructor() { constructor() {
super(); super();
@ -302,6 +304,14 @@ export class SocksProxy extends EventEmitter implements SocksConnectionClient {
const connection = new SocksConnection(uid, socket, this); const connection = new SocksConnection(uid, socket, this);
this._connections.set(uid, connection); this._connections.set(uid, connection);
}); });
this._server.on('connection', socket => {
if (this._closed) {
socket.destroy();
return;
}
this._sockets.add(socket);
socket.once('close', () => this._sockets.delete(socket));
});
} }
async listen(port: number): Promise<number> { async listen(port: number): Promise<number> {
@ -315,6 +325,10 @@ export class SocksProxy extends EventEmitter implements SocksConnectionClient {
} }
async close() { async close() {
this._closed = true;
for (const socket of this._sockets)
socket.destroy();
this._sockets.clear();
await new Promise(f => this._server.close(f)); await new Promise(f => this._server.close(f));
} }