1739 lines
66 KiB
TypeScript
1739 lines
66 KiB
TypeScript
import * as plugins from './plugins.js';
|
|
|
|
/** Domain configuration with per-domain allowed port ranges */
|
|
export interface IDomainConfig {
|
|
domains: string[]; // Glob patterns for domain(s)
|
|
allowedIPs: string[]; // Glob patterns for allowed IPs
|
|
blockedIPs?: string[]; // Glob patterns for blocked IPs
|
|
targetIPs?: string[]; // If multiple targetIPs are given, use round robin.
|
|
portRanges?: Array<{ from: number; to: number }>; // Optional port ranges
|
|
// Allow domain-specific timeout override
|
|
connectionTimeout?: number; // Connection timeout override (ms)
|
|
}
|
|
|
|
/** Port proxy settings including global allowed port ranges */
|
|
export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|
fromPort: number;
|
|
toPort: number;
|
|
targetIP?: string; // Global target host to proxy to, defaults to 'localhost'
|
|
domainConfigs: IDomainConfig[];
|
|
sniEnabled?: boolean;
|
|
defaultAllowedIPs?: string[];
|
|
defaultBlockedIPs?: string[];
|
|
preserveSourceIP?: boolean;
|
|
|
|
// Timeout settings
|
|
initialDataTimeout?: number; // Timeout for initial data/SNI (ms), default: 60000 (60s)
|
|
socketTimeout?: number; // Socket inactivity timeout (ms), default: 3600000 (1h)
|
|
inactivityCheckInterval?: number; // How often to check for inactive connections (ms), default: 60000 (60s)
|
|
maxConnectionLifetime?: number; // Default max connection lifetime (ms), default: 86400000 (24h)
|
|
inactivityTimeout?: number; // Inactivity timeout (ms), default: 14400000 (4h)
|
|
|
|
gracefulShutdownTimeout?: number; // (ms) maximum time to wait for connections to close during shutdown
|
|
globalPortRanges: Array<{ from: number; to: number }>; // Global allowed port ranges
|
|
forwardAllGlobalRanges?: boolean; // When true, forwards all connections on global port ranges to the global targetIP
|
|
|
|
// Socket optimization settings
|
|
noDelay?: boolean; // Disable Nagle's algorithm (default: true)
|
|
keepAlive?: boolean; // Enable TCP keepalive (default: true)
|
|
keepAliveInitialDelay?: number; // Initial delay before sending keepalive probes (ms)
|
|
maxPendingDataSize?: number; // Maximum bytes to buffer during connection setup
|
|
|
|
// Enhanced features
|
|
disableInactivityCheck?: boolean; // Disable inactivity checking entirely
|
|
enableKeepAliveProbes?: boolean; // Enable TCP keep-alive probes
|
|
enableDetailedLogging?: boolean; // Enable detailed connection logging
|
|
enableTlsDebugLogging?: boolean; // Enable TLS handshake debug logging
|
|
enableRandomizedTimeouts?: boolean; // Randomize timeouts slightly to prevent thundering herd
|
|
|
|
// Rate limiting and security
|
|
maxConnectionsPerIP?: number; // Maximum simultaneous connections from a single IP
|
|
connectionRateLimitPerMinute?: number; // Max new connections per minute from a single IP
|
|
|
|
// Enhanced keep-alive settings
|
|
keepAliveTreatment?: 'standard' | 'extended' | 'immortal'; // How to treat keep-alive connections
|
|
keepAliveInactivityMultiplier?: number; // Multiplier for inactivity timeout for keep-alive connections
|
|
extendedKeepAliveLifetime?: number; // Extended lifetime for keep-alive connections (ms)
|
|
}
|
|
|
|
/**
|
|
* Enhanced connection record
|
|
*/
|
|
interface IConnectionRecord {
|
|
id: string; // Unique connection identifier
|
|
incoming: plugins.net.Socket;
|
|
outgoing: plugins.net.Socket | null;
|
|
incomingStartTime: number;
|
|
outgoingStartTime?: number;
|
|
outgoingClosedTime?: number;
|
|
lockedDomain?: string; // Used to lock this connection to the initial SNI
|
|
connectionClosed: boolean; // Flag to prevent multiple cleanup attempts
|
|
cleanupTimer?: NodeJS.Timeout; // Timer for max lifetime/inactivity
|
|
lastActivity: number; // Last activity timestamp for inactivity detection
|
|
pendingData: Buffer[]; // Buffer to hold data during connection setup
|
|
pendingDataSize: number; // Track total size of pending data
|
|
|
|
// Enhanced tracking fields
|
|
bytesReceived: number; // Total bytes received
|
|
bytesSent: number; // Total bytes sent
|
|
remoteIP: string; // Remote IP (cached for logging after socket close)
|
|
localPort: number; // Local port (cached for logging)
|
|
isTLS: boolean; // Whether this connection is a TLS connection
|
|
tlsHandshakeComplete: boolean; // Whether the TLS handshake is complete
|
|
hasReceivedInitialData: boolean; // Whether initial data has been received
|
|
domainConfig?: IDomainConfig; // Associated domain config for this connection
|
|
|
|
// Keep-alive tracking
|
|
hasKeepAlive: boolean; // Whether keep-alive is enabled for this connection
|
|
inactivityWarningIssued?: boolean; // Whether an inactivity warning has been issued
|
|
incomingTerminationReason?: string | null; // Reason for incoming termination
|
|
outgoingTerminationReason?: string | null; // Reason for outgoing termination
|
|
}
|
|
|
|
/**
|
|
* Extracts the SNI (Server Name Indication) from a TLS ClientHello packet.
|
|
* Enhanced for robustness and detailed logging.
|
|
* @param buffer - Buffer containing the TLS ClientHello.
|
|
* @param enableLogging - Whether to enable detailed logging.
|
|
* @returns The server name if found, otherwise undefined.
|
|
*/
|
|
function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | undefined {
|
|
try {
|
|
// Check if buffer is too small for TLS
|
|
if (buffer.length < 5) {
|
|
if (enableLogging) console.log('Buffer too small for TLS header');
|
|
return undefined;
|
|
}
|
|
|
|
// Check record type (has to be handshake - 22)
|
|
const recordType = buffer.readUInt8(0);
|
|
if (recordType !== 22) {
|
|
if (enableLogging) console.log(`Not a TLS handshake. Record type: ${recordType}`);
|
|
return undefined;
|
|
}
|
|
|
|
// Check TLS version (has to be 3.1 or higher)
|
|
const majorVersion = buffer.readUInt8(1);
|
|
const minorVersion = buffer.readUInt8(2);
|
|
if (enableLogging) console.log(`TLS Version: ${majorVersion}.${minorVersion}`);
|
|
|
|
// Check record length
|
|
const recordLength = buffer.readUInt16BE(3);
|
|
if (buffer.length < 5 + recordLength) {
|
|
if (enableLogging)
|
|
console.log(
|
|
`Buffer too small for TLS record. Expected: ${5 + recordLength}, Got: ${buffer.length}`
|
|
);
|
|
return undefined;
|
|
}
|
|
|
|
let offset = 5;
|
|
const handshakeType = buffer.readUInt8(offset);
|
|
if (handshakeType !== 1) {
|
|
if (enableLogging) console.log(`Not a ClientHello. Handshake type: ${handshakeType}`);
|
|
return undefined;
|
|
}
|
|
|
|
offset += 4; // Skip handshake header (type + length)
|
|
|
|
// Client version
|
|
const clientMajorVersion = buffer.readUInt8(offset);
|
|
const clientMinorVersion = buffer.readUInt8(offset + 1);
|
|
if (enableLogging) console.log(`Client Version: ${clientMajorVersion}.${clientMinorVersion}`);
|
|
|
|
offset += 2 + 32; // Skip client version and random
|
|
|
|
// Session ID
|
|
const sessionIDLength = buffer.readUInt8(offset);
|
|
if (enableLogging) console.log(`Session ID Length: ${sessionIDLength}`);
|
|
offset += 1 + sessionIDLength; // Skip session ID
|
|
|
|
// Cipher suites
|
|
if (offset + 2 > buffer.length) {
|
|
if (enableLogging) console.log('Buffer too small for cipher suites length');
|
|
return undefined;
|
|
}
|
|
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
|
if (enableLogging) console.log(`Cipher Suites Length: ${cipherSuitesLength}`);
|
|
offset += 2 + cipherSuitesLength; // Skip cipher suites
|
|
|
|
// Compression methods
|
|
if (offset + 1 > buffer.length) {
|
|
if (enableLogging) console.log('Buffer too small for compression methods length');
|
|
return undefined;
|
|
}
|
|
const compressionMethodsLength = buffer.readUInt8(offset);
|
|
if (enableLogging) console.log(`Compression Methods Length: ${compressionMethodsLength}`);
|
|
offset += 1 + compressionMethodsLength; // Skip compression methods
|
|
|
|
// Extensions
|
|
if (offset + 2 > buffer.length) {
|
|
if (enableLogging) console.log('Buffer too small for extensions length');
|
|
return undefined;
|
|
}
|
|
const extensionsLength = buffer.readUInt16BE(offset);
|
|
if (enableLogging) console.log(`Extensions Length: ${extensionsLength}`);
|
|
offset += 2;
|
|
const extensionsEnd = offset + extensionsLength;
|
|
|
|
if (extensionsEnd > buffer.length) {
|
|
if (enableLogging)
|
|
console.log(
|
|
`Buffer too small for extensions. Expected end: ${extensionsEnd}, Buffer length: ${buffer.length}`
|
|
);
|
|
return undefined;
|
|
}
|
|
|
|
// Parse extensions
|
|
while (offset + 4 <= extensionsEnd) {
|
|
const extensionType = buffer.readUInt16BE(offset);
|
|
const extensionLength = buffer.readUInt16BE(offset + 2);
|
|
|
|
if (enableLogging)
|
|
console.log(`Extension Type: 0x${extensionType.toString(16)}, Length: ${extensionLength}`);
|
|
|
|
offset += 4;
|
|
|
|
if (extensionType === 0x0000) {
|
|
// SNI extension
|
|
if (offset + 2 > buffer.length) {
|
|
if (enableLogging) console.log('Buffer too small for SNI list length');
|
|
return undefined;
|
|
}
|
|
|
|
const sniListLength = buffer.readUInt16BE(offset);
|
|
if (enableLogging) console.log(`SNI List Length: ${sniListLength}`);
|
|
offset += 2;
|
|
const sniListEnd = offset + sniListLength;
|
|
|
|
if (sniListEnd > buffer.length) {
|
|
if (enableLogging)
|
|
console.log(
|
|
`Buffer too small for SNI list. Expected end: ${sniListEnd}, Buffer length: ${buffer.length}`
|
|
);
|
|
return undefined;
|
|
}
|
|
|
|
while (offset + 3 < sniListEnd) {
|
|
const nameType = buffer.readUInt8(offset++);
|
|
const nameLen = buffer.readUInt16BE(offset);
|
|
offset += 2;
|
|
|
|
if (enableLogging) console.log(`Name Type: ${nameType}, Name Length: ${nameLen}`);
|
|
|
|
if (nameType === 0) {
|
|
// host_name
|
|
if (offset + nameLen > buffer.length) {
|
|
if (enableLogging)
|
|
console.log(
|
|
`Buffer too small for hostname. Expected: ${offset + nameLen}, Got: ${
|
|
buffer.length
|
|
}`
|
|
);
|
|
return undefined;
|
|
}
|
|
|
|
const serverName = buffer.toString('utf8', offset, offset + nameLen);
|
|
if (enableLogging) console.log(`Extracted SNI: ${serverName}`);
|
|
return serverName;
|
|
}
|
|
|
|
offset += nameLen;
|
|
}
|
|
break;
|
|
} else {
|
|
offset += extensionLength;
|
|
}
|
|
}
|
|
|
|
if (enableLogging) console.log('No SNI extension found');
|
|
return undefined;
|
|
} catch (err) {
|
|
console.log(`Error extracting SNI: ${err}`);
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
// Helper: Check if a port falls within any of the given port ranges
|
|
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
|
return ranges.some((range) => port >= range.from && port <= range.to);
|
|
};
|
|
|
|
// Helper: Check if a given IP matches any of the glob patterns
|
|
const isAllowed = (ip: string, patterns: string[]): boolean => {
|
|
if (!ip || !patterns || patterns.length === 0) return false;
|
|
|
|
const normalizeIP = (ip: string): string[] => {
|
|
if (!ip) return [];
|
|
if (ip.startsWith('::ffff:')) {
|
|
const ipv4 = ip.slice(7);
|
|
return [ip, ipv4];
|
|
}
|
|
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
|
|
return [ip, `::ffff:${ip}`];
|
|
}
|
|
return [ip];
|
|
};
|
|
|
|
const normalizedIPVariants = normalizeIP(ip);
|
|
if (normalizedIPVariants.length === 0) return false;
|
|
|
|
const expandedPatterns = patterns.flatMap(normalizeIP);
|
|
return normalizedIPVariants.some((ipVariant) =>
|
|
expandedPatterns.some((pattern) => plugins.minimatch(ipVariant, pattern))
|
|
);
|
|
};
|
|
|
|
// Helper: Check if an IP is allowed considering allowed and blocked glob patterns
|
|
const isGlobIPAllowed = (ip: string, allowed: string[], blocked: string[] = []): boolean => {
|
|
if (!ip) return false;
|
|
if (blocked.length > 0 && isAllowed(ip, blocked)) return false;
|
|
return isAllowed(ip, allowed);
|
|
};
|
|
|
|
// Helper: Generate a unique connection ID
|
|
const generateConnectionId = (): string => {
|
|
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
|
};
|
|
|
|
// Helper: Check if a buffer contains a TLS handshake
|
|
const isTlsHandshake = (buffer: Buffer): boolean => {
|
|
return buffer.length > 0 && buffer[0] === 22; // ContentType.handshake
|
|
};
|
|
|
|
// Helper: Ensure timeout values don't exceed Node.js max safe integer
|
|
const ensureSafeTimeout = (timeout: number): number => {
|
|
const MAX_SAFE_TIMEOUT = 2147483647; // Maximum safe value (2^31 - 1)
|
|
return Math.min(Math.floor(timeout), MAX_SAFE_TIMEOUT);
|
|
};
|
|
|
|
// Helper: Generate a slightly randomized timeout to prevent thundering herd
|
|
const randomizeTimeout = (baseTimeout: number, variationPercent: number = 5): number => {
|
|
const safeBaseTimeout = ensureSafeTimeout(baseTimeout);
|
|
const variation = safeBaseTimeout * (variationPercent / 100);
|
|
return ensureSafeTimeout(safeBaseTimeout + Math.floor(Math.random() * variation * 2) - variation);
|
|
};
|
|
|
|
export class PortProxy {
|
|
private netServers: plugins.net.Server[] = [];
|
|
settings: IPortProxySettings;
|
|
private connectionRecords: Map<string, IConnectionRecord> = new Map();
|
|
private connectionLogger: NodeJS.Timeout | null = null;
|
|
private isShuttingDown: boolean = false;
|
|
|
|
// Map to track round robin indices for each domain config
|
|
private domainTargetIndices: Map<IDomainConfig, number> = new Map();
|
|
|
|
// Enhanced stats tracking
|
|
private terminationStats: {
|
|
incoming: Record<string, number>;
|
|
outgoing: Record<string, number>;
|
|
} = {
|
|
incoming: {},
|
|
outgoing: {},
|
|
};
|
|
|
|
// Connection tracking by IP for rate limiting
|
|
private connectionsByIP: Map<string, Set<string>> = new Map();
|
|
private connectionRateByIP: Map<string, number[]> = new Map();
|
|
|
|
constructor(settingsArg: IPortProxySettings) {
|
|
// Set reasonable defaults for all settings
|
|
this.settings = {
|
|
...settingsArg,
|
|
targetIP: settingsArg.targetIP || 'localhost',
|
|
|
|
// Timeout settings with reasonable defaults
|
|
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial handshake
|
|
socketTimeout: ensureSafeTimeout(settingsArg.socketTimeout || 3600000), // 1 hour socket timeout
|
|
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
|
maxConnectionLifetime: ensureSafeTimeout(settingsArg.maxConnectionLifetime || 86400000), // 24 hours default
|
|
inactivityTimeout: ensureSafeTimeout(settingsArg.inactivityTimeout || 14400000), // 4 hours inactivity timeout
|
|
|
|
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
|
|
|
// Socket optimization settings
|
|
noDelay: settingsArg.noDelay !== undefined ? settingsArg.noDelay : true,
|
|
keepAlive: settingsArg.keepAlive !== undefined ? settingsArg.keepAlive : true,
|
|
keepAliveInitialDelay: settingsArg.keepAliveInitialDelay || 10000, // 10 seconds (reduced for responsiveness)
|
|
maxPendingDataSize: settingsArg.maxPendingDataSize || 10 * 1024 * 1024, // 10MB to handle large TLS handshakes
|
|
|
|
// Feature flags
|
|
disableInactivityCheck: settingsArg.disableInactivityCheck || false,
|
|
enableKeepAliveProbes: settingsArg.enableKeepAliveProbes !== undefined
|
|
? settingsArg.enableKeepAliveProbes : true, // Enable by default
|
|
enableDetailedLogging: settingsArg.enableDetailedLogging || false,
|
|
enableTlsDebugLogging: settingsArg.enableTlsDebugLogging || false,
|
|
enableRandomizedTimeouts: settingsArg.enableRandomizedTimeouts || false, // Disable randomization by default
|
|
|
|
// Rate limiting defaults
|
|
maxConnectionsPerIP: settingsArg.maxConnectionsPerIP || 100, // 100 connections per IP
|
|
connectionRateLimitPerMinute: settingsArg.connectionRateLimitPerMinute || 300, // 300 per minute
|
|
|
|
// Enhanced keep-alive settings
|
|
keepAliveTreatment: settingsArg.keepAliveTreatment || 'extended', // Extended by default
|
|
keepAliveInactivityMultiplier: settingsArg.keepAliveInactivityMultiplier || 6, // 6x normal inactivity timeout
|
|
extendedKeepAliveLifetime: settingsArg.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000, // 7 days
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Get connections count by IP
|
|
*/
|
|
private getConnectionCountByIP(ip: string): number {
|
|
return this.connectionsByIP.get(ip)?.size || 0;
|
|
}
|
|
|
|
/**
|
|
* Check and update connection rate for an IP
|
|
*/
|
|
private checkConnectionRate(ip: string): boolean {
|
|
const now = Date.now();
|
|
const minute = 60 * 1000;
|
|
|
|
if (!this.connectionRateByIP.has(ip)) {
|
|
this.connectionRateByIP.set(ip, [now]);
|
|
return true;
|
|
}
|
|
|
|
// Get timestamps and filter out entries older than 1 minute
|
|
const timestamps = this.connectionRateByIP.get(ip)!.filter((time) => now - time < minute);
|
|
timestamps.push(now);
|
|
this.connectionRateByIP.set(ip, timestamps);
|
|
|
|
// Check if rate exceeds limit
|
|
return timestamps.length <= this.settings.connectionRateLimitPerMinute!;
|
|
}
|
|
|
|
/**
|
|
* Track connection by IP
|
|
*/
|
|
private trackConnectionByIP(ip: string, connectionId: string): void {
|
|
if (!this.connectionsByIP.has(ip)) {
|
|
this.connectionsByIP.set(ip, new Set());
|
|
}
|
|
this.connectionsByIP.get(ip)!.add(connectionId);
|
|
}
|
|
|
|
/**
|
|
* Remove connection tracking for an IP
|
|
*/
|
|
private removeConnectionByIP(ip: string, connectionId: string): void {
|
|
if (this.connectionsByIP.has(ip)) {
|
|
const connections = this.connectionsByIP.get(ip)!;
|
|
connections.delete(connectionId);
|
|
if (connections.size === 0) {
|
|
this.connectionsByIP.delete(ip);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Track connection termination statistic
|
|
*/
|
|
private incrementTerminationStat(side: 'incoming' | 'outgoing', reason: string): void {
|
|
this.terminationStats[side][reason] = (this.terminationStats[side][reason] || 0) + 1;
|
|
}
|
|
|
|
/**
|
|
* Cleans up a connection record.
|
|
* 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 cleanupConnection(record: IConnectionRecord, reason: string = 'normal'): void {
|
|
if (!record.connectionClosed) {
|
|
record.connectionClosed = true;
|
|
|
|
// Track connection termination
|
|
this.removeConnectionByIP(record.remoteIP, record.id);
|
|
|
|
if (record.cleanupTimer) {
|
|
clearTimeout(record.cleanupTimer);
|
|
record.cleanupTimer = undefined;
|
|
}
|
|
|
|
// Detailed logging data
|
|
const duration = Date.now() - record.incomingStartTime;
|
|
const bytesReceived = record.bytesReceived;
|
|
const bytesSent = record.bytesSent;
|
|
|
|
try {
|
|
if (!record.incoming.destroyed) {
|
|
// Try graceful shutdown first, then force destroy after a short timeout
|
|
record.incoming.end();
|
|
const incomingTimeout = setTimeout(() => {
|
|
try {
|
|
if (record && !record.incoming.destroyed) {
|
|
record.incoming.destroy();
|
|
}
|
|
} catch (err) {
|
|
console.log(`[${record.id}] Error destroying incoming socket: ${err}`);
|
|
}
|
|
}, 1000);
|
|
|
|
// Ensure the timeout doesn't block Node from exiting
|
|
if (incomingTimeout.unref) {
|
|
incomingTimeout.unref();
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.log(`[${record.id}] Error closing incoming socket: ${err}`);
|
|
try {
|
|
if (!record.incoming.destroyed) {
|
|
record.incoming.destroy();
|
|
}
|
|
} catch (destroyErr) {
|
|
console.log(`[${record.id}] Error destroying incoming socket: ${destroyErr}`);
|
|
}
|
|
}
|
|
|
|
try {
|
|
if (record.outgoing && !record.outgoing.destroyed) {
|
|
// Try graceful shutdown first, then force destroy after a short timeout
|
|
record.outgoing.end();
|
|
const outgoingTimeout = setTimeout(() => {
|
|
try {
|
|
if (record && record.outgoing && !record.outgoing.destroyed) {
|
|
record.outgoing.destroy();
|
|
}
|
|
} catch (err) {
|
|
console.log(`[${record.id}] Error destroying outgoing socket: ${err}`);
|
|
}
|
|
}, 1000);
|
|
|
|
// Ensure the timeout doesn't block Node from exiting
|
|
if (outgoingTimeout.unref) {
|
|
outgoingTimeout.unref();
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.log(`[${record.id}] Error closing outgoing socket: ${err}`);
|
|
try {
|
|
if (record.outgoing && !record.outgoing.destroyed) {
|
|
record.outgoing.destroy();
|
|
}
|
|
} catch (destroyErr) {
|
|
console.log(`[${record.id}] Error destroying outgoing socket: ${destroyErr}`);
|
|
}
|
|
}
|
|
|
|
// Clear pendingData to avoid memory leaks
|
|
record.pendingData = [];
|
|
record.pendingDataSize = 0;
|
|
|
|
// Remove the record from the tracking map
|
|
this.connectionRecords.delete(record.id);
|
|
|
|
// Log connection details
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
|
` Duration: ${plugins.prettyMs(
|
|
duration
|
|
)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
|
`TLS: ${record.isTLS ? 'Yes' : 'No'}, Keep-Alive: ${record.hasKeepAlive ? 'Yes' : 'No'}`
|
|
);
|
|
} else {
|
|
console.log(
|
|
`[${record.id}] Connection from ${record.remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Update connection activity timestamp
|
|
*/
|
|
private updateActivity(record: IConnectionRecord): void {
|
|
record.lastActivity = Date.now();
|
|
|
|
// Clear any inactivity warning
|
|
if (record.inactivityWarningIssued) {
|
|
record.inactivityWarningIssued = false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get target IP with round-robin support
|
|
*/
|
|
private getTargetIP(domainConfig: IDomainConfig): string {
|
|
if (domainConfig.targetIPs && domainConfig.targetIPs.length > 0) {
|
|
const currentIndex = this.domainTargetIndices.get(domainConfig) || 0;
|
|
const ip = domainConfig.targetIPs[currentIndex % domainConfig.targetIPs.length];
|
|
this.domainTargetIndices.set(domainConfig, currentIndex + 1);
|
|
return ip;
|
|
}
|
|
return this.settings.targetIP!;
|
|
}
|
|
|
|
/**
|
|
* Initiates cleanup once for a connection
|
|
*/
|
|
private initiateCleanupOnce(record: IConnectionRecord, reason: string = 'normal'): void {
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${record.id}] Connection cleanup initiated for ${record.remoteIP} (${reason})`);
|
|
}
|
|
|
|
if (record.incomingTerminationReason === null || record.incomingTerminationReason === undefined) {
|
|
record.incomingTerminationReason = reason;
|
|
this.incrementTerminationStat('incoming', reason);
|
|
}
|
|
|
|
this.cleanupConnection(record, reason);
|
|
}
|
|
|
|
/**
|
|
* Main method to start the proxy
|
|
*/
|
|
public async start() {
|
|
// Don't start if already shutting down
|
|
if (this.isShuttingDown) {
|
|
console.log("Cannot start PortProxy while it's shutting down");
|
|
return;
|
|
}
|
|
|
|
// Define a unified connection handler for all listening ports.
|
|
const connectionHandler = (socket: plugins.net.Socket) => {
|
|
if (this.isShuttingDown) {
|
|
socket.end();
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
|
|
const remoteIP = socket.remoteAddress || '';
|
|
const localPort = socket.localPort || 0; // The port on which this connection was accepted.
|
|
|
|
// Check rate limits
|
|
if (
|
|
this.settings.maxConnectionsPerIP &&
|
|
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP
|
|
) {
|
|
console.log(
|
|
`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`
|
|
);
|
|
socket.end();
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
|
|
if (this.settings.connectionRateLimitPerMinute && !this.checkConnectionRate(remoteIP)) {
|
|
console.log(
|
|
`Connection rejected from ${remoteIP}: Connection rate limit (${this.settings.connectionRateLimitPerMinute}/min) exceeded`
|
|
);
|
|
socket.end();
|
|
socket.destroy();
|
|
return;
|
|
}
|
|
|
|
// Apply socket optimizations
|
|
socket.setNoDelay(this.settings.noDelay);
|
|
|
|
// Create a unique connection ID and record
|
|
const connectionId = generateConnectionId();
|
|
const connectionRecord: IConnectionRecord = {
|
|
id: connectionId,
|
|
incoming: socket,
|
|
outgoing: null,
|
|
incomingStartTime: Date.now(),
|
|
lastActivity: Date.now(),
|
|
connectionClosed: false,
|
|
pendingData: [],
|
|
pendingDataSize: 0,
|
|
|
|
// Initialize enhanced tracking fields
|
|
bytesReceived: 0,
|
|
bytesSent: 0,
|
|
remoteIP: remoteIP,
|
|
localPort: localPort,
|
|
isTLS: false,
|
|
tlsHandshakeComplete: false,
|
|
hasReceivedInitialData: false,
|
|
hasKeepAlive: false, // Will set to true if keep-alive is applied
|
|
incomingTerminationReason: null,
|
|
outgoingTerminationReason: null
|
|
};
|
|
|
|
// Apply keep-alive settings if enabled
|
|
if (this.settings.keepAlive) {
|
|
socket.setKeepAlive(true, this.settings.keepAliveInitialDelay);
|
|
connectionRecord.hasKeepAlive = true; // Mark connection as having keep-alive
|
|
|
|
// Apply enhanced TCP keep-alive options if enabled
|
|
if (this.settings.enableKeepAliveProbes) {
|
|
try {
|
|
// These are platform-specific and may not be available
|
|
if ('setKeepAliveProbes' in socket) {
|
|
(socket as any).setKeepAliveProbes(10); // More aggressive probing
|
|
}
|
|
if ('setKeepAliveInterval' in socket) {
|
|
(socket as any).setKeepAliveInterval(1000); // 1 second interval between probes
|
|
}
|
|
} catch (err) {
|
|
// Ignore errors - these are optional enhancements
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Enhanced TCP keep-alive settings not supported: ${err}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Track connection by IP
|
|
this.trackConnectionByIP(remoteIP, connectionId);
|
|
this.connectionRecords.set(connectionId, connectionRecord);
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] New connection from ${remoteIP} on port ${localPort}. ` +
|
|
`Keep-Alive: ${connectionRecord.hasKeepAlive ? 'Enabled' : 'Disabled'}. ` +
|
|
`Active connections: ${this.connectionRecords.size}`
|
|
);
|
|
} else {
|
|
console.log(
|
|
`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`
|
|
);
|
|
}
|
|
|
|
let initialDataReceived = false;
|
|
let incomingTerminationReason: string | null = null;
|
|
let outgoingTerminationReason: string | null = null;
|
|
|
|
// Define initiateCleanupOnce for compatibility
|
|
const initiateCleanupOnce = (reason: string = 'normal') => {
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Connection cleanup initiated for ${remoteIP} (${reason})`);
|
|
}
|
|
if (incomingTerminationReason === null) {
|
|
incomingTerminationReason = reason;
|
|
connectionRecord.incomingTerminationReason = reason;
|
|
this.incrementTerminationStat('incoming', reason);
|
|
}
|
|
this.cleanupConnection(connectionRecord, reason);
|
|
};
|
|
|
|
// Helper to reject an incoming connection
|
|
const rejectIncomingConnection = (reason: string, logMessage: string) => {
|
|
console.log(`[${connectionId}] ${logMessage}`);
|
|
socket.end();
|
|
if (incomingTerminationReason === null) {
|
|
incomingTerminationReason = reason;
|
|
connectionRecord.incomingTerminationReason = reason;
|
|
this.incrementTerminationStat('incoming', reason);
|
|
}
|
|
this.cleanupConnection(connectionRecord, reason);
|
|
};
|
|
|
|
// Set an initial timeout for SNI data if needed
|
|
let initialTimeout: NodeJS.Timeout | null = null;
|
|
if (this.settings.sniEnabled) {
|
|
initialTimeout = setTimeout(() => {
|
|
if (!initialDataReceived) {
|
|
console.log(
|
|
`[${connectionId}] Initial data timeout (${this.settings.initialDataTimeout}ms) for connection from ${remoteIP} on port ${localPort}`
|
|
);
|
|
if (incomingTerminationReason === null) {
|
|
incomingTerminationReason = 'initial_timeout';
|
|
connectionRecord.incomingTerminationReason = 'initial_timeout';
|
|
this.incrementTerminationStat('incoming', 'initial_timeout');
|
|
}
|
|
socket.end();
|
|
this.cleanupConnection(connectionRecord, 'initial_timeout');
|
|
}
|
|
}, this.settings.initialDataTimeout!);
|
|
|
|
// Make sure timeout doesn't keep the process alive
|
|
if (initialTimeout.unref) {
|
|
initialTimeout.unref();
|
|
}
|
|
} else {
|
|
initialDataReceived = true;
|
|
connectionRecord.hasReceivedInitialData = true;
|
|
}
|
|
|
|
socket.on('error', (err: Error) => {
|
|
console.log(`[${connectionId}] Incoming socket error from ${remoteIP}: ${err.message}`);
|
|
});
|
|
|
|
// Track data for bytes counting
|
|
socket.on('data', (chunk: Buffer) => {
|
|
connectionRecord.bytesReceived += chunk.length;
|
|
this.updateActivity(connectionRecord);
|
|
|
|
// Check for TLS handshake if this is the first chunk
|
|
if (!connectionRecord.isTLS && isTlsHandshake(chunk)) {
|
|
connectionRecord.isTLS = true;
|
|
|
|
if (this.settings.enableTlsDebugLogging) {
|
|
console.log(
|
|
`[${connectionId}] TLS handshake detected from ${remoteIP}, ${chunk.length} bytes`
|
|
);
|
|
// Try to extract SNI and log detailed debug info
|
|
extractSNI(chunk, true);
|
|
}
|
|
}
|
|
});
|
|
|
|
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
|
|
const code = (err as any).code;
|
|
let reason = 'error';
|
|
|
|
const now = Date.now();
|
|
const connectionDuration = now - connectionRecord.incomingStartTime;
|
|
const lastActivityAge = now - connectionRecord.lastActivity;
|
|
|
|
if (code === 'ECONNRESET') {
|
|
reason = 'econnreset';
|
|
console.log(
|
|
`[${connectionId}] ECONNRESET on ${side} side from ${remoteIP}: ${
|
|
err.message
|
|
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
|
lastActivityAge
|
|
)} ago`
|
|
);
|
|
} else if (code === 'ETIMEDOUT') {
|
|
reason = 'etimedout';
|
|
console.log(
|
|
`[${connectionId}] ETIMEDOUT on ${side} side from ${remoteIP}: ${
|
|
err.message
|
|
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
|
lastActivityAge
|
|
)} ago`
|
|
);
|
|
} else {
|
|
console.log(
|
|
`[${connectionId}] Error on ${side} side from ${remoteIP}: ${
|
|
err.message
|
|
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
|
lastActivityAge
|
|
)} ago`
|
|
);
|
|
}
|
|
|
|
if (side === 'incoming' && incomingTerminationReason === null) {
|
|
incomingTerminationReason = reason;
|
|
connectionRecord.incomingTerminationReason = reason;
|
|
this.incrementTerminationStat('incoming', reason);
|
|
} else if (side === 'outgoing' && outgoingTerminationReason === null) {
|
|
outgoingTerminationReason = reason;
|
|
connectionRecord.outgoingTerminationReason = reason;
|
|
this.incrementTerminationStat('outgoing', reason);
|
|
}
|
|
|
|
initiateCleanupOnce(reason);
|
|
};
|
|
|
|
const handleClose = (side: 'incoming' | 'outgoing') => () => {
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Connection closed on ${side} side from ${remoteIP}`);
|
|
}
|
|
|
|
if (side === 'incoming' && incomingTerminationReason === null) {
|
|
incomingTerminationReason = 'normal';
|
|
connectionRecord.incomingTerminationReason = 'normal';
|
|
this.incrementTerminationStat('incoming', 'normal');
|
|
} else if (side === 'outgoing' && outgoingTerminationReason === null) {
|
|
outgoingTerminationReason = 'normal';
|
|
connectionRecord.outgoingTerminationReason = 'normal';
|
|
this.incrementTerminationStat('outgoing', 'normal');
|
|
// Record the time when outgoing socket closed.
|
|
connectionRecord.outgoingClosedTime = Date.now();
|
|
}
|
|
|
|
initiateCleanupOnce('closed_' + side);
|
|
};
|
|
|
|
/**
|
|
* Sets up the connection to the target host.
|
|
* @param serverName - The SNI hostname (unused when forcedDomain is provided).
|
|
* @param initialChunk - Optional initial data chunk.
|
|
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
|
* @param overridePort - If provided, use this port for the outgoing connection.
|
|
*/
|
|
const setupConnection = (
|
|
serverName: string,
|
|
initialChunk?: Buffer,
|
|
forcedDomain?: IDomainConfig,
|
|
overridePort?: number
|
|
) => {
|
|
// Clear the initial timeout since we've received data
|
|
if (initialTimeout) {
|
|
clearTimeout(initialTimeout);
|
|
initialTimeout = null;
|
|
}
|
|
|
|
// Mark that we've received initial data
|
|
initialDataReceived = true;
|
|
connectionRecord.hasReceivedInitialData = true;
|
|
|
|
// Check if this looks like a TLS handshake
|
|
if (initialChunk && isTlsHandshake(initialChunk)) {
|
|
connectionRecord.isTLS = true;
|
|
|
|
if (this.settings.enableTlsDebugLogging) {
|
|
console.log(
|
|
`[${connectionId}] TLS handshake detected in setup, ${initialChunk.length} bytes`
|
|
);
|
|
}
|
|
}
|
|
|
|
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
|
const domainConfig = forcedDomain
|
|
? forcedDomain
|
|
: serverName
|
|
? this.settings.domainConfigs.find((config) =>
|
|
config.domains.some((d) => plugins.minimatch(serverName, d))
|
|
)
|
|
: undefined;
|
|
|
|
// Save domain config in connection record
|
|
connectionRecord.domainConfig = domainConfig;
|
|
|
|
// IP validation is skipped if allowedIPs is empty
|
|
if (domainConfig) {
|
|
const effectiveAllowedIPs: string[] = [
|
|
...domainConfig.allowedIPs,
|
|
...(this.settings.defaultAllowedIPs || []),
|
|
];
|
|
const effectiveBlockedIPs: string[] = [
|
|
...(domainConfig.blockedIPs || []),
|
|
...(this.settings.defaultBlockedIPs || []),
|
|
];
|
|
|
|
// 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(
|
|
', '
|
|
)}`
|
|
);
|
|
}
|
|
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
|
if (
|
|
!isGlobIPAllowed(
|
|
remoteIP,
|
|
this.settings.defaultAllowedIPs,
|
|
this.settings.defaultBlockedIPs || []
|
|
)
|
|
) {
|
|
return rejectIncomingConnection(
|
|
'rejected',
|
|
`Connection rejected: IP ${remoteIP} not allowed by default allowed list`
|
|
);
|
|
}
|
|
}
|
|
|
|
const targetHost = domainConfig ? this.getTargetIP(domainConfig) : this.settings.targetIP!;
|
|
const connectionOptions: plugins.net.NetConnectOpts = {
|
|
host: targetHost,
|
|
port: overridePort !== undefined ? overridePort : this.settings.toPort,
|
|
};
|
|
if (this.settings.preserveSourceIP) {
|
|
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
|
}
|
|
|
|
// Pause the incoming socket to prevent buffer overflows
|
|
socket.pause();
|
|
|
|
// Temporary handler to collect data during connection setup
|
|
const tempDataHandler = (chunk: Buffer) => {
|
|
// Track bytes received
|
|
connectionRecord.bytesReceived += chunk.length;
|
|
|
|
// Check for TLS handshake
|
|
if (!connectionRecord.isTLS && isTlsHandshake(chunk)) {
|
|
connectionRecord.isTLS = true;
|
|
|
|
if (this.settings.enableTlsDebugLogging) {
|
|
console.log(
|
|
`[${connectionId}] TLS handshake detected in tempDataHandler, ${chunk.length} bytes`
|
|
);
|
|
}
|
|
}
|
|
|
|
// Check if adding this chunk would exceed the buffer limit
|
|
const newSize = connectionRecord.pendingDataSize + chunk.length;
|
|
|
|
if (this.settings.maxPendingDataSize && newSize > this.settings.maxPendingDataSize) {
|
|
console.log(
|
|
`[${connectionId}] Buffer limit exceeded for connection from ${remoteIP}: ${newSize} bytes > ${this.settings.maxPendingDataSize} bytes`
|
|
);
|
|
socket.end(); // Gracefully close the socket
|
|
return initiateCleanupOnce('buffer_limit_exceeded');
|
|
}
|
|
|
|
// Buffer the chunk and update the size counter
|
|
connectionRecord.pendingData.push(Buffer.from(chunk));
|
|
connectionRecord.pendingDataSize = newSize;
|
|
this.updateActivity(connectionRecord);
|
|
};
|
|
|
|
// Add the temp handler to capture all incoming data during connection setup
|
|
socket.on('data', tempDataHandler);
|
|
|
|
// Add initial chunk to pending data if present
|
|
if (initialChunk) {
|
|
connectionRecord.bytesReceived += initialChunk.length;
|
|
connectionRecord.pendingData.push(Buffer.from(initialChunk));
|
|
connectionRecord.pendingDataSize = initialChunk.length;
|
|
}
|
|
|
|
// Create the target socket but don't set up piping immediately
|
|
const targetSocket = plugins.net.connect(connectionOptions);
|
|
connectionRecord.outgoing = targetSocket;
|
|
connectionRecord.outgoingStartTime = Date.now();
|
|
|
|
// Apply socket optimizations
|
|
targetSocket.setNoDelay(this.settings.noDelay);
|
|
|
|
// Apply keep-alive settings to the outgoing connection as well
|
|
if (this.settings.keepAlive) {
|
|
targetSocket.setKeepAlive(true, this.settings.keepAliveInitialDelay);
|
|
|
|
// Apply enhanced TCP keep-alive options if enabled
|
|
if (this.settings.enableKeepAliveProbes) {
|
|
try {
|
|
if ('setKeepAliveProbes' in targetSocket) {
|
|
(targetSocket as any).setKeepAliveProbes(10);
|
|
}
|
|
if ('setKeepAliveInterval' in targetSocket) {
|
|
(targetSocket as any).setKeepAliveInterval(1000);
|
|
}
|
|
} catch (err) {
|
|
// Ignore errors - these are optional enhancements
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Enhanced TCP keep-alive not supported for outgoing socket: ${err}`);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Setup specific error handler for connection phase
|
|
targetSocket.once('error', (err) => {
|
|
// This handler runs only once during the initial connection phase
|
|
const code = (err as any).code;
|
|
console.log(
|
|
`[${connectionId}] Connection setup error to ${targetHost}:${connectionOptions.port}: ${err.message} (${code})`
|
|
);
|
|
|
|
// Resume the incoming socket to prevent it from hanging
|
|
socket.resume();
|
|
|
|
if (code === 'ECONNREFUSED') {
|
|
console.log(
|
|
`[${connectionId}] Target ${targetHost}:${connectionOptions.port} refused connection`
|
|
);
|
|
} else if (code === 'ETIMEDOUT') {
|
|
console.log(
|
|
`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} timed out`
|
|
);
|
|
} else if (code === 'ECONNRESET') {
|
|
console.log(
|
|
`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} was reset`
|
|
);
|
|
} else if (code === 'EHOSTUNREACH') {
|
|
console.log(`[${connectionId}] Host ${targetHost} is unreachable`);
|
|
}
|
|
|
|
// Clear any existing error handler after connection phase
|
|
targetSocket.removeAllListeners('error');
|
|
|
|
// Re-add the normal error handler for established connections
|
|
targetSocket.on('error', handleError('outgoing'));
|
|
|
|
if (outgoingTerminationReason === null) {
|
|
outgoingTerminationReason = 'connection_failed';
|
|
connectionRecord.outgoingTerminationReason = 'connection_failed';
|
|
this.incrementTerminationStat('outgoing', 'connection_failed');
|
|
}
|
|
|
|
// Clean up the connection
|
|
initiateCleanupOnce(`connection_failed_${code}`);
|
|
});
|
|
|
|
// Setup close handler
|
|
targetSocket.on('close', handleClose('outgoing'));
|
|
socket.on('close', handleClose('incoming'));
|
|
|
|
// Handle timeouts with keep-alive awareness
|
|
socket.on('timeout', () => {
|
|
// For keep-alive connections, just log a warning instead of closing
|
|
if (connectionRecord.hasKeepAlive) {
|
|
console.log(
|
|
`[${connectionId}] Timeout event on incoming keep-alive connection from ${remoteIP} after ${plugins.prettyMs(
|
|
this.settings.socketTimeout || 3600000
|
|
)}. Connection preserved.`
|
|
);
|
|
// Don't close the connection - just log
|
|
return;
|
|
}
|
|
|
|
// For non-keep-alive connections, proceed with normal cleanup
|
|
console.log(
|
|
`[${connectionId}] Timeout on incoming side from ${remoteIP} after ${plugins.prettyMs(
|
|
this.settings.socketTimeout || 3600000
|
|
)}`
|
|
);
|
|
if (incomingTerminationReason === null) {
|
|
incomingTerminationReason = 'timeout';
|
|
connectionRecord.incomingTerminationReason = 'timeout';
|
|
this.incrementTerminationStat('incoming', 'timeout');
|
|
}
|
|
initiateCleanupOnce('timeout_incoming');
|
|
});
|
|
|
|
targetSocket.on('timeout', () => {
|
|
// For keep-alive connections, just log a warning instead of closing
|
|
if (connectionRecord.hasKeepAlive) {
|
|
console.log(
|
|
`[${connectionId}] Timeout event on outgoing keep-alive connection from ${remoteIP} after ${plugins.prettyMs(
|
|
this.settings.socketTimeout || 3600000
|
|
)}. Connection preserved.`
|
|
);
|
|
// Don't close the connection - just log
|
|
return;
|
|
}
|
|
|
|
// For non-keep-alive connections, proceed with normal cleanup
|
|
console.log(
|
|
`[${connectionId}] Timeout on outgoing side from ${remoteIP} after ${plugins.prettyMs(
|
|
this.settings.socketTimeout || 3600000
|
|
)}`
|
|
);
|
|
if (outgoingTerminationReason === null) {
|
|
outgoingTerminationReason = 'timeout';
|
|
connectionRecord.outgoingTerminationReason = 'timeout';
|
|
this.incrementTerminationStat('outgoing', 'timeout');
|
|
}
|
|
initiateCleanupOnce('timeout_outgoing');
|
|
});
|
|
|
|
// Set appropriate timeouts, or disable for immortal keep-alive connections
|
|
if (connectionRecord.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal') {
|
|
// Disable timeouts completely for immortal connections
|
|
socket.setTimeout(0);
|
|
targetSocket.setTimeout(0);
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Disabled socket timeouts for immortal keep-alive connection`);
|
|
}
|
|
} else {
|
|
// Set normal timeouts for other connections
|
|
socket.setTimeout(ensureSafeTimeout(this.settings.socketTimeout || 3600000));
|
|
targetSocket.setTimeout(ensureSafeTimeout(this.settings.socketTimeout || 3600000));
|
|
}
|
|
|
|
// Track outgoing data for bytes counting
|
|
targetSocket.on('data', (chunk: Buffer) => {
|
|
connectionRecord.bytesSent += chunk.length;
|
|
this.updateActivity(connectionRecord);
|
|
});
|
|
|
|
// Wait for the outgoing connection to be ready before setting up piping
|
|
targetSocket.once('connect', () => {
|
|
// Clear the initial connection error handler
|
|
targetSocket.removeAllListeners('error');
|
|
|
|
// Add the normal error handler for established connections
|
|
targetSocket.on('error', handleError('outgoing'));
|
|
|
|
// Remove temporary data handler
|
|
socket.removeListener('data', tempDataHandler);
|
|
|
|
// Flush all pending data to target
|
|
if (connectionRecord.pendingData.length > 0) {
|
|
const combinedData = Buffer.concat(connectionRecord.pendingData);
|
|
targetSocket.write(combinedData, (err) => {
|
|
if (err) {
|
|
console.log(
|
|
`[${connectionId}] Error writing pending data to target: ${err.message}`
|
|
);
|
|
return initiateCleanupOnce('write_error');
|
|
}
|
|
|
|
// Now set up piping for future data and resume the socket
|
|
socket.pipe(targetSocket);
|
|
targetSocket.pipe(socket);
|
|
socket.resume(); // Resume the socket after piping is established
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
|
`${
|
|
serverName
|
|
? ` (SNI: ${serverName})`
|
|
: forcedDomain
|
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
|
: ''
|
|
}` +
|
|
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}, Keep-Alive: ${connectionRecord.hasKeepAlive ? 'Yes' : 'No'}`
|
|
);
|
|
} else {
|
|
console.log(
|
|
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
|
`${
|
|
serverName
|
|
? ` (SNI: ${serverName})`
|
|
: forcedDomain
|
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
|
: ''
|
|
}`
|
|
);
|
|
}
|
|
});
|
|
} else {
|
|
// No pending data, so just set up piping
|
|
socket.pipe(targetSocket);
|
|
targetSocket.pipe(socket);
|
|
socket.resume(); // Resume the socket after piping is established
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
|
`${
|
|
serverName
|
|
? ` (SNI: ${serverName})`
|
|
: forcedDomain
|
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
|
: ''
|
|
}` +
|
|
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}, Keep-Alive: ${connectionRecord.hasKeepAlive ? 'Yes' : 'No'}`
|
|
);
|
|
} else {
|
|
console.log(
|
|
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
|
`${
|
|
serverName
|
|
? ` (SNI: ${serverName})`
|
|
: forcedDomain
|
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
|
: ''
|
|
}`
|
|
);
|
|
}
|
|
}
|
|
|
|
// Clear the buffer now that we've processed it
|
|
connectionRecord.pendingData = [];
|
|
connectionRecord.pendingDataSize = 0;
|
|
|
|
// Add the renegotiation listener for SNI validation
|
|
if (serverName) {
|
|
socket.on('data', (renegChunk: Buffer) => {
|
|
if (renegChunk.length > 0 && renegChunk.readUInt8(0) === 22) {
|
|
try {
|
|
// Try to extract SNI from potential renegotiation
|
|
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
|
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
|
console.log(
|
|
`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`
|
|
);
|
|
initiateCleanupOnce('sni_mismatch');
|
|
} else if (newSNI && this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`
|
|
);
|
|
}
|
|
} catch (err) {
|
|
console.log(
|
|
`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`
|
|
);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
// Set connection timeout with simpler logic
|
|
if (connectionRecord.cleanupTimer) {
|
|
clearTimeout(connectionRecord.cleanupTimer);
|
|
}
|
|
|
|
// For immortal keep-alive connections, skip setting a timeout completely
|
|
if (connectionRecord.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal') {
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Keep-alive connection with immortal treatment - no max lifetime`);
|
|
}
|
|
// No cleanup timer for immortal connections
|
|
}
|
|
// For extended keep-alive connections, use extended timeout
|
|
else if (connectionRecord.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
|
|
const extendedTimeout = this.settings.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
const safeTimeout = ensureSafeTimeout(extendedTimeout);
|
|
|
|
connectionRecord.cleanupTimer = setTimeout(() => {
|
|
console.log(
|
|
`[${connectionId}] Keep-alive connection from ${remoteIP} exceeded extended lifetime (${plugins.prettyMs(
|
|
extendedTimeout
|
|
)}), forcing cleanup.`
|
|
);
|
|
initiateCleanupOnce('extended_lifetime');
|
|
}, safeTimeout);
|
|
|
|
// Make sure timeout doesn't keep the process alive
|
|
if (connectionRecord.cleanupTimer.unref) {
|
|
connectionRecord.cleanupTimer.unref();
|
|
}
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${connectionId}] Keep-alive connection with extended lifetime of ${plugins.prettyMs(extendedTimeout)}`);
|
|
}
|
|
}
|
|
// For standard connections, use normal timeout
|
|
else {
|
|
// Use domain-specific timeout if available, otherwise use default
|
|
const connectionTimeout = connectionRecord.domainConfig?.connectionTimeout || this.settings.maxConnectionLifetime!;
|
|
const safeTimeout = ensureSafeTimeout(connectionTimeout);
|
|
|
|
connectionRecord.cleanupTimer = setTimeout(() => {
|
|
console.log(
|
|
`[${connectionId}] Connection from ${remoteIP} exceeded max lifetime (${plugins.prettyMs(
|
|
connectionTimeout
|
|
)}), forcing cleanup.`
|
|
);
|
|
initiateCleanupOnce('connection_timeout');
|
|
}, safeTimeout);
|
|
|
|
// Make sure timeout doesn't keep the process alive
|
|
if (connectionRecord.cleanupTimer.unref) {
|
|
connectionRecord.cleanupTimer.unref();
|
|
}
|
|
}
|
|
|
|
// Mark TLS handshake as complete for TLS connections
|
|
if (connectionRecord.isTLS) {
|
|
connectionRecord.tlsHandshakeComplete = true;
|
|
|
|
if (this.settings.enableTlsDebugLogging) {
|
|
console.log(
|
|
`[${connectionId}] TLS handshake complete for connection from ${remoteIP}`
|
|
);
|
|
}
|
|
}
|
|
});
|
|
};
|
|
|
|
// --- PORT RANGE-BASED HANDLING ---
|
|
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
|
if (
|
|
this.settings.globalPortRanges &&
|
|
isPortInRanges(localPort, this.settings.globalPortRanges)
|
|
) {
|
|
if (this.settings.forwardAllGlobalRanges) {
|
|
if (
|
|
this.settings.defaultAllowedIPs &&
|
|
this.settings.defaultAllowedIPs.length > 0 &&
|
|
!isAllowed(remoteIP, this.settings.defaultAllowedIPs)
|
|
) {
|
|
console.log(
|
|
`[${connectionId}] Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`
|
|
);
|
|
socket.end();
|
|
return;
|
|
}
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`
|
|
);
|
|
}
|
|
setupConnection(
|
|
'',
|
|
undefined,
|
|
{
|
|
domains: ['global'],
|
|
allowedIPs: this.settings.defaultAllowedIPs || [],
|
|
blockedIPs: this.settings.defaultBlockedIPs || [],
|
|
targetIPs: [this.settings.targetIP!],
|
|
portRanges: [],
|
|
},
|
|
localPort
|
|
);
|
|
return;
|
|
} else {
|
|
// Attempt to find a matching forced domain config based on the local port.
|
|
const forcedDomain = this.settings.domainConfigs.find(
|
|
(domain) =>
|
|
domain.portRanges &&
|
|
domain.portRanges.length > 0 &&
|
|
isPortInRanges(localPort, domain.portRanges)
|
|
);
|
|
if (forcedDomain) {
|
|
const effectiveAllowedIPs: string[] = [
|
|
...forcedDomain.allowedIPs,
|
|
...(this.settings.defaultAllowedIPs || []),
|
|
];
|
|
const effectiveBlockedIPs: string[] = [
|
|
...(forcedDomain.blockedIPs || []),
|
|
...(this.settings.defaultBlockedIPs || []),
|
|
];
|
|
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
|
console.log(
|
|
`[${connectionId}] Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(
|
|
', '
|
|
)} on port ${localPort}.`
|
|
);
|
|
socket.end();
|
|
return;
|
|
}
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(
|
|
', '
|
|
)}.`
|
|
);
|
|
}
|
|
setupConnection('', undefined, forcedDomain, localPort);
|
|
return;
|
|
}
|
|
// Fall through to SNI/default handling if no forced domain config is found.
|
|
}
|
|
}
|
|
|
|
// --- FALLBACK: SNI-BASED HANDLING (or default when SNI is disabled) ---
|
|
if (this.settings.sniEnabled) {
|
|
initialDataReceived = false;
|
|
|
|
socket.once('data', (chunk: Buffer) => {
|
|
if (initialTimeout) {
|
|
clearTimeout(initialTimeout);
|
|
initialTimeout = null;
|
|
}
|
|
|
|
initialDataReceived = true;
|
|
|
|
// Try to extract SNI
|
|
let serverName = '';
|
|
|
|
if (isTlsHandshake(chunk)) {
|
|
connectionRecord.isTLS = true;
|
|
|
|
if (this.settings.enableTlsDebugLogging) {
|
|
console.log(
|
|
`[${connectionId}] Extracting SNI from TLS handshake, ${chunk.length} bytes`
|
|
);
|
|
}
|
|
|
|
serverName = extractSNI(chunk, this.settings.enableTlsDebugLogging) || '';
|
|
}
|
|
|
|
// Lock the connection to the negotiated SNI.
|
|
connectionRecord.lockedDomain = serverName;
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(
|
|
`[${connectionId}] Received connection from ${remoteIP} with SNI: ${
|
|
serverName || '(empty)'
|
|
}`
|
|
);
|
|
}
|
|
|
|
setupConnection(serverName, chunk);
|
|
});
|
|
} else {
|
|
initialDataReceived = true;
|
|
connectionRecord.hasReceivedInitialData = true;
|
|
|
|
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`
|
|
);
|
|
}
|
|
|
|
setupConnection('');
|
|
}
|
|
};
|
|
|
|
// --- SETUP LISTENERS ---
|
|
// Determine which ports to listen on.
|
|
const listeningPorts = new Set<number>();
|
|
if (this.settings.globalPortRanges && this.settings.globalPortRanges.length > 0) {
|
|
// Listen on every port defined by the global ranges.
|
|
for (const range of this.settings.globalPortRanges) {
|
|
for (let port = range.from; port <= range.to; port++) {
|
|
listeningPorts.add(port);
|
|
}
|
|
}
|
|
// Also ensure the default fromPort is listened to if it isn't already in the ranges.
|
|
listeningPorts.add(this.settings.fromPort);
|
|
} else {
|
|
listeningPorts.add(this.settings.fromPort);
|
|
}
|
|
|
|
// Create a server for each port.
|
|
for (const port of listeningPorts) {
|
|
const server = plugins.net.createServer(connectionHandler).on('error', (err: Error) => {
|
|
console.log(`Server Error on port ${port}: ${err.message}`);
|
|
});
|
|
server.listen(port, () => {
|
|
console.log(
|
|
`PortProxy -> OK: Now listening on port ${port}${
|
|
this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''
|
|
}`
|
|
);
|
|
});
|
|
this.netServers.push(server);
|
|
}
|
|
|
|
// Log active connection count, longest running durations, and run parity checks periodically
|
|
this.connectionLogger = setInterval(() => {
|
|
// Immediately return if shutting down
|
|
if (this.isShuttingDown) return;
|
|
|
|
const now = Date.now();
|
|
let maxIncoming = 0;
|
|
let maxOutgoing = 0;
|
|
let tlsConnections = 0;
|
|
let nonTlsConnections = 0;
|
|
let completedTlsHandshakes = 0;
|
|
let pendingTlsHandshakes = 0;
|
|
let keepAliveConnections = 0;
|
|
|
|
// Create a copy of the keys to avoid modification during iteration
|
|
const connectionIds = [...this.connectionRecords.keys()];
|
|
|
|
for (const id of connectionIds) {
|
|
const record = this.connectionRecords.get(id);
|
|
if (!record) continue;
|
|
|
|
// Track connection stats
|
|
if (record.isTLS) {
|
|
tlsConnections++;
|
|
if (record.tlsHandshakeComplete) {
|
|
completedTlsHandshakes++;
|
|
} else {
|
|
pendingTlsHandshakes++;
|
|
}
|
|
} else {
|
|
nonTlsConnections++;
|
|
}
|
|
|
|
if (record.hasKeepAlive) {
|
|
keepAliveConnections++;
|
|
}
|
|
|
|
maxIncoming = Math.max(maxIncoming, now - record.incomingStartTime);
|
|
if (record.outgoingStartTime) {
|
|
maxOutgoing = Math.max(maxOutgoing, now - record.outgoingStartTime);
|
|
}
|
|
|
|
// Parity check: if outgoing socket closed and incoming remains active
|
|
if (
|
|
record.outgoingClosedTime &&
|
|
!record.incoming.destroyed &&
|
|
!record.connectionClosed &&
|
|
now - record.outgoingClosedTime > 120000
|
|
) {
|
|
const remoteIP = record.remoteIP;
|
|
console.log(
|
|
`[${id}] Parity check: Incoming socket for ${remoteIP} still active ${plugins.prettyMs(
|
|
now - record.outgoingClosedTime
|
|
)} after outgoing closed.`
|
|
);
|
|
this.cleanupConnection(record, 'parity_check');
|
|
}
|
|
|
|
// Check for stalled connections waiting for initial data
|
|
if (
|
|
!record.hasReceivedInitialData &&
|
|
now - record.incomingStartTime > this.settings.initialDataTimeout! / 2
|
|
) {
|
|
console.log(
|
|
`[${id}] Warning: Connection from ${
|
|
record.remoteIP
|
|
} has not received initial data after ${plugins.prettyMs(
|
|
now - record.incomingStartTime
|
|
)}`
|
|
);
|
|
}
|
|
|
|
// Skip inactivity check if disabled or for immortal keep-alive connections
|
|
if (!this.settings.disableInactivityCheck &&
|
|
!(record.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal')) {
|
|
|
|
const inactivityTime = now - record.lastActivity;
|
|
|
|
// Use extended timeout for extended-treatment keep-alive connections
|
|
let effectiveTimeout = this.settings.inactivityTimeout!;
|
|
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
|
|
const multiplier = this.settings.keepAliveInactivityMultiplier || 6;
|
|
effectiveTimeout = effectiveTimeout * multiplier;
|
|
}
|
|
|
|
if (inactivityTime > effectiveTimeout && !record.connectionClosed) {
|
|
// For keep-alive connections, issue a warning first
|
|
if (record.hasKeepAlive && !record.inactivityWarningIssued) {
|
|
console.log(
|
|
`[${id}] Warning: Keep-alive connection from ${record.remoteIP} inactive for ${plugins.prettyMs(inactivityTime)}. ` +
|
|
`Will close in 10 minutes if no activity.`
|
|
);
|
|
|
|
// Set warning flag and add grace period
|
|
record.inactivityWarningIssued = true;
|
|
record.lastActivity = now - (effectiveTimeout - 600000);
|
|
|
|
// Try to stimulate activity with a probe packet
|
|
if (record.outgoing && !record.outgoing.destroyed) {
|
|
try {
|
|
record.outgoing.write(Buffer.alloc(0));
|
|
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${id}] Sent probe packet to test keep-alive connection`);
|
|
}
|
|
} catch (err) {
|
|
console.log(`[${id}] Error sending probe packet: ${err}`);
|
|
}
|
|
}
|
|
} else {
|
|
// For non-keep-alive or after warning, close the connection
|
|
console.log(
|
|
`[${id}] Inactivity check: No activity on connection from ${record.remoteIP} ` +
|
|
`for ${plugins.prettyMs(inactivityTime)}.` +
|
|
(record.hasKeepAlive ? ' Despite keep-alive being enabled.' : '')
|
|
);
|
|
this.cleanupConnection(record, 'inactivity');
|
|
}
|
|
} else if (inactivityTime <= effectiveTimeout && record.inactivityWarningIssued) {
|
|
// If activity detected after warning, clear the warning
|
|
if (this.settings.enableDetailedLogging) {
|
|
console.log(`[${id}] Connection activity detected after inactivity warning, resetting warning`);
|
|
}
|
|
record.inactivityWarningIssued = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Log detailed stats periodically
|
|
console.log(
|
|
`Active connections: ${this.connectionRecords.size}. ` +
|
|
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), ` +
|
|
`Non-TLS=${nonTlsConnections}, KeepAlive=${keepAliveConnections}. ` +
|
|
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(
|
|
maxOutgoing
|
|
)}. ` +
|
|
`Termination stats: ${JSON.stringify({
|
|
IN: this.terminationStats.incoming,
|
|
OUT: this.terminationStats.outgoing,
|
|
})}`
|
|
);
|
|
}, this.settings.inactivityCheckInterval || 60000);
|
|
|
|
// Make sure the interval doesn't keep the process alive
|
|
if (this.connectionLogger.unref) {
|
|
this.connectionLogger.unref();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Gracefully shut down the proxy
|
|
*/
|
|
public async stop() {
|
|
console.log('PortProxy shutting down...');
|
|
this.isShuttingDown = true;
|
|
|
|
// Stop accepting new connections
|
|
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
|
(server) =>
|
|
new Promise<void>((resolve) => {
|
|
if (!server.listening) {
|
|
resolve();
|
|
return;
|
|
}
|
|
server.close((err) => {
|
|
if (err) {
|
|
console.log(`Error closing server: ${err.message}`);
|
|
}
|
|
resolve();
|
|
});
|
|
})
|
|
);
|
|
|
|
// Stop the connection logger
|
|
if (this.connectionLogger) {
|
|
clearInterval(this.connectionLogger);
|
|
this.connectionLogger = null;
|
|
}
|
|
|
|
// Wait for servers to close
|
|
await Promise.all(closeServerPromises);
|
|
console.log('All servers closed. Cleaning up active connections...');
|
|
|
|
// Force destroy all active connections immediately
|
|
const connectionIds = [...this.connectionRecords.keys()];
|
|
console.log(`Cleaning up ${connectionIds.length} active connections...`);
|
|
|
|
// First pass: End all connections gracefully
|
|
for (const id of connectionIds) {
|
|
const record = this.connectionRecords.get(id);
|
|
if (record) {
|
|
try {
|
|
// Clear any timers
|
|
if (record.cleanupTimer) {
|
|
clearTimeout(record.cleanupTimer);
|
|
record.cleanupTimer = undefined;
|
|
}
|
|
|
|
// End sockets gracefully
|
|
if (record.incoming && !record.incoming.destroyed) {
|
|
record.incoming.end();
|
|
}
|
|
|
|
if (record.outgoing && !record.outgoing.destroyed) {
|
|
record.outgoing.end();
|
|
}
|
|
} catch (err) {
|
|
console.log(`Error during graceful connection end for ${id}: ${err}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Short delay to allow graceful ends to process
|
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
|
|
// Second pass: Force destroy everything
|
|
for (const id of connectionIds) {
|
|
const record = this.connectionRecords.get(id);
|
|
if (record) {
|
|
try {
|
|
// Remove all listeners to prevent memory leaks
|
|
if (record.incoming) {
|
|
record.incoming.removeAllListeners();
|
|
if (!record.incoming.destroyed) {
|
|
record.incoming.destroy();
|
|
}
|
|
}
|
|
|
|
if (record.outgoing) {
|
|
record.outgoing.removeAllListeners();
|
|
if (!record.outgoing.destroyed) {
|
|
record.outgoing.destroy();
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.log(`Error during forced connection destruction for ${id}: ${err}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Clear all tracking maps
|
|
this.connectionRecords.clear();
|
|
this.domainTargetIndices.clear();
|
|
this.connectionsByIP.clear();
|
|
this.connectionRateByIP.clear();
|
|
this.netServers = [];
|
|
|
|
// Reset termination stats
|
|
this.terminationStats = {
|
|
incoming: {},
|
|
outgoing: {},
|
|
};
|
|
|
|
console.log('PortProxy shutdown complete.');
|
|
}
|
|
} |