-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdispatcher.js
64 lines (52 loc) · 2.03 KB
/
dispatcher.js
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
import { generateRandomIP } from './ip.js';
import { createRandomSocket, createSocketFromHostname } from './socket.js'
import { Agent, buildConnector } from 'undici'
// taken from `fetch-socks`, many thanks
function resolvePort(protocol, port) {
return port ? Number.parseInt(port) : protocol === "http:" ? 80 : 443
}
export function createConnectorFromIP(ip, tlsOpts = {}, sockOpts = {}) {
const undiciConnect = buildConnector(tlsOpts)
return (options, callback) => {
let { protocol, hostname, port } = options;
createSocketFromHostname(
hostname,
resolvePort(protocol, port),
ip,
sockOpts
)
.then(httpSocket => undiciConnect({ ...options, httpSocket }, callback))
.catch(err => callback(err))
};
}
export function createRandomConnector(cidr, tlsOpts = {}, sockOpts = {}) {
const undiciConnect = buildConnector(tlsOpts)
return (options, callback) => {
let { protocol, hostname, port } = options;
createRandomSocket(
hostname,
resolvePort(protocol, port),
cidr,
sockOpts
)
.then(httpSocket => undiciConnect({ ...options, httpSocket }, callback))
.catch(err => callback(err))
};
}
export function createRandomStickyConnector(cidr, tlsOpts, options) {
const { bits, ...sockOpts } = options;
const ip = generateRandomIP(cidr, bits);
return createConnectorFromIP(ip, tlsOpts, sockOpts);
}
export function dispatcherFromIP(ip, options = {}) {
const { connect, ...rest } = options
return new Agent({ ...rest, connect: createConnectorFromIP(ip, connect, rest) })
}
export function randomStickyDispatcher(cidr, options = {}) {
const { connect, ...rest } = options
return new Agent({ ...rest, connect: createRandomStickyConnector(cidr, connect, rest) })
}
export function randomDispatcher(cidr, options = {}) {
const { connect, ...rest } = options
return new Agent({ ...rest, connect: createRandomConnector(cidr, connect, rest) })
}