How CFnew's forwardTCP Function Handles Traffic Forwarding and Fallback
CFnew's forwardTCP function implements a resilient TCP-over-WebSocket proxy with automatic SOCKS5 downgrade, region-aware backup IP selection, and multi-layered fallback logic to ensure continuous traffic flow even when primary routes fail.
The forwardTCP function serves as the core traffic forwarding engine in the byJoey/cfnew repository, handling TCP and TCP-over-WebSocket connections for VLESS and Trojan protocols. This Cloudflare Worker implementation prioritizes connection reliability through sophisticated parameter normalization and intelligent fallback mechanisms that automatically activate when primary routes become unavailable. Located in 明文源吗 (lines 3155–3254), this function orchestrates the entire data path from client WebSocket to ultimate destination.
Parameter Normalization and Configuration Priority
Before establishing any connections, forwardTCP resolves effective configuration values by prioritizing request-specific parameters over global settings. This hierarchy ensures that per-request overrides take precedence while maintaining sane defaults.
In 明文源吗 at line 3156, the function computes effective values for fallback addressing, region selection, and SOCKS5 configuration:
const effectiveFallback = reqFallback || fallbackAddress;
const effectiveRegion = reqRegion || currentWorkerRegion;
const effectiveRegionMatching = reqRm !== null ? reqRm : enableRegionMatching;
const effectiveSocksConfig = reqSocksConfig || parsedSocks5Config;
const effectiveSocksEnabled = reqSocksConfig ? true : isSocksEnabled;
const initialData = toUint8Array(rawData);
This normalization pattern allows the same function to serve both VLESS and Trojan handlers while respecting per-connection preferences for routing and proxy behavior.
Connection Establishment with SOCKS5 Support
The connectAndSend helper function (lines 3164–3170) abstracts the transport layer complexity, enabling seamless switching between direct TCP and SOCKS5-tunneled connections.
The connectAndSend Implementation
This internal helper determines the connection strategy based on the useSocks parameter:
async function connectAndSend(address, port, useSocks = false) {
// If SOCKS5 is requested, establish tunnel via establishSocksConnection
// Otherwise, open plain TCP socket via connectTcpSocket
// Immediately write initialData to remote writer upon connection
}
When effectiveSocksEnabled is true and SOCKS downgrade is not configured, the function routes traffic through establishSocksConnection. For standard TCP forwarding, it invokes connectTcpSocket. Both paths immediately flush any buffered client data (initialData) to minimize latency.
Remote Socket Lifecycle Management
To handle connection churn and fallback activation, forwardTCP implements a wrapper-based lifecycle management system using detachIfCurrent and attachRemote.
detachIfCurrent and attachRemote
The detachIfCurrent helper (lines 3173–3178) clears stale socket references when connections are superseded, preventing race conditions during fallback transitions. Conversely, attachRemote (lines 3180–3195) stores the active socket and writer in remoteConnWrapper, initiates bidirectional stream plumbing via connectStreams, and registers cleanup handlers.
This architecture ensures that when a primary connection fails, the retry logic can cleanly detach the failed socket before attaching the fallback connection without leaking resources or corrupting stream state.
Retry and Fallback Logic
The retryConnection function (lines 3200–3244) implements the core resilience strategy, offering distinct paths for SOCKS5 downgrade scenarios and plain TCP failures.
SOCKS5 Downgrade Path
When enableSocksDowngrade is true and SOCKS is enabled, forwardTCP first attempts a SOCKS5 connection. If this attempt fails, the function automatically falls back to either the user-defined effectiveFallback address or a region-aware backup IP retrieved via getBestBackupIP. This downgrade capability ensures connectivity even when SOCKS5 proxies become unreachable.
Region-Aware Backup IP Selection
For environments without SOCKS5 or when downgrade is disabled, the fallback logic proceeds directly to backup selection. The function queries getBestBackupIP using the effectiveRegion and effectiveRegionMatching parameters to locate the optimal alternative route. Both branches ultimately invoke connectAndSend for the backup host and port, then attach the resulting socket through attachRemote.
Initial Connection Attempt and Error Handling
The execution flow begins with a direct connection attempt to the original host:portNum destination. In lines 3246–3254, the implementation attempts the primary route while registering a retry callback for later use:
try {
const { remoteSock: initialSocket, writer: initialWriter } = await connectAndSend(host, portNum, enableSocksDowngrade ? false : effectiveSocksEnabled);
attachRemote(initialSocket, initialWriter, () => {
detachIfCurrent(initialSocket, initialWriter);
retryConnection();
});
} catch (err) {
await retryConnection();
}
If the initial connectAndSend succeeds, the socket is attached with a closure callback that triggers retryConnection if the stream later terminates unexpectedly. If the initial attempt throws (due to DNS resolution failure or connection refusal), retryConnection executes immediately, activating the fallback chain without waiting for a mid-stream failure.
Stream Plumbing and WebSocket Integration
Once established, the connectStreams helper binds the remote TCP socket to the client WebSocket (ws), handling optional response headers (respHeader) and enforcing proper back-pressure management. This component ensures that the WebSocket closes gracefully when the remote socket terminates, preventing half-open connections and resource exhaustion.
Summary
- CFnew's
forwardTCPfunction in明文源吗(lines 3155–3254) serves as the primary TCP traffic forwarding mechanism for VLESS and Trojan protocols in Cloudflare Workers. - Parameter normalization prioritizes per-request settings over global configuration, enabling flexible routing decisions for individual connections.
- SOCKS5 downgrade support allows automatic fallback from SOCKS5 tunnels to direct TCP when proxy connections fail, enhancing reliability in restrictive network environments.
- Region-aware backup selection via
getBestBackupIPprovides intelligent fallback routing based on geographic proximity and matching rules. - Lifecycle management through
detachIfCurrentandattachRemoteensures clean socket transitions and prevents resource leaks during fallback operations.
Frequently Asked Questions
What triggers the fallback mechanism in CFnew's forwardTCP function?
The fallback mechanism activates under two conditions: when the initial connection attempt to the target host:portNum throws an immediate error (such as DNS failure or connection refusal), or when an established connection closes unexpectedly during data transfer. In the latter case, the retry callback registered via attachRemote invokes retryConnection to establish a new path using either the configured fallback address or a region-selected backup IP.
How does forwardTCP handle SOCKS5 connection failures?
When enableSocksDowngrade is enabled and SOCKS5 is active, forwardTCP attempts the primary SOCKS5 connection first. If establishSocksConnection fails, the function automatically downgrades to a direct TCP connection attempt. If the direct attempt also fails, the system proceeds to the fallback address or queries getBestBackupIP for a region-appropriate backup, ensuring multiple layers of redundancy for proxy-dependent deployments.
What is the difference between effectiveFallback and getBestBackupIP?
The effectiveFallback variable represents a user-defined static fallback address provided either through request parameters or global configuration, offering deterministic routing to a specific backup endpoint. In contrast, getBestBackupIP is a dynamic selection function that analyzes the effectiveRegion and effectiveRegionMatching settings to choose the optimal backup IP from a pool of available addresses, enabling geographic optimization and load distribution across multiple edge locations.
How does region matching affect traffic routing in forwardTCP?
Region matching influences the backup IP selection process when primary connections fail. The effectiveRegionMatching flag (derived from reqRm or enableRegionMatching) determines whether getBestBackupIP filters available backup addresses based on the effectiveRegion parameter. When enabled, the system prioritizes backup IPs geographically close to the specified region, reducing latency for fallback connections while respecting data sovereignty requirements.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →