Compare commits

...

10 Commits

4 changed files with 170 additions and 253 deletions

View File

@ -1,5 +1,39 @@
# Changelog # Changelog
## 2025-03-03 - 3.22.4 - fix(core)
Addressed minor issues in the core modules to improve stability and performance.
## 2025-03-03 - 3.22.3 - fix(core)
Improve connection management and error handling in PortProxy
- Refactored connection cleanup to handle errors more gracefully.
- Introduced comprehensive comments for better code understanding.
- Revised SNI data timeout logic for connection handling.
- Enhanced logging and error reporting during connection management.
- Improved inactivity checks and parity checks for existing connections.
## 2025-03-03 - 3.22.2 - fix(portproxy)
Refactored connection cleanup logic in PortProxy
- Simplified the connection cleanup logic by removing redundant methods.
- Consolidated the cleanup initiation and execution into a single cleanup method.
- Improved error handling by ensuring connections are closed appropriately.
## 2025-03-03 - 3.22.1 - fix(PortProxy)
Fix connection timeout and IP validation handling for PortProxy
- Adjusted initial data timeout setting for SNI-enabled connections in PortProxy.
- Restored IP validation logic to original behavior, ensuring compatibility with domain configurations.
## 2025-03-03 - 3.22.0 - feat(classes.portproxy)
Enhanced PortProxy to support initial data timeout and improved IP handling
- Added `initialDataTimeout` to PortProxy settings for handling data flow in chained proxies.
- Improved IP validation by allowing relaxed checks in chained proxy setups.
- Introduced dynamic logging for connection lifecycle and proxy configurations.
- Enhanced timeout handling for better proxy resilience.
## 2025-03-03 - 3.21.0 - feat(PortProxy) ## 2025-03-03 - 3.21.0 - feat(PortProxy)
Enhancements to connection management in PortProxy Enhancements to connection management in PortProxy

View File

@ -1,6 +1,6 @@
{ {
"name": "@push.rocks/smartproxy", "name": "@push.rocks/smartproxy",
"version": "3.21.0", "version": "3.22.4",
"private": false, "private": false,
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.", "description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartproxy', name: '@push.rocks/smartproxy',
version: '3.21.0', version: '3.22.4',
description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.' description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.'
} }

View File

@ -89,25 +89,24 @@ function extractSNI(buffer: Buffer): string | undefined {
} }
interface IConnectionRecord { interface IConnectionRecord {
id: string; // Unique connection identifier
incoming: plugins.net.Socket; incoming: plugins.net.Socket;
outgoing: plugins.net.Socket | null; outgoing: plugins.net.Socket | null;
incomingStartTime: number; incomingStartTime: number;
outgoingStartTime?: number; outgoingStartTime?: number;
outgoingClosedTime?: number; outgoingClosedTime?: number;
lockedDomain?: string; // Field to lock this connection to the initial SNI lockedDomain?: string; // Used to lock this connection to the initial SNI
connectionClosed: boolean; connectionClosed: boolean; // Flag to prevent multiple cleanup attempts
cleanupTimer?: NodeJS.Timeout; // Timer to force cleanup after max lifetime/inactivity cleanupTimer?: NodeJS.Timeout; // Timer for max lifetime/inactivity
cleanupInitiated: boolean; // Flag to track if cleanup has been initiated but not completed lastActivity: number; // Last activity timestamp for inactivity detection
id: string; // Unique identifier for the connection
lastActivity: number; // Timestamp of last activity on either socket
} }
// Helper: Check if a port falls within any of the given port ranges. // Helper: Check if a port falls within any of the given port ranges
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => { const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
return ranges.some(range => port >= range.from && port <= range.to); return ranges.some(range => port >= range.from && port <= range.to);
}; };
// Helper: Check if a given IP matches any of the glob patterns. // Helper: Check if a given IP matches any of the glob patterns
const isAllowed = (ip: string, patterns: string[]): boolean => { const isAllowed = (ip: string, patterns: string[]): boolean => {
const normalizeIP = (ip: string): string[] => { const normalizeIP = (ip: string): string[] => {
if (ip.startsWith('::ffff:')) { if (ip.startsWith('::ffff:')) {
@ -126,13 +125,13 @@ const isAllowed = (ip: string, patterns: string[]): boolean => {
); );
}; };
// Helper: Check if an IP is allowed considering allowed and blocked glob patterns. // Helper: Check if an IP is allowed considering allowed and blocked glob patterns
const isGlobIPAllowed = (ip: string, allowed: string[], blocked: string[] = []): boolean => { const isGlobIPAllowed = (ip: string, allowed: string[], blocked: string[] = []): boolean => {
if (blocked.length > 0 && isAllowed(ip, blocked)) return false; if (blocked.length > 0 && isAllowed(ip, blocked)) return false;
return isAllowed(ip, allowed); return isAllowed(ip, allowed);
}; };
// Helper: Generate a unique ID for a connection // Helper: Generate a unique connection ID
const generateConnectionId = (): string => { const generateConnectionId = (): string => {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}; };
@ -140,12 +139,11 @@ const generateConnectionId = (): string => {
export class PortProxy { export class PortProxy {
private netServers: plugins.net.Server[] = []; private netServers: plugins.net.Server[] = [];
settings: IPortProxySettings; settings: IPortProxySettings;
// Unified record tracking each connection pair.
private connectionRecords: Map<string, IConnectionRecord> = new Map(); private connectionRecords: Map<string, IConnectionRecord> = new Map();
private connectionLogger: NodeJS.Timeout | null = null; private connectionLogger: NodeJS.Timeout | null = null;
private isShuttingDown: boolean = false; private isShuttingDown: boolean = false;
// Map to track round robin indices for each domain config. // Map to track round robin indices for each domain config
private domainTargetIndices: Map<IDomainConfig, number> = new Map(); private domainTargetIndices: Map<IDomainConfig, number> = new Map();
private terminationStats: { private terminationStats: {
@ -170,77 +168,64 @@ export class PortProxy {
} }
/** /**
* Initiates the cleanup process for a connection. * Cleans up a connection record.
* Sets the flag to prevent duplicate cleanup attempts and schedules actual cleanup. * Destroys both incoming and outgoing sockets, clears timers, and removes the record.
* @param record - The connection record to clean up
* @param reason - Optional reason for cleanup (for logging)
*/ */
private initiateCleanup(record: IConnectionRecord, reason: string = 'normal'): void { private cleanupConnection(record: IConnectionRecord, reason: string = 'normal'): void {
if (record.cleanupInitiated) return; if (!record.connectionClosed) {
record.connectionClosed = true;
record.cleanupInitiated = true;
const remoteIP = record.incoming.remoteAddress || 'unknown'; if (record.cleanupTimer) {
console.log(`Initiating cleanup for connection ${record.id} from ${remoteIP} (reason: ${reason})`); clearTimeout(record.cleanupTimer);
record.cleanupTimer = undefined;
// Execute cleanup immediately to prevent lingering connections }
this.executeCleanup(record);
try {
if (!record.incoming.destroyed) {
// Try graceful shutdown first, then force destroy after a short timeout
record.incoming.end();
setTimeout(() => {
if (record && !record.incoming.destroyed) {
record.incoming.destroy();
}
}, 1000);
}
} catch (err) {
console.log(`Error closing incoming socket: ${err}`);
if (!record.incoming.destroyed) {
record.incoming.destroy();
}
}
try {
if (record.outgoing && !record.outgoing.destroyed) {
// Try graceful shutdown first, then force destroy after a short timeout
record.outgoing.end();
setTimeout(() => {
if (record && record.outgoing && !record.outgoing.destroyed) {
record.outgoing.destroy();
}
}, 1000);
}
} catch (err) {
console.log(`Error closing outgoing socket: ${err}`);
if (record.outgoing && !record.outgoing.destroyed) {
record.outgoing.destroy();
}
}
// Remove the record from the tracking map
this.connectionRecords.delete(record.id);
const remoteIP = record.incoming.remoteAddress || 'unknown';
console.log(`Connection from ${remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`);
}
} }
/** private updateActivity(record: IConnectionRecord): void {
* Executes the actual cleanup of a connection. record.lastActivity = Date.now();
* Destroys sockets, clears timers, and removes the record.
*/
private executeCleanup(record: IConnectionRecord): void {
if (record.connectionClosed) return;
record.connectionClosed = true;
const remoteIP = record.incoming.remoteAddress || 'unknown';
if (record.cleanupTimer) {
clearTimeout(record.cleanupTimer);
record.cleanupTimer = undefined;
}
// End the sockets first to allow for graceful closure
try {
if (!record.incoming.destroyed) {
record.incoming.end();
// Set a safety timeout to force destroy if end doesn't complete
setTimeout(() => {
if (!record.incoming.destroyed) {
console.log(`Forcing destruction of incoming socket for ${remoteIP}`);
record.incoming.destroy();
}
}, 1000);
}
} catch (err) {
console.error(`Error ending incoming socket for ${remoteIP}:`, err);
if (!record.incoming.destroyed) {
record.incoming.destroy();
}
}
try {
if (record.outgoing && !record.outgoing.destroyed) {
record.outgoing.end();
// Set a safety timeout to force destroy if end doesn't complete
setTimeout(() => {
if (record.outgoing && !record.outgoing.destroyed) {
console.log(`Forcing destruction of outgoing socket for ${remoteIP}`);
record.outgoing.destroy();
}
}, 1000);
}
} catch (err) {
console.error(`Error ending outgoing socket for ${remoteIP}:`, err);
if (record.outgoing && !record.outgoing.destroyed) {
record.outgoing.destroy();
}
}
// Remove the record after a delay to ensure all events have propagated
setTimeout(() => {
this.connectionRecords.delete(record.id);
console.log(`Connection ${record.id} from ${remoteIP} fully cleaned up. Active connections: ${this.connectionRecords.size}`);
}, 2000);
} }
private getTargetIP(domainConfig: IDomainConfig): string { private getTargetIP(domainConfig: IDomainConfig): string {
@ -253,27 +238,6 @@ export class PortProxy {
return this.settings.targetIP!; return this.settings.targetIP!;
} }
/**
* Updates the last activity timestamp for a connection record
*/
private updateActivity(record: IConnectionRecord): void {
record.lastActivity = Date.now();
// Reset the inactivity timer if one is set
if (this.settings.maxConnectionLifetime && record.cleanupTimer) {
clearTimeout(record.cleanupTimer);
// Set a new cleanup timer
record.cleanupTimer = setTimeout(() => {
const now = Date.now();
const inactivityTime = now - record.lastActivity;
const remoteIP = record.incoming.remoteAddress || 'unknown';
console.log(`Connection ${record.id} from ${remoteIP} exceeded max lifetime or inactivity period (${inactivityTime}ms), forcing cleanup.`);
this.initiateCleanup(record, 'timeout');
}, this.settings.maxConnectionLifetime);
}
}
public async start() { public async start() {
// Define a unified connection handler for all listening ports. // Define a unified connection handler for all listening ports.
const connectionHandler = (socket: plugins.net.Socket) => { const connectionHandler = (socket: plugins.net.Socket) => {
@ -293,23 +257,28 @@ export class PortProxy {
outgoing: null, outgoing: null,
incomingStartTime: Date.now(), incomingStartTime: Date.now(),
lastActivity: Date.now(), lastActivity: Date.now(),
connectionClosed: false, connectionClosed: false
cleanupInitiated: false
}; };
this.connectionRecords.set(connectionId, connectionRecord); this.connectionRecords.set(connectionId, connectionRecord);
console.log(`New connection ${connectionId} from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
console.log(`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
let initialDataReceived = false; let initialDataReceived = false;
let incomingTerminationReason: string | null = null; let incomingTerminationReason: string | null = null;
let outgoingTerminationReason: string | null = null; let outgoingTerminationReason: string | null = null;
// Local cleanup function that delegates to the class method. // Local function for cleanupOnce
const cleanupOnce = () => {
this.cleanupConnection(connectionRecord);
};
// Define initiateCleanupOnce for compatibility with potential future improvements
const initiateCleanupOnce = (reason: string = 'normal') => { const initiateCleanupOnce = (reason: string = 'normal') => {
this.initiateCleanup(connectionRecord, reason); console.log(`Connection cleanup initiated for ${remoteIP} (${reason})`);
cleanupOnce();
}; };
// Helper to reject an incoming connection. // Helper to reject an incoming connection
const rejectIncomingConnection = (reason: string, logMessage: string) => { const rejectIncomingConnection = (reason: string, logMessage: string) => {
console.log(logMessage); console.log(logMessage);
socket.end(); socket.end();
@ -317,31 +286,25 @@ export class PortProxy {
incomingTerminationReason = reason; incomingTerminationReason = reason;
this.incrementTerminationStat('incoming', reason); this.incrementTerminationStat('incoming', reason);
} }
initiateCleanupOnce(reason); cleanupOnce();
}; };
// Set an initial timeout immediately // Set an initial timeout for SNI data if needed
const initialTimeout = setTimeout(() => { let initialTimeout: NodeJS.Timeout | null = null;
if (!initialDataReceived) { if (this.settings.sniEnabled) {
console.log(`Initial connection timeout for ${remoteIP} (no data received)`); initialTimeout = setTimeout(() => {
if (incomingTerminationReason === null) { if (!initialDataReceived) {
incomingTerminationReason = 'initial_timeout'; console.log(`Initial data timeout for ${remoteIP}`);
this.incrementTerminationStat('incoming', 'initial_timeout'); socket.end();
cleanupOnce();
} }
initiateCleanupOnce('initial_timeout'); }, 5000);
} } else {
}, 5000); initialDataReceived = true;
}
socket.on('error', (err: Error) => { socket.on('error', (err: Error) => {
const errorMessage = initialDataReceived console.log(`Incoming socket error from ${remoteIP}: ${err.message}`);
? `(Immediate) Incoming socket error from ${remoteIP}: ${err.message}`
: `(Premature) Incoming socket error from ${remoteIP} before data received: ${err.message}`;
console.log(errorMessage);
// Clear the initial timeout if it exists
if (initialTimeout) {
clearTimeout(initialTimeout);
}
}); });
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => { const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
@ -350,13 +313,9 @@ export class PortProxy {
if (code === 'ECONNRESET') { if (code === 'ECONNRESET') {
reason = 'econnreset'; reason = 'econnreset';
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`); console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
} else if (code === 'ECONNREFUSED') {
reason = 'econnrefused';
console.log(`ECONNREFUSED on ${side} side from ${remoteIP}: ${err.message}`);
} else { } else {
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`); console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
} }
if (side === 'incoming' && incomingTerminationReason === null) { if (side === 'incoming' && incomingTerminationReason === null) {
incomingTerminationReason = reason; incomingTerminationReason = reason;
this.incrementTerminationStat('incoming', reason); this.incrementTerminationStat('incoming', reason);
@ -364,13 +323,11 @@ export class PortProxy {
outgoingTerminationReason = reason; outgoingTerminationReason = reason;
this.incrementTerminationStat('outgoing', reason); this.incrementTerminationStat('outgoing', reason);
} }
initiateCleanupOnce(reason); initiateCleanupOnce(reason);
}; };
const handleClose = (side: 'incoming' | 'outgoing') => () => { const handleClose = (side: 'incoming' | 'outgoing') => () => {
console.log(`Connection closed on ${side} side from ${remoteIP}`); console.log(`Connection closed on ${side} side from ${remoteIP}`);
if (side === 'incoming' && incomingTerminationReason === null) { if (side === 'incoming' && incomingTerminationReason === null) {
incomingTerminationReason = 'normal'; incomingTerminationReason = 'normal';
this.incrementTerminationStat('incoming', 'normal'); this.incrementTerminationStat('incoming', 'normal');
@ -379,24 +336,8 @@ export class PortProxy {
this.incrementTerminationStat('outgoing', 'normal'); this.incrementTerminationStat('outgoing', 'normal');
// Record the time when outgoing socket closed. // Record the time when outgoing socket closed.
connectionRecord.outgoingClosedTime = Date.now(); connectionRecord.outgoingClosedTime = Date.now();
// If incoming is still active but outgoing closed, set a shorter timeout
if (!connectionRecord.incoming.destroyed) {
console.log(`Outgoing socket closed but incoming still active for ${remoteIP}. Setting cleanup timeout.`);
setTimeout(() => {
if (!connectionRecord.connectionClosed && !connectionRecord.incoming.destroyed) {
console.log(`Incoming socket still active ${Date.now() - connectionRecord.outgoingClosedTime!}ms after outgoing closed for ${remoteIP}. Cleaning up.`);
initiateCleanupOnce('outgoing_closed_timeout');
}
}, 10000); // 10 second timeout instead of waiting for the next parity check
}
}
// If both sides are closed/destroyed, clean up
if ((side === 'incoming' && connectionRecord.outgoing?.destroyed) ||
(side === 'outgoing' && connectionRecord.incoming.destroyed)) {
initiateCleanupOnce('both_closed');
} }
initiateCleanupOnce('closed_' + side);
}; };
/** /**
@ -410,6 +351,7 @@ export class PortProxy {
// Clear the initial timeout since we've received data // Clear the initial timeout since we've received data
if (initialTimeout) { if (initialTimeout) {
clearTimeout(initialTimeout); clearTimeout(initialTimeout);
initialTimeout = null;
} }
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup. // If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
@ -419,7 +361,7 @@ export class PortProxy {
config.domains.some(d => plugins.minimatch(serverName, d)) config.domains.some(d => plugins.minimatch(serverName, d))
) : undefined); ) : undefined);
// Effective IP check: merge allowed IPs with default allowed, and remove blocked IPs. // IP validation is skipped if allowedIPs is empty
if (domainConfig) { if (domainConfig) {
const effectiveAllowedIPs: string[] = [ const effectiveAllowedIPs: string[] = [
...domainConfig.allowedIPs, ...domainConfig.allowedIPs,
@ -429,16 +371,15 @@ export class PortProxy {
...(domainConfig.blockedIPs || []), ...(domainConfig.blockedIPs || []),
...(this.settings.defaultBlockedIPs || []) ...(this.settings.defaultBlockedIPs || [])
]; ];
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
// Skip IP validation if allowedIPs is empty
if (domainConfig.allowedIPs.length > 0 && !isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(', ')}`); return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(', ')}`);
} }
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) { } else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
if (!isGlobIPAllowed(remoteIP, this.settings.defaultAllowedIPs, this.settings.defaultBlockedIPs || [])) { if (!isGlobIPAllowed(remoteIP, this.settings.defaultAllowedIPs, this.settings.defaultBlockedIPs || [])) {
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`); return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`);
} }
} else {
// No domain config and no default allowed IPs - reject the connection
return rejectIncomingConnection('no_config', `Connection rejected: No matching domain configuration or default allowed IPs for ${remoteIP}`);
} }
const targetHost = domainConfig ? this.getTargetIP(domainConfig) : this.settings.targetIP!; const targetHost = domainConfig ? this.getTargetIP(domainConfig) : this.settings.targetIP!;
@ -450,116 +391,57 @@ export class PortProxy {
connectionOptions.localAddress = remoteIP.replace('::ffff:', ''); connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
} }
// Add explicit connection timeout and error handling // Create the target socket and immediately set up data piping
let connectionTimeout: NodeJS.Timeout | null = null;
let connectionSucceeded = false;
// Set connection timeout
connectionTimeout = setTimeout(() => {
if (!connectionSucceeded) {
console.log(`Connection timeout connecting to ${targetHost}:${connectionOptions.port} for ${remoteIP}`);
if (outgoingTerminationReason === null) {
outgoingTerminationReason = 'connection_timeout';
this.incrementTerminationStat('outgoing', 'connection_timeout');
}
initiateCleanupOnce('connection_timeout');
}
}, 5000);
console.log(`Attempting to connect to ${targetHost}:${connectionOptions.port} for client ${remoteIP}...`);
// Create the target socket
const targetSocket = plugins.net.connect(connectionOptions); const targetSocket = plugins.net.connect(connectionOptions);
connectionRecord.outgoing = targetSocket; connectionRecord.outgoing = targetSocket;
connectionRecord.outgoingStartTime = Date.now();
// Handle successful connection // Set up the pipe immediately to ensure data flows without delay
targetSocket.once('connect', () => {
connectionSucceeded = true;
if (connectionTimeout) {
clearTimeout(connectionTimeout);
connectionTimeout = null;
}
connectionRecord.outgoingStartTime = Date.now();
console.log(
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
);
// Setup data flow after confirmed connection
setupDataFlow(targetSocket, initialChunk);
});
// Handle connection errors early
targetSocket.once('error', (err) => {
if (!connectionSucceeded) {
// This is an initial connection error
console.log(`Failed to connect to ${targetHost}:${connectionOptions.port} for ${remoteIP}: ${err.message}`);
if (connectionTimeout) {
clearTimeout(connectionTimeout);
connectionTimeout = null;
}
if (outgoingTerminationReason === null) {
outgoingTerminationReason = 'connection_failed';
this.incrementTerminationStat('outgoing', 'connection_failed');
}
initiateCleanupOnce('connection_failed');
}
// Other errors will be handled by the main error handler
});
};
/**
* Sets up the data flow between sockets after successful connection
*/
const setupDataFlow = (targetSocket: plugins.net.Socket, initialChunk?: Buffer) => {
if (initialChunk) { if (initialChunk) {
socket.unshift(initialChunk); socket.unshift(initialChunk);
} }
// Set appropriate timeouts for both sockets
socket.setTimeout(120000);
targetSocket.setTimeout(120000);
// Set up the pipe in both directions
socket.pipe(targetSocket); socket.pipe(targetSocket);
targetSocket.pipe(socket); targetSocket.pipe(socket);
console.log(
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
);
// Attach error and close handlers // Add appropriate handlers for connection management
socket.on('error', handleError('incoming')); socket.on('error', handleError('incoming'));
targetSocket.on('error', handleError('outgoing')); targetSocket.on('error', handleError('outgoing'));
socket.on('close', handleClose('incoming')); socket.on('close', handleClose('incoming'));
targetSocket.on('close', handleClose('outgoing')); targetSocket.on('close', handleClose('outgoing'));
// Handle timeout events
socket.on('timeout', () => { socket.on('timeout', () => {
console.log(`Timeout on incoming side from ${remoteIP}`); console.log(`Timeout on incoming side from ${remoteIP}`);
if (incomingTerminationReason === null) { if (incomingTerminationReason === null) {
incomingTerminationReason = 'timeout'; incomingTerminationReason = 'timeout';
this.incrementTerminationStat('incoming', 'timeout'); this.incrementTerminationStat('incoming', 'timeout');
} }
initiateCleanupOnce('timeout'); initiateCleanupOnce('timeout_incoming');
}); });
targetSocket.on('timeout', () => { targetSocket.on('timeout', () => {
console.log(`Timeout on outgoing side from ${remoteIP}`); console.log(`Timeout on outgoing side from ${remoteIP}`);
if (outgoingTerminationReason === null) { if (outgoingTerminationReason === null) {
outgoingTerminationReason = 'timeout'; outgoingTerminationReason = 'timeout';
this.incrementTerminationStat('outgoing', 'timeout'); this.incrementTerminationStat('outgoing', 'timeout');
} }
initiateCleanupOnce('timeout'); initiateCleanupOnce('timeout_outgoing');
}); });
socket.on('end', handleClose('incoming'));
targetSocket.on('end', handleClose('outgoing'));
// Track activity for both sockets to reset inactivity timers // Set appropriate timeouts
socket.on('data', (data) => { socket.setTimeout(120000);
this.updateActivity(connectionRecord); targetSocket.setTimeout(120000);
// Update activity for both sockets
socket.on('data', () => {
connectionRecord.lastActivity = Date.now();
}); });
targetSocket.on('data', (data) => { targetSocket.on('data', () => {
this.updateActivity(connectionRecord); connectionRecord.lastActivity = Date.now();
}); });
// Initialize a cleanup timer for max connection lifetime // Initialize a cleanup timer for max connection lifetime
@ -578,7 +460,6 @@ export class PortProxy {
if (this.settings.defaultAllowedIPs && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) { if (this.settings.defaultAllowedIPs && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
console.log(`Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`); console.log(`Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`);
socket.end(); socket.end();
initiateCleanupOnce('rejected');
return; return;
} }
console.log(`Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`); console.log(`Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`);
@ -607,7 +488,6 @@ export class PortProxy {
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) { if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
console.log(`Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(', ')} on port ${localPort}.`); console.log(`Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(', ')} on port ${localPort}.`);
socket.end(); socket.end();
initiateCleanupOnce('rejected');
return; return;
} }
console.log(`Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(', ')}.`); console.log(`Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(', ')}.`);
@ -623,6 +503,11 @@ export class PortProxy {
initialDataReceived = false; initialDataReceived = false;
socket.once('data', (chunk: Buffer) => { socket.once('data', (chunk: Buffer) => {
if (initialTimeout) {
clearTimeout(initialTimeout);
initialTimeout = null;
}
initialDataReceived = true; initialDataReceived = true;
const serverName = extractSNI(chunk) || ''; const serverName = extractSNI(chunk) || '';
// Lock the connection to the negotiated SNI. // Lock the connection to the negotiated SNI.
@ -654,7 +539,7 @@ export class PortProxy {
}); });
} else { } else {
initialDataReceived = true; initialDataReceived = true;
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) { if (!this.settings.defaultAllowedIPs || this.settings.defaultAllowedIPs.length === 0 || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`); return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
} }
setupConnection(''); setupConnection('');
@ -690,7 +575,7 @@ export class PortProxy {
this.netServers.push(server); this.netServers.push(server);
} }
// Log active connection count, run parity checks, and check for connection issues every 10 seconds. // Log active connection count, longest running durations, and run parity checks every 10 seconds.
this.connectionLogger = setInterval(() => { this.connectionLogger = setInterval(() => {
if (this.isShuttingDown) return; if (this.isShuttingDown) return;
@ -710,25 +595,23 @@ export class PortProxy {
maxOutgoing = Math.max(maxOutgoing, now - record.outgoingStartTime); maxOutgoing = Math.max(maxOutgoing, now - record.outgoingStartTime);
} }
// Parity check: if outgoing socket closed and incoming remains active for >30 seconds, trigger cleanup // Parity check: if outgoing socket closed and incoming remains active
if (record.outgoingClosedTime && if (record.outgoingClosedTime &&
!record.incoming.destroyed && !record.incoming.destroyed &&
!record.connectionClosed && !record.connectionClosed &&
!record.cleanupInitiated &&
(now - record.outgoingClosedTime > 30000)) { (now - record.outgoingClosedTime > 30000)) {
const remoteIP = record.incoming.remoteAddress || 'unknown'; const remoteIP = record.incoming.remoteAddress || 'unknown';
console.log(`Parity check triggered: Incoming socket for ${remoteIP} has been active >30s after outgoing closed.`); console.log(`Parity check: Incoming socket for ${remoteIP} still active ${plugins.prettyMs(now - record.outgoingClosedTime)} after outgoing closed.`);
this.initiateCleanup(record, 'parity_check'); this.cleanupConnection(record, 'parity_check');
} }
// Inactivity check: if no activity for a long time but sockets still open // Inactivity check
const inactivityTime = now - record.lastActivity; const inactivityTime = now - record.lastActivity;
if (inactivityTime > 180000 && // 3 minutes if (inactivityTime > 180000 && // 3 minutes
!record.connectionClosed && !record.connectionClosed) {
!record.cleanupInitiated) {
const remoteIP = record.incoming.remoteAddress || 'unknown'; const remoteIP = record.incoming.remoteAddress || 'unknown';
console.log(`Inactivity check triggered: No activity on connection from ${remoteIP} for ${plugins.prettyMs(inactivityTime)}.`); console.log(`Inactivity check: No activity on connection from ${remoteIP} for ${plugins.prettyMs(inactivityTime)}.`);
this.initiateCleanup(record, 'inactivity'); this.cleanupConnection(record, 'inactivity');
} }
} }
@ -763,14 +646,14 @@ export class PortProxy {
await Promise.all(closeServerPromises); await Promise.all(closeServerPromises);
console.log("All servers closed. Cleaning up active connections..."); console.log("All servers closed. Cleaning up active connections...");
// Gracefully close active connections // Clean up active connections
const connectionIds = [...this.connectionRecords.keys()]; const connectionIds = [...this.connectionRecords.keys()];
console.log(`Cleaning up ${connectionIds.length} active connections...`); console.log(`Cleaning up ${connectionIds.length} active connections...`);
for (const id of connectionIds) { for (const id of connectionIds) {
const record = this.connectionRecords.get(id); const record = this.connectionRecords.get(id);
if (record && !record.connectionClosed && !record.cleanupInitiated) { if (record && !record.connectionClosed) {
this.initiateCleanup(record, 'shutdown'); this.cleanupConnection(record, 'shutdown');
} }
} }