What Do `parseWsPacketHeader()` and `forwardTCP()` Do in CFnew? WebSocket Proxy Architecture Explained
In the CFnew Cloudflare Workers proxy, parseWsPacketHeader() validates and extracts destination metadata from VLESS/Trojan WebSocket frames, while forwardTCP() establishes the downstream TCP connection and manages bidirectional data flow with automatic failover support.
The CFnew repository (byJoey/cfnew) implements a high-performance proxy layer running on Cloudflare Workers that bridges WebSocket clients to remote TCP servers. At the heart of this architecture sit two critical functions—parseWsPacketHeader() and forwardTCP()—which isolate protocol parsing from network forwarding to enable reliable, maintainable proxy operations.
Understanding parseWsPacketHeader() in CFnew
The parseWsPacketHeader() function serves as the protocol decoder for incoming WebSocket connections. Located in the snippets file (lines 556–617), this utility validates authentication tokens and extracts routing information embedded in the initial VLESS or Trojan-style protocol header.
VLESS Header Validation and Parsing
When a WebSocket data frame arrives at the Worker, parseWsPacketHeader() receives the raw Uint8Array chunk alongside the expected authentication token (at). The function performs strict length validation (requiring a minimum of 24 bytes) before decoding the packet structure:
- UUID Authentication: Validates the 16-byte VLESS user ID against the configured token.
- Command Extraction: Interprets the protocol command byte to determine the requested operation (TCP forwarding, UDP association, etc.).
- Address Resolution: Parses the address type byte (IPv4, IPv6, or domain name) and extracts the target hostname or IP address plus port number.
Return Values and Error Handling
Upon successful parsing, the function returns a descriptor object containing:
addressType: Integer indicating IPv4 (1), IPv6 (4), or domain (3)hostname: String representation of the target hostport: Integer port numberisUDP: Boolean flag for UDP vs TCP moderawIndex: Byte offset where the actual payload data begins (after the header)version: Protocol version bytehasError: Boolean error flagmessage: Descriptive error text when validation fails
// Located in snippets (lines 556-617)
const headerInfo = parseWsPacketHeader(chunk, at);
if (headerInfo.hasError) {
console.error('Header parsing failed:', headerInfo.message);
// Close connection or return error response
} else {
console.log('Target destination:', headerInfo.hostname, headerInfo.port);
// Proceed to traffic forwarding
}
Understanding forwardTCP() in CFnew
While parseWsPacketHeader() handles protocol semantics, forwardTCP() manages the actual network I/O. This function resides in the 明文源吗 file (lines 3155–3186) and implements the TCP bridge between the Cloudflare Worker and the remote destination.
TCP Connection Establishment
forwardTCP() accepts the parsed address components and immediately initiates a socket connection:
- Socket Creation: Establishes a native TCP connection to the resolved host and port (or optionally routes through a SOCKS5 proxy if configured).
- Early Data Flush: Writes any initial payload data (
rawData) that was included in the first WebSocket frame immediately after connection setup, reducing latency for protocols that send data in the initial handshake. - Resource Tracking: Stores the socket reference in
remoteConnWrapperfor lifecycle management and cleanup.
Bidirectional Stream Piping
After establishing connectivity, the function sets up asynchronous stream piping between the WebSocket (ws) and the remote TCP socket:
- Client-to-Server: Reads subsequent WebSocket frames and writes them to the TCP socket.
- Server-to-Client: Reads TCP socket responses and frames them back to the WebSocket client.
- Flow Control: Manages backpressure between the two transport layers to prevent memory exhaustion.
Fallback and Resilience Logic
Between lines 3220–3260 in the same source file, forwardTCP() implements sophisticated retry mechanisms:
- Primary Failure Detection: Catches connection timeouts and ECONNREFUSED errors.
- SOCKS5 Downgrade: Automatically attempts connection via an upstream SOCKS5 proxy if direct TCP fails.
- Region-Aware Failover: Consults
currentWorkerRegionand fallback address lists to route through backup IPs when the primary destination is unreachable. - Custom Fallback: Respects user-configured
fallbackAddressparameters for high-availability deployments.
// Located in 明文源吗 (lines 3155-3186)
await forwardTCP(
headerInfo.addressType,
headerInfo.hostname,
headerInfo.port,
payload, // rawData after header
serverSock, // WebSocket connection
null, // Optional response header
remoteConnWrapper,
fallbackAddress, // User-defined fallback
currentWorkerRegion,
regionMatchedBackupIP, // Optional region-specific backup
socks5Config, // Optional SOCKS5 configuration
requestFetcher // Optional fetch wrapper
);
How parseWsPacketHeader() and forwardTCP() Work Together
The two functions operate sequentially within the WebSocket request handler pipeline:
- Frame Reception: The Worker receives a binary WebSocket frame containing the full VLESS/Trojan request.
- Header Parsing:
parseWsPacketHeader()extracts the destination metadata and validates the authentication token. - Payload Segmentation: The Worker slices the remaining bytes after the header (
data.subarray(rawIndex)) to isolate the initial payload. - Connection Bridging:
forwardTCP()receives the parsed destination and payload, establishes the downstream socket, and begins bidirectional data transfer. - Error Recovery: If
forwardTCP()encounters connection failures, it automatically invokes the fallback chain without requiring re-parsing the header.
This separation of concerns allows parseWsPacketHeader() to remain agnostic of network implementation details, while forwardTCP() focuses purely on transport reliability and performance optimization.
Summary
parseWsPacketHeader()insnippets(lines 556–617) validates VLESS/Trojan protocol headers, extracts target addresses, and verifies authentication tokens.forwardTCP()in明文源吗(lines 3155–3186) manages TCP socket creation, writes early data, pipes bidirectional streams, and implements multi-layer fallback logic.- Together, these functions enable CFnew to proxy WebSocket traffic to arbitrary TCP destinations while maintaining high availability through automatic failover to backup IPs and SOCKS5 proxies.
- The architecture isolates protocol parsing from network operations, simplifying testing and extension for new proxy protocols.
Frequently Asked Questions
What protocol formats does parseWsPacketHeader() support?
According to the CFnew source code in snippets, parseWsPacketHeader() primarily handles the VLESS protocol format, which includes a 16-byte UUID for authentication, a command byte, an address type indicator, and variable-length destination addressing. The function validates the minimum 24-byte header structure and extracts routing metadata compatible with both TCP and UDP forwarding modes.
How does forwardTCP() handle connection timeouts?
As implemented in 明文源吗 (lines 3220–3260), forwardTCP() wraps the initial TCP connection attempt in try-catch logic that detects network-level failures. Upon timeout or connection refusal, it sequentially attempts SOCKS5 proxy routing, region-matched backup IPs, and finally a user-configured fallback address before returning an error to the client. This ensures high availability even when primary routes fail.
Can forwardTCP() route traffic through intermediary proxies?
Yes. The function signature includes a socks5Config parameter that, when provided, triggers SOCKS5 handshake logic before connecting to the final destination. This allows CFnew to chain connections through upstream proxy servers, effectively masking the Worker's origin IP or routing through corporate proxies. The SOCKS5 implementation supports both username/password and no-authentication modes.
Where are these functions located in the CFnew codebase?
parseWsPacketHeader() resides in the snippets file at lines 556–617, serving as a reusable utility for header parsing. forwardTCP() is located in the 明文源吗 file at lines 3155–3186, where it integrates directly with the main request handler and WebSocket upgrade logic. The snippets file essentially contains modularized versions of the core logic found in the full Worker script (明文源吗).
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 →