Translating a SOCKS5 Request into an HTTP Tunnel
Complete the parent CONNECT exchange, return a SOCKS reply to the client and only then relay application bytes.
A SOCKS5 front end can use an HTTP proxy as its onward transport. It acts as a SOCKS server toward the client and an HTTP CONNECT client toward the parent. The two control exchanges finish before the application stream begins.
The SOCKS CONNECT request already supplies the destination host or address and port. For an illustrative HTTP/1.1 parent exchange:
client → adapter: SOCKS5 CONNECT service.example.net:443
adapter → parent:
CONNECT service.example.net:443 HTTP/1.1
Host: service.example.net:443
parent → adapter: HTTP/1.1 200 Connection Established
[end of headers]
adapter → client: SOCKS5 success reply
client ↔ adapter ↔ parent ↔ service: application bytes
Translate the result at the boundary
The adapter completes any required parent authentication and waits for the CONNECT result. A successful 2xx response establishes the parent tunnel. Only then should it return the corresponding SOCKS success reply to the downstream client.
If the parent rejects the operation, send a defined SOCKS failure reply, then terminate the client connection promptly. SOCKS5 requires that closure within ten seconds of detecting the failure. Keep the parent's HTTP status as diagnostic information for the adapter. Forwarding that status line as application data would put an HTTP control message into a stream whose client expects SOCKS framing.
Before a successful CONNECT result, the parent is still speaking HTTP, including the framing of any challenge or error response. After a successful result's header delimiter, the connection becomes the tunnel; there is no HTTP response body to consume first.
Preserve the bytes after the headers
A read can contain the end of the parent headers and bytes from the destination together. Retain those extra bytes for the downstream application. Server-first protocols can greet immediately after their connection opens.
Once the SOCKS success reply has been sent, relay the application stream in both directions. The adapter does not need to alternate one client message with one server message, and it does not need to understand TLS records to forward them. Its protocol work was establishing and translating the two tunnel negotiations.