|
| 1 | +import http from 'http'; |
| 2 | +import net from 'net'; |
| 3 | +import { Buffer } from 'buffer'; |
| 4 | +import { URL } from 'url'; |
| 5 | +import { EventEmitter } from 'events'; |
| 6 | +import { SocksClient, SocksClientError, type SocksProxy } from 'socks'; |
| 7 | +import { countTargetBytes } from './utils/count_target_bytes'; |
| 8 | +import { Socket } from './socket'; |
| 9 | +import { createCustomStatusHttpResponse, socksErrorMessageToStatusCode } from './statuses'; |
| 10 | + |
| 11 | +export interface HandlerOpts { |
| 12 | + upstreamProxyUrlParsed: URL; |
| 13 | + customTag?: unknown; |
| 14 | +} |
| 15 | + |
| 16 | +interface ChainSocksOpts { |
| 17 | + request: http.IncomingMessage, |
| 18 | + sourceSocket: Socket; |
| 19 | + head: Buffer; |
| 20 | + server: EventEmitter & { log: (connectionId: unknown, str: string) => void }; |
| 21 | + handlerOpts: HandlerOpts; |
| 22 | +} |
| 23 | + |
| 24 | +const socksProtocolToVersionNumber = (protocol: string): 4 | 5 => { |
| 25 | + switch (protocol) { |
| 26 | + case 'socks4:': |
| 27 | + case 'socks4a:': |
| 28 | + return 4; |
| 29 | + default: |
| 30 | + return 5; |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +/** |
| 35 | + * Client -> Apify (CONNECT) -> Upstream (SOCKS) -> Web |
| 36 | + * Client <- Apify (CONNECT) <- Upstream (SOCKS) <- Web |
| 37 | + */ |
| 38 | +export const chainSocks = async ({ |
| 39 | + request, |
| 40 | + sourceSocket, |
| 41 | + head, |
| 42 | + server, |
| 43 | + handlerOpts, |
| 44 | +}: ChainSocksOpts): Promise<void> => { |
| 45 | + const { proxyChainId } = sourceSocket; |
| 46 | + |
| 47 | + const { hostname, port, username, password } = handlerOpts.upstreamProxyUrlParsed; |
| 48 | + |
| 49 | + const proxy: SocksProxy = { |
| 50 | + host: hostname, |
| 51 | + port: Number(port), |
| 52 | + type: socksProtocolToVersionNumber(handlerOpts.upstreamProxyUrlParsed.protocol), |
| 53 | + userId: username, |
| 54 | + password, |
| 55 | + }; |
| 56 | + |
| 57 | + if (head && head.length > 0) { |
| 58 | + // HTTP/1.1 has no defined semantics when sending payload along with CONNECT and servers can reject the request. |
| 59 | + // HTTP/2 only says that subsequent DATA frames must be transferred after HEADERS has been sent. |
| 60 | + // HTTP/3 says that all DATA frames should be transferred (implies pre-HEADERS data). |
| 61 | + // |
| 62 | + // Let's go with the HTTP/3 behavior. |
| 63 | + // There are also clients that send payload along with CONNECT to save milliseconds apparently. |
| 64 | + // Beware of upstream proxy servers that send out valid CONNECT responses with diagnostic data such as IPs! |
| 65 | + sourceSocket.unshift(head); |
| 66 | + } |
| 67 | + |
| 68 | + const url = new URL(`connect://${request.url}`); |
| 69 | + const destination = { |
| 70 | + port: Number(url.port), |
| 71 | + host: url.hostname, |
| 72 | + }; |
| 73 | + |
| 74 | + let targetSocket: net.Socket; |
| 75 | + |
| 76 | + try { |
| 77 | + const client = await SocksClient.createConnection({ |
| 78 | + proxy, |
| 79 | + command: 'connect', |
| 80 | + destination, |
| 81 | + }); |
| 82 | + targetSocket = client.socket; |
| 83 | + |
| 84 | + sourceSocket.write(`HTTP/1.1 200 Connection Established\r\n\r\n`); |
| 85 | + } catch (error) { |
| 86 | + const socksError = error as SocksClientError; |
| 87 | + server.log(proxyChainId, `Failed to connect to upstream SOCKS proxy ${socksError.stack}`); |
| 88 | + sourceSocket.end(createCustomStatusHttpResponse(socksErrorMessageToStatusCode(socksError.message), socksError.message)); |
| 89 | + return; |
| 90 | + } |
| 91 | + |
| 92 | + countTargetBytes(sourceSocket, targetSocket); |
| 93 | + |
| 94 | + sourceSocket.pipe(targetSocket); |
| 95 | + targetSocket.pipe(sourceSocket); |
| 96 | + |
| 97 | + // Once target socket closes forcibly, the source socket gets paused. |
| 98 | + // We need to enable flowing, otherwise the socket would remain open indefinitely. |
| 99 | + // Nothing would consume the data, we just want to close the socket. |
| 100 | + targetSocket.on('close', () => { |
| 101 | + sourceSocket.resume(); |
| 102 | + |
| 103 | + if (sourceSocket.writable) { |
| 104 | + sourceSocket.end(); |
| 105 | + } |
| 106 | + }); |
| 107 | + |
| 108 | + // Same here. |
| 109 | + sourceSocket.on('close', () => { |
| 110 | + targetSocket.resume(); |
| 111 | + |
| 112 | + if (targetSocket.writable) { |
| 113 | + targetSocket.end(); |
| 114 | + } |
| 115 | + }); |
| 116 | + |
| 117 | + targetSocket.on('error', (error) => { |
| 118 | + server.log(proxyChainId, `Chain SOCKS Destination Socket Error: ${error.stack}`); |
| 119 | + |
| 120 | + sourceSocket.destroy(); |
| 121 | + }); |
| 122 | + |
| 123 | + sourceSocket.on('error', (error) => { |
| 124 | + server.log(proxyChainId, `Chain SOCKS Source Socket Error: ${error.stack}`); |
| 125 | + |
| 126 | + targetSocket.destroy(); |
| 127 | + }); |
| 128 | +}; |
0 commit comments