Compare commits

...

16 Commits

Author SHA1 Message Date
e47436608f 3.10.1 2025-02-22 13:22:26 +00:00
128f8203ac fix(PortProxy): Improve socket cleanup logic to prevent potential resource leaks 2025-02-22 13:22:26 +00:00
c7697eca84 3.10.0 2025-02-22 05:46:30 +00:00
71b5237cd4 feat(smartproxy.portproxy): Enhance PortProxy with detailed connection statistics and termination tracking 2025-02-22 05:46:30 +00:00
2df2f0ceaf 3.9.4 2025-02-22 05:41:29 +00:00
2b266ca779 fix(PortProxy): Ensure proper cleanup on connection rejection in PortProxy 2025-02-22 05:41:29 +00:00
c2547036fd 3.9.3 2025-02-21 23:57:54 +00:00
a8131ece26 fix(PortProxy): Fix handling of optional outgoing socket in PortProxy 2025-02-21 23:57:54 +00:00
ad8c667dec 3.9.2 2025-02-21 23:33:16 +00:00
942e0649c8 fix(PortProxy): Improve timeout handling for port proxy connections 2025-02-21 23:33:15 +00:00
59625167b4 3.9.1 2025-02-21 23:30:51 +00:00
385d984727 fix(dependencies): Ensure correct ordering of dependencies and improve logging format. 2025-02-21 23:30:51 +00:00
a959c2ad0e 3.9.0 2025-02-21 23:18:17 +00:00
88f5436c9a feat(smartproxy.portproxy): Add logging of connection durations to PortProxy 2025-02-21 23:18:17 +00:00
06101cd1b1 3.8.1 2025-02-21 23:11:14 +00:00
438d65107d fix(plugins): Simplified plugin import structure across codebase 2025-02-21 23:11:13 +00:00
9 changed files with 204 additions and 34 deletions

View File

@ -1,5 +1,55 @@
# Changelog
## 2025-02-22 - 3.10.1 - fix(PortProxy)
Improve socket cleanup logic to prevent potential resource leaks
- Updated socket cleanup in PortProxy to ensure sockets are forcefully destroyed if not already destroyed.
## 2025-02-22 - 3.10.0 - feat(smartproxy.portproxy)
Enhance PortProxy with detailed connection statistics and termination tracking
- Added tracking of termination statistics for incoming and outgoing connections
- Enhanced logging to include detailed termination statistics
- Introduced helpers to update and log termination stats
- Retained detailed connection duration and active connection logging
## 2025-02-22 - 3.9.4 - fix(PortProxy)
Ensure proper cleanup on connection rejection in PortProxy
- Added cleanup calls after socket end in connection rejection scenarios within PortProxy
## 2025-02-21 - 3.9.3 - fix(PortProxy)
Fix handling of optional outgoing socket in PortProxy
- Refactored the cleanUpSockets function to correctly handle cases where the outgoing socket may be undefined.
- Ensured correct handling of socket events with non-null assertions where applicable.
- Improved robustness in connection establishment and cleanup processes.
## 2025-02-21 - 3.9.2 - fix(PortProxy)
Improve timeout handling for port proxy connections
- Added console logging for both incoming and outgoing side timeouts in the PortProxy class.
- Updated the timeout event handlers to ensure proper cleanup of connections.
## 2025-02-21 - 3.9.1 - fix(dependencies)
Ensure correct ordering of dependencies and improve logging format.
- Reorder dependencies in package.json for better readability.
- Use pretty-ms for displaying time durations in logs.
## 2025-02-21 - 3.9.0 - feat(smartproxy.portproxy)
Add logging of connection durations to PortProxy
- Track start times for incoming and outgoing connections.
- Log duration of longest running incoming and outgoing connections every 10 seconds.
## 2025-02-21 - 3.8.1 - fix(plugins)
Simplified plugin import structure across codebase
- Consolidated plugin imports under a single 'plugins.ts' file.
- Replaced individual plugin imports in smartproxy files with the consolidated plugin imports.
- Fixed error handling for early socket errors in PortProxy setup.
## 2025-02-21 - 3.8.0 - feat(PortProxy)
Add active connection tracking and logging in PortProxy

View File

@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartproxy",
"version": "3.8.0",
"version": "3.10.1",
"private": false,
"description": "a proxy for handling high workloads of proxying",
"main": "dist_ts/index.js",
@ -29,10 +29,11 @@
"@push.rocks/smartrequest": "^2.0.23",
"@push.rocks/smartstring": "^4.0.15",
"@tsclass/tsclass": "^4.4.0",
"@types/minimatch": "^5.1.2",
"@types/ws": "^8.5.14",
"ws": "^8.18.0",
"minimatch": "^9.0.3",
"@types/minimatch": "^5.1.2"
"pretty-ms": "^9.2.0",
"ws": "^8.18.0"
},
"files": [
"ts/**/*",

3
pnpm-lock.yaml generated
View File

@ -35,6 +35,9 @@ importers:
minimatch:
specifier: ^9.0.3
version: 9.0.5
pretty-ms:
specifier: ^9.2.0
version: 9.2.0
ws:
specifier: ^8.18.0
version: 8.18.0

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartproxy',
version: '3.8.0',
version: '3.10.1',
description: 'a proxy for handling high workloads of proxying'
}

View File

@ -22,8 +22,9 @@ import * as smartstring from '@push.rocks/smartstring';
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
// third party scope
import prettyMs from 'pretty-ms';
import * as ws from 'ws';
import wsDefault from 'ws';
import { minimatch } from 'minimatch';
export { wsDefault, ws, minimatch };
export { prettyMs, ws, wsDefault, minimatch };

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js';
import * as plugins from './plugins.js';
import { ProxyRouter } from './smartproxy.classes.router.js';
import * as fs from 'fs';
import * as path from 'path';

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js';
import * as plugins from './plugins.js';
export class ProxyRouter {
public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js';
import * as plugins from './plugins.js';
export class SslRedirect {
httpServer: plugins.http.Server;

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js';
import * as plugins from './plugins.js';
export interface IDomainConfig {
domain: string; // glob pattern for domain
@ -117,8 +117,21 @@ export class PortProxy {
settings: IProxySettings;
// Track active incoming connections
private activeConnections: Set<plugins.net.Socket> = new Set();
// Record start times for incoming connections
private incomingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
// Record start times for outgoing connections
private outgoingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
private connectionLogger: NodeJS.Timeout | null = null;
// Overall termination statistics
private terminationStats: {
incoming: Record<string, number>;
outgoing: Record<string, number>;
} = {
incoming: {},
outgoing: {},
};
constructor(settings: IProxySettings) {
this.settings = {
...settings,
@ -126,16 +139,24 @@ export class PortProxy {
};
}
// Helper to update termination stats.
private incrementTerminationStat(side: 'incoming' | 'outgoing', reason: string): void {
if (!this.terminationStats[side][reason]) {
this.terminationStats[side][reason] = 1;
} else {
this.terminationStats[side][reason]++;
}
}
public async start() {
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => {
from.end();
to.end();
from.removeAllListeners();
to.removeAllListeners();
from.unpipe();
to.unpipe();
from.destroy();
to.destroy();
// Adjusted cleanUpSockets: forcefully destroy both sockets if they haven't been destroyed.
const cleanUpSockets = (from: plugins.net.Socket, to?: plugins.net.Socket) => {
if (!from.destroyed) {
from.destroy();
}
if (to && !to.destroyed) {
to.destroy();
}
};
const normalizeIP = (ip: string): string[] => {
@ -167,17 +188,38 @@ export class PortProxy {
// Create a plain net server for TLS passthrough.
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
const remoteIP = socket.remoteAddress || '';
// Track the new incoming connection.
// Record start time for the incoming connection.
this.activeConnections.add(socket);
this.incomingConnectionTimes.set(socket, Date.now());
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
// Flag to ensure cleanup happens only once.
// Flag to detect if we've received the first data chunk.
let initialDataReceived = false;
// Local termination reason trackers for each side.
let incomingTermReason: string | null = null;
let outgoingTermReason: string | null = null;
// Immediately attach an error handler to catch early errors.
socket.on('error', (err: Error) => {
if (!initialDataReceived) {
console.log(`(Premature) Incoming socket error from ${remoteIP} before data received: ${err.message}`);
} else {
console.log(`(Immediate) Incoming socket error from ${remoteIP}: ${err.message}`);
}
});
// Ensure cleanup happens only once.
let connectionClosed = false;
const cleanupOnce = () => {
if (!connectionClosed) {
connectionClosed = true;
cleanUpSockets(socket, to);
cleanUpSockets(socket, to || undefined);
this.incomingConnectionTimes.delete(socket);
if (to) {
this.outgoingConnectionTimes.delete(to);
}
if (this.activeConnections.has(socket)) {
this.activeConnections.delete(socket);
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
@ -185,20 +227,39 @@ export class PortProxy {
}
};
let to: plugins.net.Socket;
// Outgoing connection placeholder.
let to: plugins.net.Socket | null = null;
// Handle errors by recording termination reason and cleaning up.
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
const code = (err as any).code;
let reason = 'error';
if (code === 'ECONNRESET') {
reason = 'econnreset';
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
} else {
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
}
if (side === 'incoming' && incomingTermReason === null) {
incomingTermReason = reason;
this.incrementTerminationStat('incoming', reason);
} else if (side === 'outgoing' && outgoingTermReason === null) {
outgoingTermReason = reason;
this.incrementTerminationStat('outgoing', reason);
}
cleanupOnce();
};
// Handle close events. If no termination reason was recorded, mark as "normal".
const handleClose = (side: 'incoming' | 'outgoing') => () => {
console.log(`Connection closed on ${side} side from ${remoteIP}`);
if (side === 'incoming' && incomingTermReason === null) {
incomingTermReason = 'normal';
this.incrementTerminationStat('incoming', 'normal');
} else if (side === 'outgoing' && outgoingTermReason === null) {
outgoingTermReason = 'normal';
this.incrementTerminationStat('outgoing', 'normal');
}
cleanupOnce();
};
@ -211,16 +272,31 @@ export class PortProxy {
if (!domainConfig) {
console.log(`Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
socket.end();
if (incomingTermReason === null) {
incomingTermReason = 'rejected';
this.incrementTerminationStat('incoming', 'rejected');
}
cleanupOnce();
return;
}
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
socket.end();
if (incomingTermReason === null) {
incomingTermReason = 'rejected';
this.incrementTerminationStat('incoming', 'rejected');
}
cleanupOnce();
return;
}
} else if (!isDefaultAllowed && !serverName) {
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
socket.end();
if (incomingTermReason === null) {
incomingTermReason = 'rejected';
this.incrementTerminationStat('incoming', 'rejected');
}
cleanupOnce();
return;
} else {
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
@ -241,6 +317,9 @@ export class PortProxy {
// Establish outgoing connection.
to = plugins.net.connect(connectionOptions);
if (to) {
this.outgoingConnectionTimes.set(to, Date.now());
}
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
// Push back the initial chunk if provided.
@ -248,33 +327,53 @@ export class PortProxy {
socket.unshift(initialChunk);
}
socket.setTimeout(120000);
socket.pipe(to);
to.pipe(socket);
socket.pipe(to!);
to!.pipe(socket);
// Attach error and close handlers for both sockets.
// Attach event handlers for both sockets.
socket.on('error', handleError('incoming'));
to.on('error', handleError('outgoing'));
to!.on('error', handleError('outgoing'));
socket.on('close', handleClose('incoming'));
to.on('close', handleClose('outgoing'));
socket.on('timeout', handleError('incoming'));
to.on('timeout', handleError('outgoing'));
to!.on('close', handleClose('outgoing'));
socket.on('timeout', () => {
console.log(`Timeout on incoming side from ${remoteIP}`);
if (incomingTermReason === null) {
incomingTermReason = 'timeout';
this.incrementTerminationStat('incoming', 'timeout');
}
cleanupOnce();
});
to!.on('timeout', () => {
console.log(`Timeout on outgoing side from ${remoteIP}`);
if (outgoingTermReason === null) {
outgoingTermReason = 'timeout';
this.incrementTerminationStat('outgoing', 'timeout');
}
cleanupOnce();
});
socket.on('end', handleClose('incoming'));
to.on('end', handleClose('outgoing'));
to!.on('end', handleClose('outgoing'));
};
// 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.
initialDataReceived = true;
const serverName = extractSNI(chunk) || '';
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
setupConnection(serverName, chunk);
});
} else {
// For non-SNI connections, simply check defaultAllowedIPs.
initialDataReceived = true;
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
socket.end();
if (incomingTermReason === null) {
incomingTermReason = 'rejected';
this.incrementTerminationStat('incoming', 'rejected');
}
cleanupOnce();
return;
}
setupConnection('');
@ -287,9 +386,25 @@ export class PortProxy {
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
});
// Log active connection count every 10 seconds.
// Log active connection count, longest running connection durations,
// and termination statistics every 10 seconds.
this.connectionLogger = setInterval(() => {
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}`);
const now = Date.now();
let maxIncoming = 0;
for (const startTime of this.incomingConnectionTimes.values()) {
const duration = now - startTime;
if (duration > maxIncoming) {
maxIncoming = duration;
}
}
let maxOutgoing = 0;
for (const startTime of this.outgoingConnectionTimes.values()) {
const duration = now - startTime;
if (duration > maxOutgoing) {
maxOutgoing = duration;
}
}
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}. Longest running incoming: ${plugins.prettyMs(maxIncoming)}, outgoing: ${plugins.prettyMs(maxOutgoing)}. Termination stats (incoming): ${JSON.stringify(this.terminationStats.incoming)}, (outgoing): ${JSON.stringify(this.terminationStats.outgoing)}`);
}, 10000);
}