-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathdirect.ts
110 lines (90 loc) · 2.73 KB
/
direct.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import net from 'net';
import dns from 'dns';
import { Buffer } from 'buffer';
import { URL } from 'url';
import { EventEmitter } from 'events';
import { countTargetBytes } from './utils/count_target_bytes';
import { Socket } from './socket';
export interface HandlerOpts {
localAddress?: string;
ipFamily?: number;
dnsLookup?: typeof dns['lookup'];
}
interface DirectOpts {
request: { url?: string };
sourceSocket: Socket;
head: Buffer;
server: EventEmitter & { log: (connectionId: unknown, str: string) => void };
handlerOpts: HandlerOpts;
}
/**
* Directly connects to the target.
* Client -> Apify (CONNECT) -> Web
* Client <- Apify (CONNECT) <- Web
*/
export const direct = (
{
request,
sourceSocket,
head,
server,
handlerOpts,
}: DirectOpts,
): void => {
const url = new URL(`connect://${request.url}`);
if (!url.hostname) {
throw new Error('Missing CONNECT hostname');
}
if (!url.port) {
throw new Error('Missing CONNECT port');
}
if (head.length > 0) {
// See comment in chain.ts
sourceSocket.unshift(head);
}
const options = {
port: Number(url.port),
host: url.hostname,
localAddress: handlerOpts.localAddress,
family: handlerOpts.ipFamily,
lookup: handlerOpts.dnsLookup,
};
if (options.host[0] === '[') {
options.host = options.host.slice(1, -1);
}
const targetSocket = net.createConnection(options, () => {
try {
sourceSocket.write(`HTTP/1.1 200 Connection Established\r\n\r\n`);
} catch (error) {
sourceSocket.destroy(error as Error);
}
});
countTargetBytes(sourceSocket, targetSocket);
sourceSocket.pipe(targetSocket);
targetSocket.pipe(sourceSocket);
// Once target socket closes forcibly, the source socket gets paused.
// We need to enable flowing, otherwise the socket would remain open indefinitely.
// Nothing would consume the data, we just want to close the socket.
targetSocket.on('close', () => {
sourceSocket.resume();
if (sourceSocket.writable) {
sourceSocket.end();
}
});
// Same here.
sourceSocket.on('close', () => {
targetSocket.resume();
if (targetSocket.writable) {
targetSocket.end();
}
});
const { proxyChainId } = sourceSocket;
targetSocket.on('error', (error) => {
server.log(proxyChainId, `Direct Destination Socket Error: ${error.stack}`);
sourceSocket.destroy();
});
sourceSocket.on('error', (error) => {
server.log(proxyChainId, `Direct Source Socket Error: ${error.stack}`);
targetSocket.destroy();
});
};