-
Notifications
You must be signed in to change notification settings - Fork 2
/
connectionHandler.ts
50 lines (42 loc) · 1.56 KB
/
connectionHandler.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
import { InitialisedSocks5Connection, Socks5ConnectionStatus } from "./types";
import net from "net";
// The default connection handler
export default function (connection: InitialisedSocks5Connection, sendStatus: (status: keyof typeof Socks5ConnectionStatus) => void) {
if (connection.command !== 'connect') return sendStatus('COMMAND_NOT_SUPPORTED');
connection.socket.on('error', () => { }); // Ignore errors
const stream = net.createConnection({
host: connection.destAddress,
port: connection.destPort
});
stream.setNoDelay();
let streamOpened = false;
stream.on('error', (err: Error & { code: string }) => {
if (!streamOpened) {
switch (err.code) {
case 'EINVAL':
case 'ENOENT':
case 'ENOTFOUND':
case 'ETIMEDOUT':
case 'EADDRNOTAVAIL':
case 'EHOSTUNREACH':
sendStatus('HOST_UNREACHABLE');
break;
case 'ENETUNREACH':
sendStatus('NETWORK_UNREACHABLE')
break;
case 'ECONNREFUSED':
sendStatus('CONNECTION_REFUSED');
break;
default:
sendStatus('GENERAL_FAILURE');
}
}
})
stream.on('ready', () => {
streamOpened = true;
sendStatus('REQUEST_GRANTED');
connection.socket.pipe(stream).pipe(connection.socket);
})
connection.socket.on('close', () => stream.destroy());
return stream;
}