feat(PortProxy): Add active connection tracking and logging in PortProxy
This commit is contained in:
parent
4854d7c38d
commit
ba787729e8
@ -1,5 +1,12 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2025-02-21 - 3.8.0 - feat(PortProxy)
|
||||||
|
Add active connection tracking and logging in PortProxy
|
||||||
|
|
||||||
|
- Implemented a feature to track active incoming connections in PortProxy.
|
||||||
|
- Active connections are now logged every 10 seconds for monitoring purposes.
|
||||||
|
- Refactored connection handling to ensure proper cleanup and logging.
|
||||||
|
|
||||||
## 2025-02-21 - 3.7.3 - fix(portproxy)
|
## 2025-02-21 - 3.7.3 - fix(portproxy)
|
||||||
Fix handling of connections in PortProxy to improve stability and performance.
|
Fix handling of connections in PortProxy to improve stability and performance.
|
||||||
|
|
||||||
|
@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartproxy',
|
name: '@push.rocks/smartproxy',
|
||||||
version: '3.7.3',
|
version: '3.8.0',
|
||||||
description: 'a proxy for handling high workloads of proxying'
|
description: 'a proxy for handling high workloads of proxying'
|
||||||
}
|
}
|
||||||
|
@ -115,6 +115,9 @@ function extractSNI(buffer: Buffer): string | undefined {
|
|||||||
export class PortProxy {
|
export class PortProxy {
|
||||||
netServer: plugins.net.Server;
|
netServer: plugins.net.Server;
|
||||||
settings: IProxySettings;
|
settings: IProxySettings;
|
||||||
|
// Track active incoming connections
|
||||||
|
private activeConnections: Set<plugins.net.Socket> = new Set();
|
||||||
|
private connectionLogger: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
constructor(settings: IProxySettings) {
|
constructor(settings: IProxySettings) {
|
||||||
this.settings = {
|
this.settings = {
|
||||||
@ -161,81 +164,73 @@ export class PortProxy {
|
|||||||
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
||||||
};
|
};
|
||||||
|
|
||||||
// Always create a plain net server for TLS passthrough.
|
// Create a plain net server for TLS passthrough.
|
||||||
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
|
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
|
||||||
const remoteIP = socket.remoteAddress || '';
|
const remoteIP = socket.remoteAddress || '';
|
||||||
|
|
||||||
// If SNI is enabled, we peek at the first chunk to extract the SNI.
|
// Track the new incoming connection.
|
||||||
if (this.settings.sniEnabled) {
|
this.activeConnections.add(socket);
|
||||||
socket.once('data', (chunk: Buffer) => {
|
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
|
||||||
// Try to extract the server name from the ClientHello.
|
|
||||||
const serverName = extractSNI(chunk) || '';
|
|
||||||
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
|
||||||
|
|
||||||
// Check if the IP is allowed by default.
|
// Flag to ensure cleanup happens only once.
|
||||||
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
let connectionClosed = false;
|
||||||
if (!isDefaultAllowed && serverName) {
|
const cleanupOnce = () => {
|
||||||
const domainConfig = findMatchingDomain(serverName);
|
if (!connectionClosed) {
|
||||||
if (!domainConfig) {
|
connectionClosed = true;
|
||||||
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
|
cleanUpSockets(socket, to);
|
||||||
socket.end();
|
if (this.activeConnections.has(socket)) {
|
||||||
return;
|
this.activeConnections.delete(socket);
|
||||||
}
|
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
|
||||||
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
}
|
||||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
}
|
||||||
socket.end();
|
};
|
||||||
return;
|
|
||||||
}
|
let to: plugins.net.Socket;
|
||||||
} else if (!isDefaultAllowed && !serverName) {
|
|
||||||
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
|
||||||
|
const code = (err as any).code;
|
||||||
|
if (code === 'ECONNRESET') {
|
||||||
|
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
|
||||||
|
} else {
|
||||||
|
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
|
||||||
|
}
|
||||||
|
cleanupOnce();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleClose = (side: 'incoming' | 'outgoing') => () => {
|
||||||
|
console.log(`Connection closed on ${side} side from ${remoteIP}`);
|
||||||
|
cleanupOnce();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Setup connection, optionally accepting the initial data chunk.
|
||||||
|
const setupConnection = (serverName: string, initialChunk?: Buffer) => {
|
||||||
|
// Check if the IP is allowed by default.
|
||||||
|
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
||||||
|
if (!isDefaultAllowed && serverName) {
|
||||||
|
const domainConfig = findMatchingDomain(serverName);
|
||||||
|
if (!domainConfig) {
|
||||||
|
console.log(`Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
|
||||||
socket.end();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
} else {
|
|
||||||
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
|
||||||
}
|
}
|
||||||
|
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
||||||
// Determine target host.
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
||||||
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
socket.end();
|
||||||
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
return;
|
||||||
|
|
||||||
// Create connection options.
|
|
||||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
|
||||||
host: targetHost,
|
|
||||||
port: this.settings.toPort,
|
|
||||||
};
|
|
||||||
if (this.settings.preserveSourceIP) {
|
|
||||||
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
|
||||||
}
|
}
|
||||||
|
} else if (!isDefaultAllowed && !serverName) {
|
||||||
const to = plugins.net.connect(connectionOptions);
|
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
||||||
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
|
||||||
|
|
||||||
// Unshift the data chunk back so that the TLS handshake can complete at the backend.
|
|
||||||
socket.unshift(chunk);
|
|
||||||
socket.setTimeout(120000);
|
|
||||||
socket.pipe(to);
|
|
||||||
to.pipe(socket);
|
|
||||||
|
|
||||||
const errorHandler = () => {
|
|
||||||
cleanUpSockets(socket, to);
|
|
||||||
};
|
|
||||||
socket.on('error', errorHandler);
|
|
||||||
to.on('error', errorHandler);
|
|
||||||
socket.on('close', errorHandler);
|
|
||||||
to.on('close', errorHandler);
|
|
||||||
socket.on('timeout', errorHandler);
|
|
||||||
to.on('timeout', errorHandler);
|
|
||||||
socket.on('end', errorHandler);
|
|
||||||
to.on('end', errorHandler);
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// If SNI is not enabled, use defaultAllowedIPs check.
|
|
||||||
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
|
||||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
|
||||||
socket.end();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
|
} else {
|
||||||
|
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
||||||
}
|
}
|
||||||
const targetHost = this.settings.toHost!;
|
|
||||||
|
// Determine target host.
|
||||||
|
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
||||||
|
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
||||||
|
|
||||||
|
// Create connection options.
|
||||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||||
host: targetHost,
|
host: targetHost,
|
||||||
port: this.settings.toPort,
|
port: this.settings.toPort,
|
||||||
@ -243,22 +238,46 @@ export class PortProxy {
|
|||||||
if (this.settings.preserveSourceIP) {
|
if (this.settings.preserveSourceIP) {
|
||||||
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
||||||
}
|
}
|
||||||
const to = plugins.net.connect(connectionOptions);
|
|
||||||
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}`);
|
// Establish outgoing connection.
|
||||||
|
to = plugins.net.connect(connectionOptions);
|
||||||
|
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
||||||
|
|
||||||
|
// Push back the initial chunk if provided.
|
||||||
|
if (initialChunk) {
|
||||||
|
socket.unshift(initialChunk);
|
||||||
|
}
|
||||||
socket.setTimeout(120000);
|
socket.setTimeout(120000);
|
||||||
socket.pipe(to);
|
socket.pipe(to);
|
||||||
to.pipe(socket);
|
to.pipe(socket);
|
||||||
const errorHandler = () => {
|
|
||||||
cleanUpSockets(socket, to);
|
// Attach error and close handlers for both sockets.
|
||||||
};
|
socket.on('error', handleError('incoming'));
|
||||||
socket.on('error', errorHandler);
|
to.on('error', handleError('outgoing'));
|
||||||
to.on('error', errorHandler);
|
socket.on('close', handleClose('incoming'));
|
||||||
socket.on('close', errorHandler);
|
to.on('close', handleClose('outgoing'));
|
||||||
to.on('close', errorHandler);
|
socket.on('timeout', handleError('incoming'));
|
||||||
socket.on('timeout', errorHandler);
|
to.on('timeout', handleError('outgoing'));
|
||||||
to.on('timeout', errorHandler);
|
socket.on('end', handleClose('incoming'));
|
||||||
socket.on('end', errorHandler);
|
to.on('end', handleClose('outgoing'));
|
||||||
to.on('end', errorHandler);
|
};
|
||||||
|
|
||||||
|
// For SNI-enabled connections, peek at the first chunk.
|
||||||
|
if (this.settings.sniEnabled) {
|
||||||
|
socket.once('data', (chunk: Buffer) => {
|
||||||
|
// Try to extract the server name from the ClientHello.
|
||||||
|
const serverName = extractSNI(chunk) || '';
|
||||||
|
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
||||||
|
setupConnection(serverName, chunk);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// For non-SNI connections, simply check defaultAllowedIPs.
|
||||||
|
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||||
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
||||||
|
socket.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setupConnection('');
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.on('error', (err: Error) => {
|
.on('error', (err: Error) => {
|
||||||
@ -267,6 +286,11 @@ export class PortProxy {
|
|||||||
.listen(this.settings.fromPort, () => {
|
.listen(this.settings.fromPort, () => {
|
||||||
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Log active connection count every 10 seconds.
|
||||||
|
this.connectionLogger = setInterval(() => {
|
||||||
|
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}`);
|
||||||
|
}, 10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop() {
|
public async stop() {
|
||||||
@ -274,6 +298,10 @@ export class PortProxy {
|
|||||||
this.netServer.close(() => {
|
this.netServer.close(() => {
|
||||||
done.resolve();
|
done.resolve();
|
||||||
});
|
});
|
||||||
|
if (this.connectionLogger) {
|
||||||
|
clearInterval(this.connectionLogger);
|
||||||
|
this.connectionLogger = null;
|
||||||
|
}
|
||||||
await done.promise;
|
await done.promise;
|
||||||
}
|
}
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user